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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
// Copyright 2015-2017 Susy Technologies
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

/// Return `s` without the `0x` at the beginning of it, if any.
pub fn clean_0x(s: &str) -> &str {
	if s.starts_with("0x") {
		&s[2..]
	} else {
		s
	}
}

#[macro_export]
macro_rules! construct_hash {
	($from: ident, $size: expr) => {
		#[repr(C)]
		/// Unformatted binary data of fixed length.
		pub struct $from (pub [u8; $size]);


		impl From<[u8; $size]> for $from {
			fn from(bytes: [u8; $size]) -> Self {
				$from(bytes)
			}
		}

		impl From<$from> for [u8; $size] {
			fn from(s: $from) -> Self {
				s.0
			}
		}

		impl ::core::ops::Deref for $from {
			type Target = [u8];

			#[inline]
			fn deref(&self) -> &[u8] {
				&self.0
			}
		}

		impl AsRef<[u8]> for $from {
			#[inline]
			fn as_ref(&self) -> &[u8] {
				&self.0
			}
		}

		impl AsRef<$from> for $from {
			#[inline]
			fn as_ref(&self) -> &$from {
				&self
			}
		}

		impl ::core::ops::DerefMut for $from {
			#[inline]
			fn deref_mut(&mut self) -> &mut [u8] {
				&mut self.0
			}
		}

		impl $from {
			/// Create a new, zero-initialised, instance.
			pub fn new() -> $from {
				$from([0; $size])
			}

			/// Synonym for `new()`. Prefer to new as it's more readable.
			pub fn zero() -> $from {
				$from([0; $size])
			}

			/// Get the size of this object in bytes.
			pub fn len() -> usize {
				$size
			}

			#[inline]
			/// Assign self to be of the same value as a slice of bytes of length `len()`.
			pub fn clone_from_slice(&mut self, src: &[u8]) -> usize {
				let min = ::core::cmp::min($size, src.len());
				self.0[..min].copy_from_slice(&src[..min]);
				min
			}

			/// Convert a slice of bytes of length `len()` to an instance of this type.
			pub fn from_slice(src: &[u8]) -> Self {
				let mut r = Self::new();
				r.clone_from_slice(src);
				r
			}

			/// Copy the data of this object into some mutable slice of length `len()`.
			pub fn copy_to(&self, dest: &mut[u8]) {
				let min = ::core::cmp::min($size, dest.len());
				dest[..min].copy_from_slice(&self.0[..min]);
			}

			/// Returns `true` if all bits set in `b` are also set in `self`.
			pub fn contains<'a>(&'a self, b: &'a Self) -> bool {
				&(b & self) == b
			}

			/// Returns `true` if no bits are set.
			pub fn is_zero(&self) -> bool {
				self.eq(&Self::new())
			}

			/// Returns the lowest 8 bytes interpreted as a BigEndian integer.
			pub fn low_u64(&self) -> u64 {
				let mut ret = 0u64;
				for i in 0..::core::cmp::min($size, 8) {
					ret |= (self.0[$size - 1 - i] as u64) << (i * 8);
				}
				ret
			}

			impl_std_for_hash_internals!($from, $size);
		}

		impl ::core::fmt::Debug for $from {
			fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
				write!(f, "0x")?;
				::core::fmt::LowerHex::fmt(self, f)
			}
		}

		impl ::core::fmt::Display for $from {
			fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
				write!(f, "0x")?;
				for i in &self.0[0..2] {
					write!(f, "{:02x}", i)?;
				}
				write!(f, "…")?;
				for i in &self.0[$size - 2..$size] {
					write!(f, "{:02x}", i)?;
				}
				Ok(())
			}
		}

		impl ::core::fmt::LowerHex for $from {
			fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
				for i in &self.0[..] {
					write!(f, "{:02x}", i)?;
				}
				Ok(())
			}
		}

		impl Copy for $from {}
		#[cfg_attr(feature="dev", allow(expl_impl_clone_on_copy))]
		impl Clone for $from {
			fn clone(&self) -> $from {
				let mut ret = $from::new();
				ret.0.copy_from_slice(&self.0);
				ret
			}
		}

		impl Eq for $from {}

		impl PartialOrd for $from {
			fn partial_cmp(&self, other: &Self) -> Option<::core::cmp::Ordering> {
				Some(self.cmp(other))
			}
		}

		impl ::core::hash::Hash for $from {
			fn hash<H>(&self, state: &mut H) where H: ::core::hash::Hasher {
				state.write(&self.0);
				state.finish();
			}
		}

		impl ::core::ops::Index<usize> for $from {
			type Output = u8;

			fn index(&self, index: usize) -> &u8 {
				&self.0[index]
			}
		}
		impl ::core::ops::IndexMut<usize> for $from {
			fn index_mut(&mut self, index: usize) -> &mut u8 {
				&mut self.0[index]
			}
		}
		impl ::core::ops::Index<::core::ops::Range<usize>> for $from {
			type Output = [u8];

			fn index(&self, index: ::core::ops::Range<usize>) -> &[u8] {
				&self.0[index]
			}
		}
		impl ::core::ops::IndexMut<::core::ops::Range<usize>> for $from {
			fn index_mut(&mut self, index: ::core::ops::Range<usize>) -> &mut [u8] {
				&mut self.0[index]
			}
		}
		impl ::core::ops::Index<::core::ops::RangeFull> for $from {
			type Output = [u8];

			fn index(&self, _index: ::core::ops::RangeFull) -> &[u8] {
				&self.0
			}
		}
		impl ::core::ops::IndexMut<::core::ops::RangeFull> for $from {
			fn index_mut(&mut self, _index: ::core::ops::RangeFull) -> &mut [u8] {
				&mut self.0
			}
		}

		/// `BitOr` on references
		impl<'a> ::core::ops::BitOr for &'a $from {
			type Output = $from;

			fn bitor(self, rhs: Self) -> Self::Output {
				let mut ret: $from = $from::default();
				for i in 0..$size {
					ret.0[i] = self.0[i] | rhs.0[i];
				}
				ret
			}
		}

		/// Moving `BitOr`
		impl ::core::ops::BitOr for $from {
			type Output = $from;

			fn bitor(self, rhs: Self) -> Self::Output {
				&self | &rhs
			}
		}

		/// `BitAnd` on references
		impl <'a> ::core::ops::BitAnd for &'a $from {
			type Output = $from;

			fn bitand(self, rhs: Self) -> Self::Output {
				let mut ret: $from = $from::default();
				for i in 0..$size {
					ret.0[i] = self.0[i] & rhs.0[i];
				}
				ret
			}
		}

		/// Moving `BitAnd`
		impl ::core::ops::BitAnd for $from {
			type Output = $from;

			fn bitand(self, rhs: Self) -> Self::Output {
				&self & &rhs
			}
		}

		/// `BitXor` on references
		impl <'a> ::core::ops::BitXor for &'a $from {
			type Output = $from;

			fn bitxor(self, rhs: Self) -> Self::Output {
				let mut ret: $from = $from::default();
				for i in 0..$size {
					ret.0[i] = self.0[i] ^ rhs.0[i];
				}
				ret
			}
		}

		/// Moving `BitXor`
		impl ::core::ops::BitXor for $from {
			type Output = $from;

			fn bitxor(self, rhs: Self) -> Self::Output {
				&self ^ &rhs
			}
		}

		impl Default for $from {
			fn default() -> Self { $from::new() }
		}

		impl From<u64> for $from {
			fn from(mut value: u64) -> $from {
				let mut ret = $from::new();
				for i in 0..8 {
					if i < $size {
						ret.0[$size - i - 1] = (value & 0xff) as u8;
						value >>= 8;
					}
				}
				ret
			}
		}

		impl<'a> From<&'a [u8]> for $from {
			fn from(s: &'a [u8]) -> $from {
				$from::from_slice(s)
			}
		}

		impl_std_for_hash!($from, $size);
		impl_heapsize_for_hash!($from);
		impl_libc_for_hash!($from, $size);
		impl_quickcheck_arbitrary_for_hash!($from, $size);
	}
}

