balanced-ternary 2.1.0

A library to manipulate balanced ternary values.
Documentation
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
use crate::concepts::DigitOperate;
use crate::{Digit, Ternary};
use alloc::string::ToString;
use alloc::vec::Vec;
use core::fmt::Display;
use core::ops::{Add, BitAnd, BitOr, BitXor, Div, Mul, Neg, Sub};

/// A struct to store 5 ternary digits (~7.8 bits) value into one byte.
///
/// `TritsChunks` helps store ternary numbers into a compact memory structure.
///
/// From `0` to `± 121`.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[repr(transparent)]
pub struct TritsChunk(i8);

impl TritsChunk {
    /// Creates a `TritsChunk` from a given decimal value.
    ///
    /// # Arguments
    ///
    /// * `from` - An `i8` value representing the decimal value to be converted into a `TritsChunk`.
    ///
    /// # Panics
    ///
    /// This function panics if the input value is out of the valid range `-121..=121`.
    ///
    /// # Example
    ///
    /// ```
    /// use balanced_ternary::TritsChunk;
    ///
    /// let chunk = TritsChunk::from_dec(42);
    /// assert_eq!(chunk.to_dec(), 42);
    /// ```
    pub fn from_dec(from: i8) -> Self {
        if !(-121..=121).contains(&from) {
            panic!("TritsChunk::from_dec(): Invalid value: {}", from);
        }
        Self(from)
    }

    /// Converts the `TritsChunk` into its decimal representation.
    ///
    /// # Returns
    ///
    /// An `i8` value representing the decimal form of the `TritsChunk`.
    ///
    /// # Example
    ///
    /// ```
    /// use balanced_ternary::TritsChunk;
    ///
    /// let chunk = TritsChunk::from_dec(42);
    /// assert_eq!(chunk.to_dec(), 42);
    /// ```
    pub fn to_dec(&self) -> i8 {
        self.0
    }

    /// Converts the `TritsChunk` into its ternary representation.
    ///
    /// # Returns
    ///
    /// A `Ternary` type representing the ternary form of the `TritsChunk`.
    ///
    /// # Example
    ///
    /// ```
    /// use balanced_ternary::{TritsChunk, Ternary};
    ///
    /// let chunk = TritsChunk::from_dec(42);
    /// let ternary = chunk.to_ternary();
    /// assert_eq!(ternary.to_dec(), 42);
    /// ```
    pub fn to_ternary(&self) -> Ternary {
        Ternary::from_dec(self.0 as i64)
    }

    /// Converts the `TritsChunk` into its fixed-length ternary representation.
    ///
    /// # Returns
    ///
    /// A `Ternary` type representing the 5-digit fixed-length ternary form of the `TritsChunk`.
    ///
    /// # Example
    ///
    /// ```
    /// use balanced_ternary::{TritsChunk, Ternary};
    ///
    /// let chunk = TritsChunk::from_dec(42);
    /// let fixed_ternary = chunk.to_fixed_ternary();
    /// assert_eq!(fixed_ternary.to_dec(), 42);
    /// assert_eq!(fixed_ternary.to_digit_slice().len(), 5);
    /// ```
    pub fn to_fixed_ternary(&self) -> Ternary {
        Ternary::from_dec(self.0 as i64).with_length(5)
    }

    /// Converts the `TritsChunk` into a vector of its individual ternary digits.
    ///
    /// # Returns
    ///
    /// A `Vec<Digit>` representing the individual ternary digits of the `TritsChunk`.
    ///
    /// The resulting vector will always contain 5 digits since the `TritsChunk` is
    /// represented in a fixed-length ternary form.
    ///
    /// # Example
    ///
    /// ```
    /// use balanced_ternary::{TritsChunk, Digit};
    ///
    /// let chunk = TritsChunk::from_dec(42);
    /// let digits: Vec<Digit> = chunk.to_digits();
    /// assert_eq!(digits.len(), 5);
    /// ```
    pub fn to_digits(&self) -> Vec<Digit> {
        self.to_fixed_ternary().to_digit_slice().to_vec()
    }

