#[cfg(not(feature = "std"))]use alloc::vec::Vec;
#[cfg(not(feature = "std"))]use alloc::string::String;
#[cfg(feature = "std")] use std::fmt;
#[cfg(not(feature = "std"))] use core::fmt;
use {UntrustedRlp, PayloadInfo, Prototype, Decodable};
impl<'a> From<UntrustedRlp<'a>> for Rlp<'a> {
fn from(rlp: UntrustedRlp<'a>) -> Rlp<'a> {
Rlp { rlp: rlp }
}
}
#[derive(Debug)]
pub struct Rlp<'a> {
rlp: UntrustedRlp<'a>
}
impl<'a> fmt::Display for Rlp<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "{}", self.rlp)
}
}
impl<'a, 'view> Rlp<'a> where 'a: 'view {
pub fn new(bytes: &'a [u8]) -> Rlp<'a> {
Rlp {
rlp: UntrustedRlp::new(bytes)
}
}
pub fn as_raw(&'view self) -> &'a [u8] {
self.rlp.as_raw()
}
pub fn prototype(&self) -> Prototype {
self.rlp.prototype().unwrap()
}
pub fn payload_info(&self) -> PayloadInfo {
self.rlp.payload_info().unwrap()
}
pub fn data(&'view self) -> &'a [u8] {
self.rlp.data().unwrap()
}
pub fn item_count(&self) -> usize {
self.rlp.item_count().unwrap_or(0)
}
pub fn size(&self) -> usize {
self.rlp.size()
}
pub fn at(&'view self, index: usize) -> Rlp<'a> {
From::from(self.rlp.at(index).unwrap())
}
pub fn is_null(&self) -> bool {
self.rlp.is_null()
}
pub fn is_empty(&self) -> bool {
self.rlp.is_empty()
}
pub fn is_list(&self) -> bool {
self.rlp.is_list()
}
pub fn is_data(&self) -> bool {
self.rlp.is_data()
}
pub fn is_int(&self) -> bool {
self.rlp.is_int()
}
pub fn iter(&'view self) -> RlpIterator<'a, 'view> {
self.into_iter()
}
pub fn as_val<T>(&self) -> T where T: Decodable {
self.rlp.as_val().expect("Unexpected rlp error")
}
pub fn as_list<T>(&self) -> Vec<T> where T: Decodable {
self.iter().map(|rlp| rlp.as_val()).collect()
}
pub fn val_at<T>(&self, index: usize) -> T where T: Decodable {
self.at(index).as_val()
}
pub fn list_at<T>(&self, index: usize) -> Vec<T> where T: Decodable {
self.at(index).as_list()
}
}
pub struct RlpIterator<'a, 'view> where 'a: 'view {
rlp: &'view Rlp<'a>,
index: usize
}
impl<'a, 'view> IntoIterator for &'view Rlp<'a> where 'a: 'view {
type Item = Rlp<'a>;
type IntoIter = RlpIterator<'a, 'view>;
fn into_iter(self) -> Self::IntoIter {
RlpIterator {
rlp: self,
index: 0,
}
}
}
impl<'a, 'view> Iterator for RlpIterator<'a, 'view> {
type Item = Rlp<'a>;
fn next(&mut self) -> Option<Rlp<'a>> {
let index = self.index;
let result = self.rlp.rlp.at(index).ok().map(From::from);
self.index += 1;
result
}
}