fixed_bigint/
machineword.rs

1// Copyright 2021 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// Note: in the future, #![feature(const_trait_impl)] should allow
16// turning this into a const trait
17
18/// Represents a CPU native word, from 8-bit to 32-bit, with corresponding
19/// double-word to hold multiplication/division products.
20pub trait MachineWord:
21    num_traits::PrimInt
22    + num_traits::ops::overflowing::OverflowingAdd
23    + num_traits::ops::overflowing::OverflowingSub
24    + From<u8>
25    + core::ops::BitAndAssign
26    + core::ops::BitOrAssign
27    + core::ops::BitXorAssign
28    + num_traits::FromBytes
29    + num_traits::ToBytes
30    + Default
31    + core::hash::Hash
32{
33    type DoubleWord: num_traits::PrimInt;
34    fn to_double(self) -> Self::DoubleWord;
35    fn from_double(word: Self::DoubleWord) -> Self;
36}
37
38impl MachineWord for u8 {
39    type DoubleWord = u16;
40    fn to_double(self) -> Self::DoubleWord {
41        self as Self::DoubleWord
42    }
43    fn from_double(word: Self::DoubleWord) -> Self {
44        word as Self
45    }
46}
47impl MachineWord for u16 {
48    type DoubleWord = u32;
49    fn to_double(self) -> Self::DoubleWord {
50        self as Self::DoubleWord
51    }
52    fn from_double(word: Self::DoubleWord) -> Self {
53        word as Self
54    }
55}
56impl MachineWord for u32 {
57    type DoubleWord = u64;
58    fn to_double(self) -> Self::DoubleWord {
59        self as Self::DoubleWord
60    }
61    fn from_double(word: Self::DoubleWord) -> Self {
62        word as Self
63    }
64}
65impl MachineWord for u64 {
66    type DoubleWord = u128;
67    fn to_double(self) -> Self::DoubleWord {
68        self as Self::DoubleWord
69    }
70    fn from_double(word: Self::DoubleWord) -> Self {
71        word as Self
72    }
73}