    /// Creates a `TritsChunk` from a given `Ternary` value.
    ///
    /// # Arguments
    ///
    /// * `ternary` - A `Ternary` value to be converted into a `TritsChunk`.
    ///
    /// # Panics
    ///
    /// This function panics if the provided `ternary` value has a logarithmic length greater than 5,
    /// indicating that it cannot be represented by a single `TritsChunk`.
    ///
    /// # Example
    ///
    /// ```
    /// use balanced_ternary::{TritsChunk, Ternary};
    ///
    /// let ternary = Ternary::from_dec(42);
    /// let chunk = TritsChunk::from_ternary(ternary);
    /// assert_eq!(chunk.to_dec(), 42);
    /// ```
    pub fn from_ternary(ternary: Ternary) -> Self {
        if ternary.log() > 5 {
            panic!(
                "TritsChunk::from_ternary(): Ternary is too long: {}",
                ternary.to_string()
            );
        }
        Self(ternary.to_dec() as i8)
    }
}

/// Offers a compact structure to store a ternary number.
///
/// - A [Ternary] is 1 byte long per [Digit]. An 8 (16, 32, 64) digits ternary number is 8 (16, 32, 64) bytes long.
/// - A [DataTernary] is stored into [TritsChunk]. An 8 (16, 32, 64) digits ternary number with this structure is 2 (4, 7, 13) bytes long (1 byte for 5 digits).
///
/// Use the [Ternary] type to execute operations on numbers and [DataTernary] to store numbers.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct DataTernary {
    chunks: Vec<TritsChunk>,
}

impl DataTernary {
    /// Creates a new instance of `DataTernary` from a given `Ternary` value.
    ///
    /// This method ensures that the total number of ternary digits is a multiple of 5
    /// by padding as necessary. It then divides the ternary number into chunks of
    /// 5 digits each, which are stored in the `DataTernary` structure.
    ///
    /// # Arguments
    ///
    /// * `ternary` - A `Ternary` value to be converted into a `DataTernary`.
    ///
    /// # Returns
    ///
    /// A new `DataTernary` instance containing the converted chunks.
    ///
    /// # Example
    ///
    /// ```
    /// use balanced_ternary::{DataTernary, Ternary};
    ///
    /// let ternary = Ternary::from_dec(42);
    /// let data_ternary = DataTernary::from_ternary(ternary);
    /// assert_eq!(data_ternary.to_dec(), 42);
    /// ```
    pub fn from_ternary(ternary: Ternary) -> Self {
        let len = ternary.log();
        let diff = (5 - len % 5) % 5;
        let ternary = ternary.with_length(len + diff);
        let mut chunks = Vec::new();
        for i in 0..(ternary.log() / 5) {
            let digits = ternary.to_digit_slice()[i * 5..(i + 1) * 5].to_vec();
            chunks.push(TritsChunk::from_ternary(Ternary::new(digits)));
        }
        Self { chunks }
    }

    /// Converts a `DataTernary` into its equivalent `Ternary` representation.
    ///
    /// This function iterates over all the `TritsChunk` instances in the `DataTernary`,
    /// extracts their ternary representations, and reconstructs them into the full
    /// `Ternary` value. The resulting `Ternary` value may be trimmed to remove
    /// any leading zeroes in its ternary digit representation.
    ///
    /// # Returns
    ///
    /// A `Ternary` value that represents the combined ternary digits of the
    /// `DataTernary`.
    ///
    /// # Example
    ///
    /// ```
    /// use balanced_ternary::{DataTernary, Ternary};
    ///
    /// let ternary = Ternary::from_dec(42);
    /// let data_ternary = DataTernary::from_ternary(ternary.clone());
    /// assert_eq!(data_ternary.to_ternary(), ternary);
    /// ```
    pub fn to_ternary(&self) -> Ternary {
        let mut digits = Vec::new();
        for chunk in &self.chunks {
            digits.extend(chunk.to_ternary().to_digit_slice());
        }
        Ternary::new(digits).trim()
    }

