      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
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291

    // Copyright 2015-2017 Parity Technologies (UK) Ltd.
    // This file is part of Parity.

    // Parity is free software: you can redistribute it and/or modify
    // it under the terms of the GNU General Public License as published by
    // the Free Software Foundation, either version 3 of the License, or
    // (at your option) any later version.

    // Parity is distributed in the hope that it will be useful,
    // but WITHOUT ANY WARRANTY; without even the implied warranty of
    // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    // GNU General Public License for more details.

    // You should have received a copy of the GNU General Public License
    // along with Parity.  If not, see <http://www.gnu.org/licenses/>.

    //! Unified interfaces for RLP bytes operations on basic types
    //!

    use std::mem;
    use std::fmt;
    use std::cmp::Ordering;
    use std::error::Error as StdError;
    use bigint::prelude::{Uint, U128, U256, H64, H128, H160, H256, H512, H520, H2048};
    use elastic_array::*;

    /// Vector like object
    pub trait VecLike<T> {
    	/// Add an element to the collection
        fn vec_push(&mut self, value: T);

    	/// Add a slice to the collection
        fn vec_extend(&mut self, slice: &[T]);
    }

    impl<T> VecLike<T> for Vec<T> where T: Copy {
    	fn vec_push(&mut self, value: T) {
    		Vec::<T>::push(self, value)
    	}

    	fn vec_extend(&mut self, slice: &[T]) {
    		Vec::<T>::extend_from_slice(self, slice)
    	}
    }

    macro_rules! impl_veclike_for_elastic_array {
    	($from: ident) => {
    		impl<T> VecLike<T> for $from<T> where T: Copy {
    			fn vec_push(&mut self, value: T) {
    				$from::<T>::push(self, value)
    			}
    			fn vec_extend(&mut self, slice: &[T]) {
    				$from::<T>::append_slice(self, slice)

    			}
    		}
    	}
    }

    impl_veclike_for_elastic_array!(ElasticArray16);
    impl_veclike_for_elastic_array!(ElasticArray32);
    impl_veclike_for_elastic_array!(ElasticArray1024);

    /// Converts given type to its shortest representation in bytes
    ///
    /// TODO: optimise some conversations
    pub trait ToBytes {
    	/// Serialize self to byte array
    	fn to_bytes<V: VecLike<u8>>(&self, out: &mut V);
    	/// Get length of serialized data in bytes
    	fn to_bytes_len(&self) -> usize;
    }

    impl <'a> ToBytes for &'a str {
    	fn to_bytes<V: VecLike<u8>>(&self, out: &mut V) {
    		out.vec_extend(self.as_bytes());
    	}

    	fn to_bytes_len(&self) -> usize {
    		self.as_bytes().len()
    	}
    }

    impl ToBytes for String {
    	fn to_bytes<V: VecLike<u8>>(&self, out: &mut V) {
    		out.vec_extend(self.as_bytes());
    	}

    	fn to_bytes_len(&self) -> usize {
    		self.len()
    	}
    }

    impl ToBytes for u64 {
    	fn to_bytes<V: VecLike<u8>>(&self, out: &mut V) {
    		let count = self.to_bytes_len();
    		for i in 0..count {
    			let j = count - 1 - i;
    			out.vec_push((*self >> (j * 8)) as u8);
    		}
    	}

    	fn to_bytes_len(&self) -> usize { 8 - self.leading_zeros() as usize / 8 }
    }

    impl ToBytes for bool {
    	fn to_bytes<V: VecLike<u8>>(&self, out: &mut V) {
    		out.vec_push(if *self { 1u8 } else { 0u8 })
    	}

    	fn to_bytes_len(&self) -> usize { 1 }
    }

    macro_rules! impl_map_to_bytes {
    	($from: ident, $to: ty) => {
    		impl ToBytes for $from {
    			fn to_bytes<V: VecLike<u8>>(&self, out: &mut V) {
    				(*self as $to).to_bytes(out)
    			}

    			fn to_bytes_len(&self) -> usize { (*self as $to).to_bytes_len() }
    		}
    	}
    }

    impl_map_to_bytes!(usize, u64);
    impl_map_to_bytes!(u16, u64);
    impl_map_to_bytes!(u32, u64);

    macro_rules! impl_uint_to_bytes {
    	($name: ident) => {
    		impl ToBytes for $name {
    			fn to_bytes<V: VecLike<u8>>(&self, out: &mut V) {
    				let count = self.to_bytes_len();
    				for i in 0..count {
    					let j = count - 1 - i;
    					out.vec_push(self.byte(j));
    				}
    			}
    			fn to_bytes_len(&self) -> usize { (self.bits() + 7) / 8 }
    		}
    	}
    }

    impl_uint_to_bytes!(U256);
    impl_uint_to_bytes!(U128);

    macro_rules! impl_hash_to_bytes {
    	($name: ident) => {
    		impl ToBytes for $name {
    			fn to_bytes<V: VecLike<u8>>(&self, out: &mut V) {
    				out.vec_extend(&self);
    			}
    			fn to_bytes_len(&self) -> usize { self.len() }
    		}
    	}
    }

    impl_hash_to_bytes!(H64);
    impl_hash_to_bytes!(H128);
    impl_hash_to_bytes!(H160);
    impl_hash_to_bytes!(H256);
    impl_hash_to_bytes!(H512);
    impl_hash_to_bytes!(H520);
    impl_hash_to_bytes!(H2048);

    /// Error returned when `FromBytes` conversation goes wrong
    #[derive(Debug, PartialEq, Eq)]
    pub enum FromBytesError {
    	/// Expected more RLP data
    	DataIsTooShort,
    	/// Extra bytes after the end of the last item
    	DataIsTooLong,
    	/// Integer-representation is non-canonically prefixed with zero byte(s).
    	ZeroPrefixedInt,
    	/// String representation is not utf-8
    	InvalidUtf8,
    }

    impl StdError for FromBytesError {
    	fn description(&self) -> &str { "from_bytes error" }
    }

    impl fmt::Display for FromBytesError {
    	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    		fmt::Debug::fmt(&self, f)
    	}
    }

    /// Alias for the result of `FromBytes` trait
    pub type FromBytesResult<T> = Result<T, FromBytesError>;

    /// Converts to given type from its bytes representation
    ///
    /// TODO: check size of bytes before conversation and return appropriate error
    pub trait FromBytes: Sized {
    	/// Create a value from bytes
    	fn from_bytes(bytes: &[u8]) -> FromBytesResult<Self>;
    }

    impl FromBytes for String {
    	fn from_bytes(bytes: &[u8]) -> FromBytesResult<String> {
    		::std::str::from_utf8(bytes).map(|s| s.to_owned()).map_err(|_| FromBytesError::InvalidUtf8)
    	}
    }

    macro_rules! impl_uint_from_bytes {
    	($to: ident) => {
    		impl FromBytes for $to {
    			fn from_bytes(bytes: &[u8]) -> FromBytesResult<$to> {
    				match bytes.len() {
    					0 => Ok(0),
    					l if l <= mem::size_of::<$to>() => {
    						if bytes[0] == 0 {
    							return Err(FromBytesError::ZeroPrefixedInt)
    						}
    						let mut res = 0 as $to;
    						for i in 0..l {
    							let shift = (l - 1 - i) * 8;
    							res = res + ((bytes[i] as $to) << shift);
    						}
    						Ok(res)
    					}
    					_ => Err(FromBytesError::DataIsTooLong)
    				}
    			}
    		}
    	}
    }

    impl FromBytes for bool {
    	fn from_bytes(bytes: &[u8]) -> FromBytesResult<bool> {
    		match bytes.len() {
    			0 => Ok(false),
    			1 => Ok(bytes[0] != 0),
    			_ => Err(FromBytesError::DataIsTooLong),
    		}
    	}
    }

    //impl_uint_from_bytes!(u8);
    impl_uint_from_bytes!(u16);
    impl_uint_from_bytes!(u32);
    impl_uint_from_bytes!(u64);
    impl_uint_from_bytes!(usize);

    macro_rules! impl_uint_from_bytes {
    	($name: ident, $size: expr) => {
    		impl FromBytes for $name {
    			fn from_bytes(bytes: &[u8]) -> FromBytesResult<$name> {
    				if !bytes.is_empty() && bytes[0] == 0 {
    					Err(FromBytesError::ZeroPrefixedInt)
    				} else if bytes.len() <= $size {
    					Ok($name::from(bytes))
    				} else {
    					Err(FromBytesError::DataIsTooLong)
    				}
    			}
    		}
    	}
    }

    impl_uint_from_bytes!(U256, 32);
    impl_uint_from_bytes!(U128, 16);

    macro_rules! impl_hash_from_bytes {
    	($name: ident, $size: expr) => {
    		impl FromBytes for $name {
    			fn from_bytes(bytes: &[u8]) -> FromBytesResult<$name> {
    				match bytes.len().cmp(&$size) {
    					Ordering::Less => Err(FromBytesError::DataIsTooShort),
    					Ordering::Greater => Err(FromBytesError::DataIsTooLong),
    					Ordering::Equal => {
    						let mut t = [0u8; $size];
    						t.copy_from_slice(bytes);
    						Ok($name(t))
    					}
    				}
    			}
    		}
    	}
    }

    impl_hash_from_bytes!(H64, 8);
    impl_hash_from_bytes!(H128, 16);
    impl_hash_from_bytes!(H160, 20);
    impl_hash_from_bytes!(H256, 32);
    impl_hash_from_bytes!(H512, 64);
    impl_hash_from_bytes!(H520, 65);
    impl_hash_from_bytes!(H2048, 256);

# Help

## Keyboard Shortcuts

?
  Show this help dialog
S
  Focus the search field
⇤
  Move up in search results
⇥
  Move down in search results
⏎
  Go to active search result
+
  Collapse/expand all sections

## Search Tricks

Prefix searches with a type followed by a colon (e.g. `fn:`) to restrict the search to a given type.

Accepted types are: `fn`, `mod`, `struct`, `enum`, `trait`, `type`, `macro`, and `const`.

Search functions by type signature (e.g. `vec -> usize` or `* -> vec`)