1 // Copyright 2018 Brian Smith. 2 // 3 // Permission to use, copy, modify, and/or distribute this software for any 4 // purpose with or without fee is hereby granted, provided that the above 5 // copyright notice and this permission notice appear in all copies. 6 // 7 // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES 8 // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 9 // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY 10 // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 11 // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION 12 // OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN 13 // CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 14 15 //! Serialization and deserialization. 16 17 /// A serialized positive integer. 18 #[derive(Copy, Clone)] 19 pub struct Positive<'a>(untrusted::Input<'a>); 20 21 impl<'a> Positive<'a> { 22 #[inline] new_non_empty_without_leading_zeros(input: untrusted::Input<'a>) -> Self23 pub(crate) fn new_non_empty_without_leading_zeros(input: untrusted::Input<'a>) -> Self { 24 debug_assert!(!input.is_empty()); 25 debug_assert!(input.len() == 1 || input.as_slice_less_safe()[0] != 0); 26 Self(input) 27 } 28 29 /// Returns the value, ordered from significant byte to least significant 30 /// byte, without any leading zeros. The result is guaranteed to be 31 /// non-empty. 32 #[inline] big_endian_without_leading_zero(&self) -> &'a [u8]33 pub fn big_endian_without_leading_zero(&self) -> &'a [u8] { 34 self.big_endian_without_leading_zero_as_input() 35 .as_slice_less_safe() 36 } 37 38 #[inline] big_endian_without_leading_zero_as_input(&self) -> untrusted::Input<'a>39 pub(crate) fn big_endian_without_leading_zero_as_input(&self) -> untrusted::Input<'a> { 40 self.0 41 } 42 } 43 44 impl Positive<'_> { 45 /// Returns the first byte. 46 /// 47 /// Will not panic because the value is guaranteed to have at least one 48 /// byte. first_byte(&self) -> u849 pub fn first_byte(&self) -> u8 { 50 // This won't panic because 51 self.0.as_slice_less_safe()[0] 52 } 53 } 54