    /// Converts the `DataTernary` into its fixed-length `Ternary` representation.
    ///
    /// This method iterates over all the `TritsChunk` instances in the `DataTernary` and
    /// extracts and combines their ternary digits into a single `Ternary` value.
    /// The resulting `Ternary` value will contain a fixed number of digits without trimming
    /// or removing leading zeroes.
    ///
    /// # Returns
    ///
    /// A `Ternary` value representing the combined fixed-length ternary digits of the `DataTernary`.
    ///
    /// # Example
    ///
    /// ```
    /// use balanced_ternary::{DataTernary, Ternary};
    ///
    /// let ternary = Ternary::from_dec(42);
    /// let data_ternary = DataTernary::from_ternary(ternary);
    /// let fixed_ternary = data_ternary.to_fixed_ternary();
    /// assert_eq!(fixed_ternary.to_dec(), 42); // When properly encoded
    /// ```
    pub fn to_fixed_ternary(&self) -> Ternary {
        let mut digits = Vec::new();
        for chunk in &self.chunks {
            digits.extend(chunk.to_digits());
        }
        Ternary::new(digits).trim()
    }

    /// Converts the `DataTernary` into a vector of ternary digits.
    ///
    /// This method first converts the `DataTernary` structure into its `Ternary` representation,
    /// trims any leading zeroes, and then returns the sequence of ternary digits as a `Vec<Digit>`.
    ///
    /// # Returns
    ///
    /// A `Vec<Digit>` containing the ternary digits that represent the `DataTernary` value.
    ///
    /// # Example
    ///
    /// ```
    /// use balanced_ternary::{DataTernary, Digit, Ternary};
    ///
    /// let ternary = Ternary::from_dec(42);
    /// let data_ternary = DataTernary::from_ternary(ternary);
    /// let digits = data_ternary.to_digits();
    /// assert_eq!(digits, vec![Digit::Pos, Digit::Neg, Digit::Neg, Digit::Neg, Digit::Zero]);
    /// ```
    pub fn to_digits(&self) -> Vec<Digit> {
        self.to_ternary().trim().to_digit_slice().to_vec()
    }

    /// Converts a decimal number into a `DataTernary` structure.
    ///
    /// This method takes a signed 64-bit integer as input and converts it into a
    /// `Ternary` representation, which is then stored in the compact `DataTernary`
    /// structure. The conversion ensures that the ternary representation uses
    /// fixed-length chunks for efficient storage.
    ///
    /// # Arguments
    ///
    /// * `from` - A signed 64-bit integer value to be converted into `DataTernary`.
    ///
    /// # Returns
    ///
    /// A `DataTernary` instance that represents the given decimal number.
    ///
    /// # Example
    ///
    /// ```
    /// use balanced_ternary::{DataTernary};
    ///
    /// let data_ternary = DataTernary::from_dec(42);
    /// assert_eq!(data_ternary.to_dec(), 42);
    /// ```
    pub fn from_dec(from: i64) -> Self {
        Self::from_ternary(Ternary::from_dec(from))
    }

    /// Converts a `DataTernary` into its decimal representation.
    ///
    /// This method reconstructs the ternary value represented by the `DataTernary`
    /// structure and converts it into the corresponding signed 64-bit decimal integer.
    ///
    /// # Returns
    ///
    /// A signed 64-bit integer (`i64`) representing the decimal equivalent of the
    /// `DataTernary` structure.
    ///
    /// # Example
    ///
    /// ```
    /// use balanced_ternary::{DataTernary};
    ///
    /// let data_ternary = DataTernary::from_dec(42);
    /// let decimal = data_ternary.to_dec();
    /// assert_eq!(decimal, 42);
    /// ```
    pub fn to_dec(&self) -> i64 {
        self.to_ternary().to_dec()
    }
}

impl Display for DataTernary {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        for chunk in &self.chunks {
            write!(f, "{}", chunk.to_fixed_ternary())?;
        }
        Ok(())
    }
}

impl From<Ternary> for DataTernary {
    fn from(value: Ternary) -> Self {
        Self::from_ternary(value)
    }
}

impl From<DataTernary> for Ternary {
    fn from(value: DataTernary) -> Self {
        value.to_ternary()
    }
}

