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.
56use generic_array::{ArrayLength, GenericArray};
7use std::fmt;
8use std::marker::Sized;
910/// 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(());
1415impl fmt::Display for TryFromSizedBytesError {
16#[inline]
17fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
18 fmt::Display::fmt(self.__description(), f)
19 }
20}
2122impl TryFromSizedBytesError {
23pub fn new() -> TryFromSizedBytesError {
24 TryFromSizedBytesError(())
25 }
2627#[inline]
28 #[doc(hidden)]
29pub fn __description(&self) -> &str {
30"could not convert from generic byte slice"
31}
32}
3334impl Default for TryFromSizedBytesError {
35fn default() -> TryFromSizedBytesError {
36 TryFromSizedBytesError::new()
37 }
38}
3940/// 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
46type Len: ArrayLength<u8> + 'static;
4748/// 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.
51fn to_arr(&self) -> GenericArray<u8, Self::Len>;
5253/// How to parse such sized material from a correctly-sized byte slice.
54fn from_arr(arr: &GenericArray<u8, Self::Len>) -> Result<Self, TryFromSizedBytesError>;
55}
5657/// The blanket implementation of SizedBytes for GenericArray
58impl<N: ArrayLength<u8> + 'static> SizedBytes for GenericArray<u8, N> {
59type Len = N;
6061fn to_arr(&self) -> GenericArray<u8, Self::Len> {
62self.clone()
63 }
64fn from_arr(arr: &GenericArray<u8, Self::Len>) -> Result<Self, TryFromSizedBytesError> {
65Ok(arr.clone())
66 }
67}