1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
use super::*;
/// Format of the float, storing the number of bit for each fields.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Format {
/// Whether the float is signed or not, if true a bit will be assigned for the sign.
pub signed: bool,
/// Number of bits for the exponent.
/// Currently support up to 31 bits only.
pub exp: u8,
/// Number of bits for the mantissa (significand).
pub mant: usize,
/// The excess (offset, biased) value for the exponent.
/// This is the value that is subtracted from the exponent to get the actual exponent.
pub excess: u32,
}
impl Format {
/// Create from the given values for `exp`, `mant`, and `excess`, default to signed.
pub fn new(exp: u8, mant: usize, excess: u32) -> Format {
if exp > 31 {
panic!("exponent bits must be less than 32");
}
Format {
signed: true,
exp,
mant,
excess,
}
}
/// Create from the given values for `exp`, `mant`, and `excess`, default to unsigned.
pub fn new_unsigned(exp: u8, mant: usize, excess: u32) -> Format {
if exp > 31 {
panic!("exponent bits must be less than 32");
}
Format {
signed: false,
exp,
mant,
excess,
}
}
/// Create from the given values for `signed`, `exp`, `mant`, and `excess`.
pub fn new_with_sign(signed: bool, exp: u8, mant: usize, excess: u32) -> Format {
if exp > 31 {
panic!("exponent bits must be less than 32");
}
Format {
signed,
exp,
mant,
excess,
}
}
/// Create from the given values for `exp` and `mant`, default to signed.
/// The excess value is set to `(1 << (exp - 1)) - 1` (1 less than 2 to the power of `exp` - 1).
pub fn new_ieee_excess(exp: u8, mant: usize) -> Format {
if exp > 31 {
panic!("exponent bits must be less than 32");
}
Format {
signed: true,
exp,
mant,
excess: (1 << (exp - 1)) - 1,
}
}
/// Create from the given values for `signed`, `exp`, and `mant`.
/// The excess value is set to `(1 << (exp - 1)) - 1` (1 less than 2 to the power of `exp` - 1).
pub fn new_ieee_excess_with_sign(signed: bool, exp: u8, mant: usize) -> Format {
if exp > 31 {
panic!("exponent bits must be less than 32");
}
Format {
signed,
exp,
mant,
excess: (1 << (exp - 1)) - 1,
}
}
/// Get the number of bits for the format.
pub fn len(&self) -> usize {
self.signed as usize + self.exp as usize + self.mant
}
}
impl IeeeBinary for Format {
/// The exponent is 8 bits and biased by 127, and the mantissa is 23 bits.
fn ieee_binary32() -> Self {
Format::new(8, 23, 127)
}
/// The exponent is 11 bits and biased by 1023, and the mantissa is 52 bits.
fn ieee_binary64() -> Self {
Format::new(11, 52, 1023)
}
}