Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Make it easy to convert data to IDLValue and candid text format #502

Merged
merged 3 commits into from
Dec 7, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion rust/candid/src/types/value.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::types::number::{Int, Nat};
use crate::types::{Field, Label, Type, TypeEnv, TypeInner};
use crate::{Error, Result};
use crate::{CandidType, Error, Result};
use serde::de;
use serde::de::{Deserialize, Visitor};
use std::collections::HashMap;
Expand Down Expand Up @@ -335,6 +335,32 @@ impl IDLValue {
}
.into()
}

/// Converts data that implements [`CandidType`] into an [`IDLValue`].
///
/// # Example: Convert data to candid text format
/// ```
/// # use candid::{CandidType, IDLValue};
/// #[derive(CandidType)]
/// struct MyStruct {
/// a: u8,
/// b: String,
/// }
/// let my_struct = MyStruct { a: 42, b: "hello".to_string() };
/// let idl_value = IDLValue::try_from_candid_type(&my_struct).unwrap();
/// let expected_text = "record { a = 42 : nat8; b = \"hello\" }";
/// let actual_text = idl_value.to_string();
/// assert_eq!(expected_text, actual_text);
/// ```
pub fn try_from_candid_type<T>(data: &T) -> Result<Self>
where
T: CandidType,
{
use crate::Encode;
let blob = Encode!(data)?;
let args = IDLArgs::from_bytes_with_types(&blob, &TypeEnv::default(), &[T::ty()])?;
Ok(args.args[0].clone())
}
}

impl crate::CandidType for IDLValue {
Expand Down
Loading