overnet_core/
coding.rs

1// Copyright 2019 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! Message encode/decode helpers
6
7use anyhow::Error;
8
9/// Decode some bytes into a FIDL type
10pub fn decode_fidl<T: fidl::Persistable>(bytes: &mut [u8]) -> Result<T, Error> {
11    fidl::unpersist(bytes).map_err(Into::into)
12}
13
14/// Encode a FIDL type into some bytes
15pub fn encode_fidl<'a, T: fidl::Persistable>(value: &'a mut T) -> Result<Vec<u8>, Error> {
16    fidl::persist(value).map_err(Into::into)
17}
18
19#[cfg(test)]
20mod test {
21    use super::*;
22    use fidl_test_coding::Foo;
23
24    #[fuchsia::test]
25    fn encode_decode() {
26        let mut bytes = encode_fidl(&mut Foo { byte: 5 }).expect("encoding fails");
27        let result: Foo = decode_fidl(&mut bytes).expect("decoding fails");
28        assert_eq!(result.byte, 5);
29    }
30}