/// A struct to store 40 ternary digits (~63.398 bits) value into one `i64`.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[repr(transparent)]
pub struct Ter40(i64);

impl Ter40 {
    pub fn from_dec(from: i64) -> Self {
        Self(from)
    }
    pub fn to_dec(&self) -> i64 {
        self.0
    }
    pub fn from_ternary(ternary: Ternary) -> Self {
        Self(ternary.to_dec())
    }
    pub fn to_ternary(&self) -> Ternary {
        Ternary::from_dec(self.0).with_length(40)
    }
}

impl DigitOperate for Ter40 {
    fn to_digits(&self) -> Vec<Digit> {
        self.to_ternary().to_digits()
    }

    fn digit(&self, index: usize) -> Option<Digit> {
        self.to_ternary().digit(index)
    }

    fn each(&self, f: impl Fn(Digit) -> Digit) -> Self
    where
        Self: Sized,
    {
        Self(self.to_ternary().each(f).to_dec())
    }

    fn each_with(&self, f: impl Fn(Digit, Digit) -> Digit, other: Digit) -> Self
    where
        Self: Sized,
    {
        Self(self.to_ternary().each_with(f, other).to_dec())
    }

    fn each_zip(&self, f: impl Fn(Digit, Digit) -> Digit, other: Self) -> Self
    where
        Self: Sized,
    {
        Self(self.to_ternary().each_zip(f, other.to_ternary()).to_dec())
    }

    fn each_zip_carry(&self, f: impl Fn(Digit, Digit, Digit) -> (Digit, Digit), other: Self) -> Self
    where
        Self: Sized,
    {
        Self(
            self.to_ternary()
                .each_zip_carry(f, other.to_ternary())
                .to_dec(),
        )
    }
}

impl Display for Ter40 {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", self.to_ternary())
    }
}

impl Add for Ter40 {
    type Output = Self;
    fn add(self, other: Self) -> Self::Output {
        Self(self.0 + other.0)
    }
}
impl Sub for Ter40 {
    type Output = Self;
    fn sub(self, other: Self) -> Self::Output {
        Self(self.0 - other.0)
    }
}
impl Mul for Ter40 {
    type Output = Self;
    fn mul(self, other: Self) -> Self::Output {
        Self(self.0 * other.0)
    }
}
impl Div for Ter40 {
    type Output = Self;
    fn div(self, other: Self) -> Self::Output {
        Self(self.0 / other.0)
    }
}

impl Neg for Ter40 {
    type Output = Self;
    fn neg(self) -> Self::Output {
        Self(-self.0)
    }
}

impl BitAnd for Ter40 {
    type Output = Self;
    fn bitand(self, other: Self) -> Self::Output {
        self.each_zip(Digit::bitand, other)
    }
}

impl BitOr for Ter40 {
    type Output = Self;
    fn bitor(self, other: Self) -> Self::Output {
        self.each_zip(Digit::bitor, other)
    }
}

impl BitXor for Ter40 {
    type Output = Self;
    fn bitxor(self, other: Self) -> Self::Output {
        self.each_zip(Digit::bitxor, other)
    }
}

impl From<i64> for Ter40 {
    fn from(value: i64) -> Self {
        Self(value)
    }
}

impl From<Ter40> for i64 {
    fn from(value: Ter40) -> Self {
        value.0
    }
}

impl From<Ternary> for Ter40 {
    fn from(value: Ternary) -> Self {
        Self::from_ternary(value)
    }
}

impl From<Ter40> for Ternary {
    fn from(value: Ter40) -> Self {
        value.to_ternary()
    }
}

#[cfg(test)]
#[test]
fn single_chunk_creation() {
    use crate::Ternary;

    let ternary = Ternary::parse("+-0-+");
    let data = DataTernary::from_ternary(ternary.clone());

    assert_eq!(data.chunks.len(), 1);
    assert_eq!(data.to_ternary(), ternary);
}

#[cfg(test)]
#[test]
fn round_trip() {
    use crate::Ternary;

    let ternary = Ternary::parse("+0-0++-");
    let data = DataTernary::from_ternary(ternary.clone());

    assert_eq!(data.to_ternary(), ternary);
}