Function bcs::to_bytes [−][src]
pub fn to_bytes<T: ?Sized>(value: &T) -> Result<Vec<u8>> where
T: Serialize,
Expand description
Serialize the given data structure as a Vec<u8>
of BCS.
Serialization can fail if T
’s implementation of Serialize
decides to
fail, if T
contains sequences which are longer than MAX_SEQUENCE_LENGTH
,
or if T
attempts to serialize an unsupported datatype such as a f32,
f64, or char.
Examples
use bcs::to_bytes; use serde::Serialize; #[derive(Serialize)] struct Ip([u8; 4]); #[derive(Serialize)] struct Port(u16); #[derive(Serialize)] struct Service { ip: Ip, port: Vec<Port>, connection_max: Option<u32>, enabled: bool, } let service = Service { ip: Ip([192, 168, 1, 1]), port: vec![Port(8001), Port(8002), Port(8003)], connection_max: Some(5000), enabled: false, }; let bytes = to_bytes(&service).unwrap(); let expected = vec![ 0xc0, 0xa8, 0x01, 0x01, 0x03, 0x41, 0x1f, 0x42, 0x1f, 0x43, 0x1f, 0x01, 0x88, 0x13, 0x00, 0x00, 0x00, ]; assert_eq!(bytes, expected);