generic_bytes/
lib.rs

1// Copyright (c) Facebook, Inc. and its affiliates.
2//
3// This source code is licensed under the MIT license found in the
4// LICENSE file in the root directory of this source tree.
5
6use generic_array::{ArrayLength, GenericArray};
7use std::fmt;
8use std::marker::Sized;
9
10/// The error type returned when a conversion from a generic byte slice to a
11/// SizedBytes fails.
12#[derive(Debug, Copy, Clone)]
13pub struct TryFromSizedBytesError(());
14
15impl fmt::Display for TryFromSizedBytesError {
16    #[inline]
17    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
18        fmt::Display::fmt(self.__description(), f)
19    }
20}
21
22impl TryFromSizedBytesError {
23    pub fn new() -> TryFromSizedBytesError {
24        TryFromSizedBytesError(())
25    }
26
27    #[inline]
28    #[doc(hidden)]
29    pub fn __description(&self) -> &str {
30        "could not convert from generic byte slice"
31    }
32}
33
34impl Default for TryFromSizedBytesError {
35    fn default() -> TryFromSizedBytesError {
36        TryFromSizedBytesError::new()
37    }
38}
39
40/// A trait for sized key material that can be represented within a fixed byte
41/// array size, used to represent our DH key types. This trait being
42/// implemented with Error = SomeError allows you to derive
43/// `TryFrom<&[u8], Error = SomeError>`.
44pub trait SizedBytes: Sized {
45    /// The typed representation of the byte length
46    type Len: ArrayLength<u8> + 'static;
47
48    /// Converts this sized key material to a `GenericArray` of the same
49    /// size. One can convert this to a `&[u8]` with `GenericArray::as_slice()`
50    /// but the size information is then lost from the type.
51    fn to_arr(&self) -> GenericArray<u8, Self::Len>;
52
53    /// How to parse such sized material from a correctly-sized byte slice.
54    fn from_arr(arr: &GenericArray<u8, Self::Len>) -> Result<Self, TryFromSizedBytesError>;
55}
56
57/// The blanket implementation of SizedBytes for GenericArray
58impl<N: ArrayLength<u8> + 'static> SizedBytes for GenericArray<u8, N> {
59    type Len = N;
60
61    fn to_arr(&self) -> GenericArray<u8, Self::Len> {
62        self.clone()
63    }
64    fn from_arr(arr: &GenericArray<u8, Self::Len>) -> Result<Self, TryFromSizedBytesError> {
65        Ok(arr.clone())
66    }
67}