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 use crate::error; 18 19 /// A serialized positive integer. 20 #[derive(Copy, Clone)] 21 pub struct Positive<'a>(untrusted::Input<'a>); 22 23 impl<'a> Positive<'a> { 24 #[inline] new_non_empty_without_leading_zeros( input: untrusted::Input<'a>, ) -> Result<Self, error::Unspecified>25 pub(crate) fn new_non_empty_without_leading_zeros( 26 input: untrusted::Input<'a>, 27 ) -> Result<Self, error::Unspecified> { 28 if input.is_empty() { 29 return Err(error::Unspecified); 30 } 31 if input.len() > 1 && input.as_slice_less_safe()[0] == 0 { 32 return Err(error::Unspecified); 33 } 34 Ok(Self(input)) 35 } 36 37 /// Returns the value, ordered from significant byte to least significant 38 /// byte, without any leading zeros. The result is guaranteed to be 39 /// non-empty. 40 #[inline] big_endian_without_leading_zero(&self) -> &'a [u8]41 pub fn big_endian_without_leading_zero(&self) -> &'a [u8] { 42 self.big_endian_without_leading_zero_as_input() 43 .as_slice_less_safe() 44 } 45 46 #[inline] big_endian_without_leading_zero_as_input(&self) -> untrusted::Input<'a>47 pub(crate) fn big_endian_without_leading_zero_as_input(&self) -> untrusted::Input<'a> { 48 self.0 49 } 50 } 51 52 impl Positive<'_> { 53 /// Returns the first byte. 54 /// 55 /// Will not panic because the value is guaranteed to have at least one 56 /// byte. first_byte(&self) -> u857 pub fn first_byte(&self) -> u8 { 58 // This won't panic because 59 self.0.as_slice_less_safe()[0] 60 } 61 } 62