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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
use crate::translate::{
bct_trybble_to_i8,
i8_trybble_to_bct,
bct_trybble_to_ternary_string,
i16_tryte_to_nonary_string,
};
#[derive(Debug)]
pub struct Tryte {
hi: u8,
lo: u8,
}
impl Clone for Tryte {
fn clone(&self) -> Self {
Tryte {
hi: self.hi,
lo: self.lo,
}
}
}
impl Tryte {
pub fn from_bct_trybbles(hi: u8, lo: u8) -> Self {
Tryte { hi, lo }
}
pub fn hi_value(&self) -> i8 {
bct_trybble_to_i8(self.hi)
}
pub fn lo_value(&self) -> i8 {
bct_trybble_to_i8(self.lo)
}
pub fn hi_bct(&self) -> u8 {
self.hi
}
pub fn lo_bct(&self) -> u8 {
self.lo
}
pub fn to_integer(&self) -> i16 {
let low = bct_trybble_to_i8(self.lo) as i16;
let high = bct_trybble_to_i8(self.hi) as i16;
(high * 27) + low
}
pub fn as_ternary_string(&self) -> Option<String> {
let hi_opt = bct_trybble_to_ternary_string(self.hi);
let lo_opt = bct_trybble_to_ternary_string(self.lo);
match (hi_opt, lo_opt) {
(Some(hi), Some(lo)) => Some([hi, lo].concat()),
_ => None,
}
}
pub fn as_nonary_string(&self) -> Option<String> {
i16_tryte_to_nonary_string(self.to_integer())
}
pub fn add(first: &Tryte, second: &Tryte) -> (Tryte, i8) {
let result = first.to_integer() + second.to_integer();
let tryte = Tryte::from(result);
let carry = 0;
(tryte, carry)
}
pub fn sub(first: &Tryte, second: &Tryte) -> (Tryte, i8) {
let result = first.to_integer() - second.to_integer();
let tryte = Tryte::from(result);
let carry = 0;
(tryte, carry)
}
}
impl Into<i16> for Tryte {
fn into(self) -> i16 {
self.to_integer()
}
}
impl From<i16> for Tryte {
fn from(number: i16) -> Self {
let res = (number / 27) as i8;
let rem = (number % 27) as i8;
let (high, low) = if rem > 13 {
(res + 1, rem - 27)
} else if rem < -13 {
(res - 1, rem + 27)
} else {
(res, rem)
};
Tryte {
hi: i8_trybble_to_bct(high),
lo: i8_trybble_to_bct(low),
}
}
}