Skip to main content

idl2json/
lib.rs

1//! Library of IDL (candid) to JSON conversion functions.
2#![warn(missing_docs)]
3#![deny(clippy::panic)]
4#![deny(clippy::unwrap_used)]
5#![deny(clippy::expect_used)]
6#![deny(clippy::unimplemented)] // Allowed in some specific places
7
8mod bytes;
9pub mod candid_types;
10pub mod polyfill;
11mod typed_conversion;
12mod untyped_conversion;
13
14use candid_parser::types::IDLProg;
15pub use serde_json::Value as JsonValue;
16pub use typed_conversion::{idl2json_with_weak_names, idl_args2json_with_weak_names};
17pub use untyped_conversion::{idl2json, idl_args2json};
18#[cfg(test)]
19mod test;
20
21/// Options for idl2json conversions
22#[derive(Default)]
23pub struct Idl2JsonOptions {
24    /// How to represent `Vec<u8>`
25    pub bytes_as: Option<BytesFormat>,
26    /// How to represent `Vec<u8>` of at least some given length.
27    pub long_bytes_as: Option<(usize, BytesFormat)>,
28    /// Type definitions.
29    ///
30    /// Note:
31    /// - An `IDLProg`  corresponds to a parsed `.did` file.
32    /// - Typically either no `IDLProg` is available or one `IDLProg`
33    ///   is provided, corresponding to the `.did` file of a canister
34    ///   and that one `.did` file has all required definitions.
35    /// - In rare cases, multiple IDLProgs are needed.  If so,
36    ///   `idl2json` will use the first match it finds.  It is the
37    ///   caller's responsibility to ensure that there are no conflicting definitions.
38    pub prog: Vec<IDLProg>,
39    /// Compact JSON, without formatting whitespace.
40    pub compact: bool,
41}
42
43/// Options for how to represent `Vec<u8>`
44#[derive(Copy, Clone, Eq, PartialEq, Default, Debug)]
45#[cfg_attr(feature = "clap", derive(clap::ArgEnum))]
46#[cfg_attr(feature = "clap", clap(rename_all = "kebab_case"))]
47pub enum BytesFormat {
48    /// Data is represented as an array of numbers: `[1,34,0]`
49    #[default]
50    Numbers,
51    /// Data is represented as hex: `"A4B7"`
52    Hex,
53    /// Data is represented hex ending in an elipsis with at most the given total number of characters.
54    /// E.g. `Ellipsis(7) -> "A5B8..."`
55    // Ellipsis(usize), // TODO
56    #[cfg(feature = "crypto")]
57    /// Data is hashed:  "sha512:abbabababababababbababababab"
58    Sha256,
59}