#[cfg(feature="heapsizeof")]
#[macro_export]
#[doc(hidden)]
macro_rules! impl_heapsize_for_hash {
	($name: ident) => {
		impl $crate::heapsize::HeapSizeOf for $name {
			fn heap_size_of_children(&self) -> usize {
				0
			}
		}
	}
}

#[cfg(not(feature="heapsizeof"))]
#[macro_export]
#[doc(hidden)]
macro_rules! impl_heapsize_for_hash {
	($name: ident) => {}
}

#[cfg(feature="std")]
#[macro_export]
#[doc(hidden)]
macro_rules! impl_std_for_hash {
	($from: ident, $size: tt) => {
		impl $from {
			/// Get a hex representation.
			#[deprecated(note="Use LowerHex or Debug formatting instead.")]
			pub fn hex(&self) -> String {
				format!("{:?}", self)
			}
		}

		impl $crate::rand::Rand for $from {
			fn rand<R: $crate::rand::Rng>(r: &mut R) -> Self {
				let mut hash = $from::new();
				r.fill_bytes(&mut hash.0);
				hash
			}
		}

		impl ::core::str::FromStr for $from {
			type Err = $crate::rustc_hex::FromHexError;

			fn from_str(s: &str) -> Result<$from, $crate::rustc_hex::FromHexError> {
				use $crate::rustc_hex::FromHex;
				let a = s.from_hex()?;
				if a.len() != $size {
					return Err($crate::rustc_hex::FromHexError::InvalidHexLength);
				}

				let mut ret = [0; $size];
				ret.copy_from_slice(&a);
				Ok($from(ret))
			}
		}

		impl From<&'static str> for $from {
			fn from(s: &'static str) -> $from {
				let s = $crate::clean_0x(s);
				if s.len() % 2 == 1 {
					("0".to_owned() + s).parse().unwrap()
				} else {
					s.parse().unwrap()
				}
			}
		}
	}
}


