tetsy_rlp/lib.rs
1// Copyright 2020 Parity Technologies
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9//! Recursive Length Prefix serialization crate.
10//!
11//! Allows encoding, decoding, and view onto rlp-slice
12//!
13//!# What should you use when?
14//!
15//!### Use `encode` function when:
16//! * You want to encode something inline.
17//! * You do not work on big set of data.
18//! * You want to encode whole data structure at once.
19//!
20//!### Use `decode` function when:
21//! * You want to decode something inline.
22//! * You do not work on big set of data.
23//! * You want to decode whole rlp at once.
24//!
25//!### Use `RlpStream` when:
26//! * You want to encode something in portions.
27//! * You encode a big set of data.
28//!
29//!### Use `Rlp` when:
30//! * You need to handle data corruption errors.
31//! * You are working on input data.
32//! * You want to get view onto rlp-slice.
33//! * You don't want to decode whole rlp at once.
34
35#![cfg_attr(not(feature = "std"), no_std)]
36
37#[cfg(not(feature = "std"))]
38extern crate alloc;
39
40mod error;
41mod impls;
42mod rlpin;
43mod stream;
44mod traits;
45
46#[cfg(not(feature = "std"))]
47use alloc::vec::Vec;
48use bytes::BytesMut;
49use core::borrow::Borrow;
50
51pub use self::{
52 error::DecoderError,
53 rlpin::{PayloadInfo, Prototype, Rlp, RlpIterator},
54 stream::RlpStream,
55 traits::{Decodable, Encodable},
56};
57
58/// The RLP encoded empty data (used to mean "null value").
59pub const NULL_RLP: [u8; 1] = [0x80; 1];
60/// The RLP encoded empty list.
61pub const EMPTY_LIST_RLP: [u8; 1] = [0xC0; 1];
62
63/// Shortcut function to decode trusted rlp
64///
65/// ```
66/// let data = vec![0x83, b'c', b'a', b't'];
67/// let animal: String = tetsy_rlp::decode(&data).expect("could not decode");
68/// assert_eq!(animal, "cat".to_owned());
69/// ```
70pub fn decode<T>(bytes: &[u8]) -> Result<T, DecoderError>
71where
72 T: Decodable,
73{
74 let rlp = Rlp::new(bytes);
75 rlp.as_val()
76}
77
78pub fn decode_list<T>(bytes: &[u8]) -> Vec<T>
79where
80 T: Decodable,
81{
82 let rlp = Rlp::new(bytes);
83 rlp.as_list().expect("trusted rlp should be valid")
84}
85
86/// Shortcut function to encode structure into rlp.
87///
88/// ```
89/// let animal = "cat";
90/// let out = tetsy_rlp::encode(&animal);
91/// assert_eq!(out, vec![0x83, b'c', b'a', b't']);
92/// ```
93pub fn encode<E>(object: &E) -> BytesMut
94where
95 E: Encodable,
96{
97 let mut stream = RlpStream::new();
98 stream.append(object);
99 stream.out()
100}
101
102pub fn encode_list<E, K>(object: &[K]) -> BytesMut
103where
104 E: Encodable,
105 K: Borrow<E>,
106{
107 let mut stream = RlpStream::new();
108 stream.append_list(object);
109 stream.out()
110}