1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Copyright 2020 WeDPR Lab Project Authors. Licensed under Apache-2.0.

//! Library of protobuf definitions and their generated code.

use protobuf::Message;

#[cfg(not(tarpaulin_include))]
pub mod generated;

use wedpr_l_utils::error::WedprError;

pub fn proto_to_bytes<T: Message>(proto: &T) -> Result<Vec<u8>, WedprError> {
    return match proto.write_to_bytes() {
        Ok(v) => Ok(v),
        Err(_) => Err(WedprError::DecodeError),
    };
}

pub fn bytes_to_proto<T: Message>(proto_bytes: &[u8]) -> Result<T, WedprError> {
    return match T::parse_from_bytes(proto_bytes) {
        Ok(v) => Ok(v),
        Err(_) => Err(WedprError::DecodeError),
    };
}

#[cfg(test)]
mod tests {
    use super::*;
    use generated::zkp::BalanceProof;

    #[test]
    fn test_parser() {
        let mut proof = BalanceProof::new();
        proof.set_check1("test1".as_bytes().to_vec());
        proof.set_check2("test2".as_bytes().to_vec());
        let bytes = proto_to_bytes(&proof).unwrap();
        let proof_parser = bytes_to_proto::<BalanceProof>(&bytes).unwrap();
        assert_eq!(proof_parser, proof);
    }
}