rlp_decoder/
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 decoding, and view onto rlp-slice
12//!
13//! # What should you use when?
14//!
15//!
16//! ### Use `decode` function when:
17//! * You want to decode something inline.
18//! * You do not work on big set of data.
19//! * You want to decode whole rlp at once.
20//!
21//! ### Use `Rlp` when:
22//! * You need to handle data corruption errors.
23//! * You are working on input data.
24//! * You want to get view onto rlp-slice.
25//! * You don't want to decode whole rlp at once.
26
27#![cfg_attr(not(feature = "std"), no_std)]
28
29#[cfg(not(feature = "std"))]
30extern crate alloc;
31
32mod error;
33mod impls;
34mod rlpin;
35mod traits;
36
37#[cfg(not(feature = "std"))]
38use alloc::vec::Vec;
39
40pub use self::{
41	error::DecoderError,
42	rlpin::{PayloadInfo, Prototype, Rlp, RlpIterator},
43	traits::Decodable,
44};
45
46/// The RLP encoded empty data (used to mean "null value").
47pub const NULL_RLP: [u8; 1] = [0x80; 1];
48/// The RLP encoded empty list.
49pub const EMPTY_LIST_RLP: [u8; 1] = [0xC0; 1];
50
51/// Shortcut function to decode trusted rlp
52///
53/// ```
54/// let data = vec![0x83, b'c', b'a', b't'];
55/// let animal: String = rlp::decode(&data).expect("could not decode");
56/// assert_eq!(animal, "cat".to_owned());
57/// ```
58pub fn decode<T>(bytes: &[u8]) -> Result<T, DecoderError>
59where
60	T: Decodable,
61{
62	let rlp = Rlp::new(bytes);
63	rlp.as_val()
64}
65
66pub fn decode_list<T>(bytes: &[u8]) -> Vec<T>
67where
68	T: Decodable,
69{
70	let rlp = Rlp::new(bytes);
71	rlp.as_list().expect("trusted rlp should be valid")
72}