Skip to content

Commit

Permalink
feat: Make it easy to convert data to IDLValue and candid text format (
Browse files Browse the repository at this point in the history
…#502)

# Changes
- Add a method to convert Rust data to IDLValue and hence text-format Candid: `try_from_candid_type()`

---------

Co-authored-by: Yan Chen <[email protected]>
Co-authored-by: Yan Chen <[email protected]>
  • Loading branch information
3 people authored Dec 7, 2023
1 parent 2f70240 commit 16c167a
Showing 1 changed file with 27 additions and 1 deletion.
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

0 comments on commit 16c167a

Please sign in to comment.