#[cfg(not(feature="std"))]
#[macro_export]
#[doc(hidden)]
macro_rules! impl_std_for_hash {
	($from: ident, $size: tt) => {}
}


#[cfg(feature="std")]
#[macro_export]
#[doc(hidden)]
macro_rules! impl_std_for_hash_internals {
	($from: ident, $size: tt) => {
		/// Create a new, cryptographically random, instance.
		pub fn random() -> $from {
			let mut hash = $from::new();
			hash.randomize();
			hash
		}

		/// Assign self have a cryptographically random value.
		pub fn randomize(&mut self) {
			let mut rng = $crate::rand::OsRng::new().unwrap();
			*self = $crate::rand::Rand::rand(&mut rng);
		}
	}
}

#[cfg(not(feature="std"))]
#[macro_export]
#[doc(hidden)]
macro_rules! impl_std_for_hash_internals {
	($from: ident, $size: tt) => {}
}

#[cfg(all(feature="libc", not(target_os = "unknown")))]
#[macro_export]
#[doc(hidden)]
macro_rules! impl_libc_for_hash {
	($from: ident, $size: expr) => {
		impl PartialEq for $from {
			fn eq(&self, other: &Self) -> bool {
				unsafe { $crate::libc::memcmp(self.0.as_ptr() as *const $crate::libc::c_void, other.0.as_ptr() as *const $crate::libc::c_void, $size) == 0 }
			}
		}

		impl Ord for $from {
			fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
				let r = unsafe { $crate::libc::memcmp(self.0.as_ptr() as *const $crate::libc::c_void, other.0.as_ptr() as *const $crate::libc::c_void, $size) };
				if r < 0 { return ::core::cmp::Ordering::Less }
				if r > 0 { return ::core::cmp::Ordering::Greater }
				return ::core::cmp::Ordering::Equal;
			}
		}
	}
}

#[cfg(any(not(feature="libc"), target_os = "unknown"))]
#[macro_export]
#[doc(hidden)]
macro_rules! impl_libc_for_hash {
	($from: ident, $size: expr) => {
		impl PartialEq for $from {
			fn eq(&self, other: &Self) -> bool {
				&self.0[..] == &other.0[..]
			}
		}

		impl Ord for $from {
			fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
				self.0[..].cmp(&other.0[..])
			}
		}
	}
}

#[cfg(feature="impl_quickcheck_arbitrary")]
#[macro_export]
#[doc(hidden)]
macro_rules! impl_quickcheck_arbitrary_for_hash {
	($name: ty, $n_bytes: tt) => {
		impl $crate::quickcheck::Arbitrary for $name {
			fn arbitrary<G: $crate::quickcheck::Gen>(g: &mut G) -> Self {
				let mut res = [0u8; $n_bytes];
				g.fill_bytes(&mut res[..$n_bytes]);
				res.as_ref().into()
			}
		}
	}
}

#[cfg(not(feature="impl_quickcheck_arbitrary"))]
#[macro_export]
#[doc(hidden)]
macro_rules! impl_quickcheck_arbitrary_for_hash {
	($name: ty, $n_bytes: tt) => {}
}