Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add trait for the Numeric Bytes type #10

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 78 additions & 1 deletion src/num.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,14 @@

use crate::Fundamental;
use core::{
borrow::BorrowMut,
convert::{
AsMut,
AsRef,
},
fmt::{
Binary,
Debug,
LowerExp,
LowerHex,
Octal,
Expand All @@ -28,12 +34,20 @@ use core::{
BitOrAssign,
BitXor,
BitXorAssign,
Bound,
Div,
DivAssign,
IndexMut,
Mul,
MulAssign,
Neg,
Not,
Range,
RangeFrom,
RangeFull,
RangeInclusive,
RangeTo,
RangeToInclusive,
Rem,
RemAssign,
Shl,
Expand All @@ -43,8 +57,71 @@ use core::{
Sub,
SubAssign,
},
panic::{
RefUnwindSafe,
UnwindSafe,
},
};

/// Declares that a type is an array of bytes `[u8; N]`
/// that corresponds to a `Numeric` type's byte representation.
pub trait NumericBytes:
AsRef<[u8]>
+ AsMut<[u8]>
+ BorrowMut<[u8]>
+ Copy
+ Debug
+ Default
+ Eq
+ Hash
+ IndexMut<usize, Output = u8>
+ IndexMut<(Bound<usize>, Bound<usize>), Output = [u8]>
+ IndexMut<Range<usize>, Output = [u8]>
+ IndexMut<RangeFrom<usize>, Output = [u8]>
+ IndexMut<RangeFull, Output = [u8]>
+ IndexMut<RangeInclusive<usize>, Output = [u8]>
+ IndexMut<RangeTo<usize>, Output = [u8]>
+ IndexMut<RangeToInclusive<usize>, Output = [u8]>
+ Ord
+ PartialEq<[u8]>
+ for<'a> PartialEq<&'a [u8]>
+ for<'a> PartialEq<&'a mut [u8]>
+ for<'a> TryFrom<&'a [u8]>
+ for<'a> TryFrom<&'a mut [u8]>
+ RefUnwindSafe
+ Send
+ Sync
+ Unpin
+ UnwindSafe
{
}

/// Extra trait implementations for `NumericBytes` when the `std` feature is enabled.
#[cfg(feature = "std")]
pub trait NumericBytesStd: NumericBytes
+ TryFrom<Vec<u8>>
+ Into<Vec<u8>>
+ Into<Box<[u8]>>
{
}

macro_rules! impl_numeric_bytes {
($n:expr) => {
impl NumericBytes for [u8; $n] {
}

#[cfg(feature = "std")]
impl NumericBytesStd for [u8; $n] {
}
}
}

impl_numeric_bytes!(1);
impl_numeric_bytes!(2);
impl_numeric_bytes!(4);
impl_numeric_bytes!(8);
impl_numeric_bytes!(16);

new_trait! {
/// Declares that a type is an abstract number.
///
Expand Down Expand Up @@ -80,7 +157,7 @@ new_trait! {
, @for<'a> RemAssign<&'a Self>
{
/// The `[u8; N]` byte array that stores values of `Self`.
type Bytes;
type Bytes: NumericBytes;

new_trait! { i32 @
fn to_be_bytes(self) -> Self::Bytes;
Expand Down