rain_lang/value/primitive/
binary.rs

1/*!
2Binary constants
3*/
4use super::logical::LogicalOp;
5use num::{BigInt, BigUint};
6use std::fmt::{Debug, Display, Formatter, self};
7
8/// The maximum number of bits a small binary constant can hold
9pub const MAX_SMALL_BITS: u8 = 128;
10
11/// A single bit
12#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
13#[repr(transparent)]
14pub struct Bit(pub bool);
15
16/// A binary bitwise logical operation
17#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
18pub struct Bitwise {
19    /// The operation to carry out
20    op: LogicalOp,
21    /// The number of bits to carry it out on
22    bits: u16
23}
24
25/// A small amount of bits
26#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
27pub struct SmallBits(u8);
28
29/// Display mode for a binary constant
30#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
31pub enum BinaryDisplay {
32    /// Binary display, (bits)'b(value) for binary, 0b(value) for integer
33    Bin,
34    /// Octal display, (bits)'o(value) for binary, 0o(value) for integer
35    Oct,
36    /// Decimal display (bits)'d(value) for binary, 0d(value) for integer
37    Dec,
38    /// Hexadecimal display, (bits)'h(value) for binary, 0x(value) for integer
39    Hex
40}
41
42/// A small binary constant
43#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
44pub struct Binary {
45    bits: SmallBits,
46    display: BinaryDisplay,
47    value: u128
48}
49
50/// A big natural number
51#[derive(Clone, Eq, PartialEq, Hash)]
52pub struct Natural(pub BigUint, pub BinaryDisplay);
53
54impl Debug for Natural {
55    fn fmt(&self, fmt: &mut Formatter) -> Result<(), fmt::Error> {
56        <Self as Display>::fmt(self, fmt)
57    }
58}
59
60impl Display for Natural {
61    fn fmt(&self, fmt: &mut Formatter) -> Result<(), fmt::Error> {
62        use BinaryDisplay::*;
63        match self.1 {
64            Bin => write!(fmt, "{:#b}", self.0),
65            Oct => write!(fmt, "{:#o}", self.0),
66            Dec => write!(fmt, "{}", self.0),
67            Hex => write!(fmt, "{:#x}", self.0)
68        }
69    }
70}
71
72/// A big integer
73#[derive(Clone, Eq, PartialEq, Hash)]
74pub struct Integer(pub BigInt, pub BinaryDisplay);
75
76
77impl Debug for Integer {
78    fn fmt(&self, fmt: &mut Formatter) -> Result<(), fmt::Error> {
79        <Self as Display>::fmt(self, fmt)
80    }
81}
82
83impl Display for Integer {
84    fn fmt(&self, fmt: &mut Formatter) -> Result<(), fmt::Error> {
85        use BinaryDisplay::*;
86        match self.1 {
87            Bin => write!(fmt, "{:#b}", self.0),
88            Oct => write!(fmt, "{:#o}", self.0),
89            Dec => write!(fmt, "{}", self.0),
90            Hex => write!(fmt, "{:#x}", self.0)
91        }
92    }
93}