balanced_ternary/lib.rs
1//! A [balanced ternary](https://en.wikipedia.org/wiki/Balanced_ternary) data structure.
2//!
3//! A `Ternary` object in this module represents a number in the balanced ternary numeral system.
4//! Balanced ternary is a non-standard positional numeral system that uses three digits: {-1, 0, +1}
5//! represented here as `Neg` for -1, `Zero` for 0, and `Pos` for +1. It is useful in some domains
6//! of computer science and mathematics due to its arithmetic properties and representation
7//! symmetry.
8//!
9//! # Data Structures
10//!
11//! - **`Digit` Enum**:
12//! Represents a single digit for balanced ternary values, with possible values:
13//! - `Neg` for -1
14//! - `Zero` for 0
15//! - `Pos` for +1
16//!
17//! - **`Ternary` Struct**:
18//! Represents a balanced ternary number as a collection of `Digit`s.
19//! Provides utility functions for conversion, parsing, and manipulation.
20//!
21//! # Examples
22//!
23//! ## Converting between representations:
24//! ```rust
25//! use balanced_ternary::*;
26//!
27//! let ternary = Ternary::from_dec(5);
28//! assert_eq!(ternary.to_string(), "+--");
29//! assert_eq!(ternary.to_dec(), 5);
30//!
31//! let parsed = Ternary::parse("+--");
32//! assert_eq!(parsed.to_string(), "+--");
33//! assert_eq!(parsed.to_dec(), 5);
34//! ```
35//!
36//! ## Negative numbers:
37//! ```rust
38//! use balanced_ternary::*;
39//!
40//! let neg_five = Ternary::from_dec(-5);
41//! assert_eq!(neg_five.to_string(), "-++");
42//! assert_eq!(neg_five.to_dec(), -5);
43//!
44//! let negated = -&neg_five;
45//! assert_eq!(negated.to_string(), "+--");
46//! assert_eq!(negated.to_dec(), 5);
47//! ```
48//!
49//! ## Larger numbers:
50//! ```rust
51//! use balanced_ternary::*;
52//!
53//! let big = Ternary::from_dec(121);
54//! assert_eq!(big.to_string(), "+++++");
55//! assert_eq!(big.to_dec(), 121);
56//!
57//! let neg_big = Ternary::from_dec(-121);
58//! assert_eq!(neg_big.to_string(), "-----");
59//! assert_eq!(neg_big.to_dec(), -121);
60//! ```
61//!
62//! ## Operations
63//! ```
64//! use balanced_ternary::Ternary;
65//!
66//! let repr9 = Ternary::parse("+00");
67//! let repr4 = Ternary::parse("++");
68//! let repr13 = &repr9 + &repr4;
69//! let repr17 = &repr13 + &repr4;
70//! let repr34 = &repr17 + &repr17;
71//!
72//! assert_eq!(repr13.to_string(), "+++");
73//! assert_eq!(repr17.to_string(), "+-0-");
74//! assert_eq!(repr34.to_string(), "++-+");
75//!
76//! let repr30 = &repr34 - &repr4;
77//! assert_eq!(repr30.to_dec(), 30);
78//! assert_eq!(repr30.to_string(), "+0+0");
79//! ```
80//!
81#![no_std]
82extern crate alloc;
83
84use alloc::string::{String, ToString};
85use alloc::vec::Vec;
86use alloc::{format, vec};
87use core::fmt::{Display, Formatter};
88use core::str::FromStr;
89
90/// Provides helper functions for formatting integers in a given radix.
91///
92/// Used internally to convert decimal numbers into their ternary representation.
93/// - `x`: The number to be formatted.
94/// - `radix`: The base of the numeral system.
95///
96/// Returns a string representation of the number in the specified base.
97fn format_radix(x: i64, radix: u32) -> String {
98 let mut result = vec![];
99 let sign = x.signum();
100 let mut x = x.unsigned_abs();
101 loop {
102 let m = (x % radix as u64) as u32;
103 x /= radix as u64;
104 result.push(core::char::from_digit(m, radix).unwrap());
105 if x == 0 {
106 break;
107 }
108 }
109 format!(
110 "{}{}",
111 if sign == -1 { "-" } else { "" },
112 result.into_iter().rev().collect::<String>()
113 )
114}
115
116pub mod digit;
117
118pub use crate::digit::{
119 Digit,
120 Digit::{Neg, Pos, Zero},
121};
122
123/// Converts a character into a `Digit`.
124///
125/// # Arguments
126/// * `from` - A single character (`+`, `0`, or `-`).
127/// * **Panics** if the input character is invalid.
128///
129/// # Returns
130/// * A `Digit` enum corresponding to the character.
131///
132/// # Example
133/// ```
134/// use balanced_ternary::{trit, Digit};
135///
136/// let digit = trit('+');
137/// assert_eq!(digit, Digit::Pos);
138/// ```
139pub const fn trit(from: char) -> Digit {
140 Digit::from_char(from)
141}
142
143/// Converts a string representation of a balanced ternary number into a `Ternary` object.
144///
145/// This function is a convenient shorthand for creating `Ternary` numbers
146/// from string representations. The input string must consist of balanced
147/// ternary characters: `+`, `0`, and `-`.
148///
149/// # Arguments
150///
151/// * `from` - A string slice representing the balanced ternary number.
152/// * **Panics** if an input character is invalid.
153///
154/// # Returns
155///
156/// A `Ternary` object created from the provided string representation.
157///
158/// # Example
159/// ```
160/// use balanced_ternary::{ter, Ternary};
161///
162/// let ternary = ter("+-0+");
163/// assert_eq!(ternary.to_string(), "+-0+");
164/// ```
165pub fn ter(from: &str) -> Ternary {
166 Ternary::parse(from)
167}
168
169#[cfg(feature = "tryte")]
170/// Creates a `Tryte` object from a string representation of a balanced ternary number.
171/// It contains approximately 9.5 bits of information.
172///
173/// This function first converts the input string representation into a `Ternary` object
174/// using the `ter` function, and then constructs a `Tryte` from that `Ternary`.
175///
176/// # Panics
177///
178/// This function panics if the `Ternary` contains more than 6 digits or if an input character is invalid.
179///
180/// # Arguments
181///
182/// * `from` - A string slice representing the balanced ternary number. It must contain
183/// valid balanced ternary characters (`+`, `0`, or `-`) only.
184/// * Panics if an input character is invalid.
185///
186/// # Returns
187///
188/// A `Tryte` object constructed from the provided balanced ternary string.
189///
190/// # Example
191/// ```
192/// use balanced_ternary::{tryte, Tryte};
193///
194/// let tryte_value = tryte("+0+0");
195/// assert_eq!(tryte_value.to_string(), "00+0+0");
196/// ```
197pub fn tryte(from: &str) -> Tryte {
198 Tryte::from_ternary(&ter(from))
199}
200
201/// Represents a balanced ternary number using a sequence of `Digit`s.
202///
203/// Provides functions for creating, parsing, converting, and manipulating balanced ternary numbers.
204#[derive(Debug, Clone, PartialEq, Eq, Hash)]
205pub struct Ternary {
206 digits: Vec<Digit>,
207}
208
209impl Ternary {
210 /// Creates a new balanced ternary number from a vector of `Digit`s.
211 pub fn new(digits: Vec<Digit>) -> Ternary {
212 Ternary { digits }
213 }
214
215 /// Returns the number of digits (length) of the balanced ternary number.
216 pub fn log(&self) -> usize {
217 self.digits.len()
218 }
219
220 /// Retrieves a slice containing the digits of the `Ternary`.
221 ///
222 /// # Returns
223 ///
224 /// A slice referencing the digits vec of the `Ternary`.
225 ///
226 /// This function allows access to the raw representation of the
227 /// balanced ternary number as a slice of `Digit` values.
228 pub fn to_digit_slice(&self) -> &[Digit] {
229 self.digits.as_slice()
230 }
231
232 /// Returns a reference to the [Digit] indexed by `index` if it exists.
233 ///
234 /// Digits are indexed **from the right**:
235 /// ```
236 /// use balanced_ternary::Ternary;
237 ///
238 /// // Indexes :
239 /// // 32
240 /// // 4||1
241 /// // 5||||0
242 /// // ||||||
243 /// // vvvvvv
244 /// let ternary = Ternary::parse("+++--+");
245 /// assert_eq!(ternary.get_digit(1).unwrap().to_char(), '-')
246 /// ```
247 pub fn get_digit(&self, index: usize) -> Option<&Digit> {
248 self.digits.iter().rev().nth(index)
249 }
250
251 /// Parses a string representation of a balanced ternary number into a `Ternary` object.
252 ///
253 /// Each character in the string must be one of `+`, `0`, or `-`.
254 pub fn parse(str: &str) -> Self {
255 let mut repr = Ternary::new(vec![]);
256 for c in str.chars() {
257 repr.digits.push(Digit::from_char(c));
258 }
259 repr
260 }
261
262 /// Converts the `Ternary` object to its integer (decimal) representation.
263 ///
264 /// Calculates the sum of each digit's value multiplied by the appropriate power of 3.
265 pub fn to_dec(&self) -> i64 {
266 let mut dec = 0;
267 for (rank, digit) in self.digits.iter().rev().enumerate() {
268 dec += digit.to_i8() as i64 * 3_i64.pow(rank as u32);
269 }
270 dec
271 }
272
273 /// Creates a balanced ternary number from a decimal integer.
274 ///
275 /// The input number is converted into its balanced ternary representation,
276 /// with digits represented as `Digit`s.
277 pub fn from_dec(dec: i64) -> Self {
278 let sign = dec.signum();
279 let str = format_radix(dec.abs(), 3);
280 let mut carry = 0u8;
281 let mut repr = Ternary::new(vec![]);
282 for digit in str.chars().rev() {
283 let digit = u8::from_str(&digit.to_string()).unwrap() + carry;
284 if digit < 2 {
285 repr.digits.push(Digit::from_i8(digit as i8));
286 carry = 0;
287 } else if digit == 2 {
288 repr.digits.push(Digit::from_i8(-1));
289 carry = 1;
290 } else if digit == 3 {
291 repr.digits.push(Digit::from_i8(0));
292 carry = 1;
293 } else {
294 panic!("Ternary::from_dec(): Invalid digit: {}", digit);
295 }
296 }
297 if carry == 1 {
298 repr.digits.push(Digit::from_i8(1));
299 }
300 repr.digits.reverse();
301 if sign == -1 {
302 -&repr
303 } else {
304 repr
305 }
306 }
307
308 /// Converts the balanced ternary number to its unbalanced representation as a string.
309 ///
310 /// The unbalanced representation treats the digits as standard ternary (0, 1, 2),
311 /// instead of balanced ternary (-1, 0, +1). Negative digits are handled by
312 /// calculating the decimal value of the balanced ternary number and converting
313 /// it back to an unbalanced ternary string.
314 ///
315 /// Returns:
316 /// * `String` - The unbalanced ternary representation of the number, where each
317 /// digit is one of `0`, `1`, or `2`.
318 ///
319 /// Example:
320 /// ```
321 /// use balanced_ternary::Ternary;
322 ///
323 /// let repr = Ternary::parse("+--");
324 /// assert_eq!(repr.to_unbalanced(), "12");
325 /// assert_eq!(repr.to_dec(), 5);
326 /// let repr = Ternary::parse("-++");
327 /// assert_eq!(repr.to_unbalanced(), "-12");
328 /// assert_eq!(repr.to_dec(), -5);
329 /// ```
330 pub fn to_unbalanced(&self) -> String {
331 format_radix(self.to_dec(), 3)
332 }
333
334 /// Parses a string representation of an unbalanced ternary number into a `Ternary` object.
335 ///
336 /// The string must only contain characters valid in the unbalanced ternary numeral system (`0`, `1`, or `2`).
337 /// Each character is directly converted into its decimal value and then interpreted as a balanced ternary number.
338 ///
339 /// # Arguments
340 ///
341 /// * `unbalanced` - A string slice representing the unbalanced ternary number.
342 ///
343 /// # Returns
344 ///
345 /// A `Ternary` object representing the same value as the input string in balanced ternary form.
346 ///
347 /// # Panics
348 ///
349 /// This function will panic if the string is not a valid unbalanced ternary number.
350 /// For instance, if it contains characters other than `0`, `1`, or `2`.
351 ///
352 /// # Examples
353 ///
354 /// ```
355 /// use balanced_ternary::Ternary;
356 ///
357 /// let ternary = Ternary::from_unbalanced("-12");
358 /// assert_eq!(ternary.to_string(), "-++");
359 /// assert_eq!(ternary.to_dec(), -5);
360 /// ```
361 pub fn from_unbalanced(unbalanced: &str) -> Self {
362 Self::from_dec(i64::from_str_radix(unbalanced, 3).unwrap())
363 }
364
365 /// Applies a transformation function to each digit of the balanced ternary number,
366 /// returning a new `Ternary` object with the transformed digits.
367 ///
368 /// This method keeps the order of the digits unchanged while applying the provided
369 /// transformation function `f` to each digit individually.
370 ///
371 /// # Arguments
372 ///
373 /// * `f` - A closure or function that takes a `Digit` and returns a transformed `Digit`.
374 ///
375 /// # Returns
376 ///
377 /// * `Self` - A new `Ternary` object containing the transformed digits.
378 ///
379 /// # Digit transformations
380 ///
381 /// These methods (unary operators) from the [Digit] type can be called directly.
382 ///
383 /// * Returns either `Pos` or `Neg`:
384 /// * [Digit::possibly]
385 /// * [Digit::necessary]
386 /// * [Digit::contingently]
387 /// * [Digit::ht_not]
388 /// * Returns either `Zero` or `Pos` or `Neg`.
389 /// * [Digit::pre]
390 /// * [Digit::post]
391 /// * `Digit::not`
392 /// * `Digit::neg`
393 /// * [Digit::absolute_positive]
394 /// * [Digit::positive]
395 /// * [Digit::not_negative]
396 /// * [Digit::not_positive]
397 /// * [Digit::negative]
398 /// * [Digit::absolute_negative]
399 ///
400 /// # Examples
401 /// ```
402 /// use balanced_ternary::{Ternary, Digit};
403 ///
404 /// let orig_ternary = Ternary::parse("+0-");
405 /// let transformed = orig_ternary.each(Digit::necessary);
406 /// assert_eq!(transformed.to_string(), "+--");
407 /// let transformed = orig_ternary.each(Digit::positive);
408 /// assert_eq!(transformed.to_string(), "+00");
409 /// let transformed = orig_ternary.each(Digit::not_negative);
410 /// assert_eq!(transformed.to_string(), "++0");
411 /// let transformed = orig_ternary.each(Digit::absolute_negative);
412 /// assert_eq!(transformed.to_string(), "-0-");
413 /// ```
414 pub fn each(&self, f: impl Fn(Digit) -> Digit) -> Self {
415 let mut repr = Ternary::new(vec![]);
416 for digit in self.digits.iter() {
417 repr.digits.push(f(*digit));
418 }
419 repr
420 }
421
422 /// Applies a transformation function to each digit of the balanced ternary number,
423 /// using an additional parameter for the transformation process, returning a new `Ternary`
424 /// object with the transformed digits.
425 ///
426 /// This method keeps the order of the digits unchanged while applying the provided
427 /// transformation function `f` to each digit individually, along with the provided extra
428 /// `other` digit.
429 ///
430 /// # Arguments
431 ///
432 /// * `f` - A closure or function that takes a `Digit` and an additional `Digit`,
433 /// and returns a transformed `Digit`.
434 /// * `other` - An additional `Digit` to be passed to the transformation function `f`.
435 ///
436 /// # Returns
437 ///
438 /// * `Self` - A new `Ternary` object containing the transformed digits.
439 ///
440 /// # Digit transformations
441 ///
442 /// These methods (binary operators) from the [Digit] type can be called directly.
443 ///
444 /// * `Digit::mul`
445 /// * `Digit::div`
446 /// * `Digit::bitand` (k3/p3 and)
447 /// * [Digit::bi3_and]
448 /// * `Digit::bitor` (k3/p3 or)
449 /// * [Digit::bi3_or]
450 /// * `Digit::bitxor` (k3/p3 xor)
451 /// * [Digit::k3_imply]
452 /// * [Digit::k3_equiv]
453 /// * [Digit::bi3_imply]
454 /// * [Digit::l3_imply]
455 /// * [Digit::rm3_imply]
456 /// * [Digit::ht_imply]
457 ///
458 /// # Examples
459 /// ```
460 /// use std::ops::Mul;
461 /// use balanced_ternary::{Ternary, Digit};
462 ///
463 /// let original = Ternary::parse("+-0");
464 /// let transformed = original.each_with(Digit::mul, Digit::Neg);
465 /// assert_eq!(transformed.to_string(), "-+0");
466 /// ```
467 pub fn each_with(&self, f: impl Fn(Digit, Digit) -> Digit, other: Digit) -> Self {
468 let mut repr = Ternary::new(vec![]);
469 for digit in self.digits.iter() {
470 repr.digits.push(f(*digit, other));
471 }
472 repr
473 }
474
475
476 /// Applies a transformation function to each digit of the balanced ternary number,
477 /// along with a corresponding digit from another `Ternary` number.
478 ///
479 /// This method ensures that the digits of both `Ternary` objects are aligned from the least
480 /// significant to the most significant digit. If the `other` `Ternary` has fewer digits
481 /// than the current one, the process is reversed to handle the shorter `Ternary` consistently.
482 /// The result is a new `Ternary` object where each digit was transformed using the provided function `f`.
483 ///
484 /// # Arguments
485 ///
486 /// * `f` - A closure or function that takes two arguments:
487 /// * a `Digit` from the current `Ternary`,
488 /// * a `Digit` from the corresponding position in the `other` `Ternary`.
489 /// * The function must return a transformed `Digit`.
490 /// * `other` - A `Ternary` object with digits to process alongside the digits of the current object.
491 ///
492 /// # Returns
493 ///
494 /// * `Self` - A new `Ternary` object containing the transformed digits.
495 ///
496 /// # Examples
497 ///
498 /// ```
499 /// use std::ops::Mul;
500 /// use balanced_ternary::{Ternary, Digit};
501 ///
502 /// let ternary1 = Ternary::parse("-+0-+0-+0");
503 /// let ternary2 = Ternary::parse("---000+++");
504 ///
505 /// let result = ternary1.each_zip(Digit::mul, ternary2.clone());
506 /// assert_eq!(result.to_string(), "+-0000-+0");
507 ///
508 /// let result = ternary1.each_zip(Digit::k3_imply, ternary2.clone());
509 /// assert_eq!(result.to_string(), "+-0+00+++");
510 /// let result = ternary1.each_zip(Digit::bi3_imply, ternary2.clone());
511 /// assert_eq!(result.to_string(), "+-0000++0");
512 /// let result = ternary1.each_zip(Digit::ht_imply, ternary2.clone());
513 /// assert_eq!(result.to_string(), "+--+0++++");
514 /// ```
515 pub fn each_zip(&self, f: impl Fn(Digit, Digit) -> Digit, other: Self) -> Self {
516 if self.digits.len() < other.digits.len() {
517 return other.each_zip(f, self.clone());
518 }
519 let mut repr = Ternary::new(vec![]);
520 for (i, digit) in self.digits.iter().rev().enumerate() {
521 let d_other = other.get_digit(i).unwrap();
522 let res= f(*digit, *d_other);
523 repr.digits.push(res);
524 }
525 repr.digits.reverse();
526 repr
527 }
528
529 /// Applies a transformation function to each digit of the balanced ternary number,
530 /// along with a corresponding digit from another `Ternary` number, and a carry digit.
531 ///
532 /// This method processes the digits in reverse order (from the least significant to the most significant),
533 /// keeping their transformed order correct by reversing the result afterward. Each digit from the
534 /// current `Ternary` object is processed with the corresponding digit from another `Ternary` object
535 /// and a carry digit using the provided closure or function `f`.
536 ///
537 /// # Arguments
538 ///
539 /// * `f` - A closure or function that takes three arguments:
540 /// * a `Digit` from the current `Ternary`,
541 /// * a `Digit` from the corresponding position in the `other` `Ternary`,
542 /// * and the current carry `Digit`.
543 /// * The function must return a tuple containing `(carry: Digit, transformed: Digit)`.
544 /// * `other` - A `Ternary` object with digits to process alongside the digits of the current object.
545 ///
546 /// # Returns
547 ///
548 /// * `Self` - A new `Ternary` object containing the transformed digits.
549 ///
550 /// # Notes
551 ///
552 /// The carry digit is initially `Zero` and is passed between each step of the transformation process.
553 /// If the `other` `Ternary` has fewer digits than the current one, the missing digits in `other`
554 /// are treated as `Zero`.
555 ///
556 /// # Examples
557 ///
558 /// ```
559 /// use balanced_ternary::{Digit, Ternary};
560 ///
561 /// let ternary1 = Ternary::parse("+-0");
562 /// let ternary2 = Ternary::parse("-+0");
563 ///
564 /// // Transformation function that adds digits with a carry digit
565 /// let combine = |d1: Digit, d2: Digit, carry: Digit| -> (Digit, Digit) {
566 /// // Simple example operation: this just illustrates transforming with carry.
567 /// // Replace with meaningful logic as needed for your application.
568 /// let sum = d1.to_i8() + d2.to_i8() + carry.to_i8();
569 /// (Digit::from_i8(sum / 3), Digit::from_i8(sum % 3))
570 /// };
571 ///
572 /// let result = ternary1.each_zip_carry(combine, ternary2.clone()).trim();
573 /// assert_eq!(result.to_string(), (&ternary1 + &ternary2).to_string());
574 /// ```
575 pub fn each_zip_carry(&self, f: impl Fn(Digit, Digit, Digit) -> (Digit, Digit), other: Self) -> Self {
576 if self.digits.len() < other.digits.len() {
577 return other.each_zip_carry(f, self.clone());
578 }
579 let mut repr = Ternary::new(vec![]);
580 let mut carry = Zero;
581 for (i, digit) in self.digits.iter().rev().enumerate() {
582 let d_other = other.get_digit(i).unwrap();
583 let (c, res) = f(*digit, *d_other, carry);
584 carry = c;
585 repr.digits.push(res);
586 }
587 repr.digits.reverse();
588 repr
589 }
590
591 /// Removes leading `Zero` digits from the `Ternary` number, effectively trimming
592 /// it down to its simplest representation. The resulting `Ternary` number
593 /// will still represent the same value.
594 ///
595 /// # Returns
596 ///
597 /// * `Self` - A new `Ternary` object, trimmed of leading zeros.
598 ///
599 /// # Examples
600 ///
601 /// ```
602 /// use balanced_ternary::{ Neg, Pos, Ternary, Zero};
603 ///
604 /// let ternary = Ternary::new(vec![Zero, Zero, Pos, Neg]);
605 /// let trimmed = ternary.trim();
606 /// assert_eq!(trimmed.to_string(), "+-");
607 /// ```
608 ///
609 /// # Notes
610 ///
611 /// This method does not mutate the original `Ternary` object but returns a new representation.
612 pub fn trim(&self) -> Self {
613 if self.to_dec() == 0 {
614 return Ternary::parse("0");
615 }
616 let mut repr = Ternary::new(vec![]);
617 let mut first_digit = false;
618 for digit in self.digits.iter() {
619 if !first_digit && digit != &Zero {
620 first_digit = true;
621 }
622 if first_digit {
623 repr.digits.push(*digit);
624 }
625 }
626 repr
627 }
628
629 /// Adjusts the representation of the `Ternary` number to have a fixed number of digits.
630 ///
631 /// If the current `Ternary` has fewer digits than the specified `length`, leading zero digits
632 /// will be added to the `Ternary` to match the desired length. If the current `Ternary` has
633 /// more digits than the specified `length`, it will be returned unmodified.
634 ///
635 /// # Arguments
636 ///
637 /// * `length` - The desired length of the `Ternary` number.
638 ///
639 /// # Returns
640 ///
641 /// * `Self` - A new `Ternary` object with the specified fixed length.
642 ///
643 /// # Notes
644 ///
645 /// If `length` is smaller than the existing number of digits, the function does not truncate
646 /// the number but instead returns the original `Ternary` unchanged.
647 ///
648 /// # Examples
649 ///
650 /// ```
651 /// use balanced_ternary::{Ternary, Zero, Pos};
652 ///
653 /// let ternary = Ternary::new(vec![Pos]);
654 /// let fixed = ternary.with_length(5);
655 /// assert_eq!(fixed.to_string(), "0000+");
656 ///
657 /// let fixed = ternary.with_length(1);
658 /// assert_eq!(fixed.to_string(), "+");
659 /// ```
660 pub fn with_length(&self, length: usize) -> Self {
661 if length < self.log() {
662 return self.clone();
663 }
664 let zeroes = vec![Zero; length - self.log()];
665 let mut repr = Ternary::new(vec![]);
666 repr.digits.extend(zeroes);
667 repr.digits.extend(self.digits.iter().cloned());
668 repr
669 }
670
671
672 /// Converts the `Ternary` number into a string representation by applying a given
673 /// transformation function to each digit of the ternary number.
674 ///
675 /// # Arguments
676 ///
677 /// * `transform` - A function or closure that takes a `Digit` and returns a `char`, representing the digit.
678 ///
679 /// # Returns
680 ///
681 /// A `String`-based representation of the `Ternary` number resulting from
682 /// applying the transformation to its digits.
683 ///
684 /// # Examples
685 ///
686 /// ```
687 /// use balanced_ternary::{Digit, Pos, Neg, Zero, Ternary};
688 ///
689 /// let ternary = Ternary::new(vec![Pos, Zero, Neg]);
690 ///
691 /// let custom_repr = ternary.to_string_repr(Digit::to_char_t);
692 /// assert_eq!(custom_repr, "10T");
693 /// let custom_repr = ternary.to_string_repr(Digit::to_char_theta);
694 /// assert_eq!(custom_repr, "10Θ");
695 /// let custom_repr = ternary.to_string_repr(Digit::to_char);
696 /// assert_eq!(custom_repr, "+0-");
697 /// ```
698 ///
699 /// # Notes
700 ///
701 /// * The function provides flexibility to define custom string representations
702 /// for the ternary number digits.
703 /// * Call to `Ternary::to_string()` is equivalent to `Ternary::to_string_repr(Digit::to_char)`.
704 pub fn to_string_repr<F: Fn(&Digit) -> char>(&self, transform: F) -> String {
705 let mut str = String::new();
706 for digit in self.digits.iter() {
707 str.push(transform(digit));
708 }
709 str
710 }
711}
712
713impl Display for Ternary {
714 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
715 write!(f, "{}", self.to_string_repr(Digit::to_char))
716 }
717}
718
719pub mod operations;
720
721pub mod conversions;
722
723#[cfg(feature = "tryte")]
724pub mod tryte;
725
726#[cfg(feature = "tryte")]
727pub use crate::tryte::Tryte;
728
729#[cfg(test)]
730#[test]
731fn test_ternary() {
732 use crate::*;
733
734 let repr5 = Ternary::new(vec![Pos, Neg, Neg]);
735 assert_eq!(repr5.to_dec(), 5);
736 let repr5 = Ternary::from_dec(5);
737 assert_eq!(repr5.to_dec(), 5);
738
739 let repr13 = Ternary::new(vec![Pos, Pos, Pos]);
740 assert_eq!(repr13.to_dec(), 13);
741
742 let repr14 = Ternary::parse("+---");
743 let repr15 = Ternary::parse("+--0");
744 assert_eq!(repr14.to_dec(), 14);
745 assert_eq!(repr15.to_dec(), 15);
746 assert_eq!(repr14.to_string(), "+---");
747 assert_eq!(repr15.to_string(), "+--0");
748
749 let repr120 = Ternary::from_dec(120);
750 assert_eq!(repr120.to_dec(), 120);
751 assert_eq!(repr120.to_string(), "++++0");
752 let repr121 = Ternary::from_dec(121);
753 assert_eq!(repr121.to_dec(), 121);
754 assert_eq!(repr121.to_string(), "+++++");
755
756 let repr_neg_5 = Ternary::parse("-++");
757 assert_eq!(repr_neg_5.to_dec(), -5);
758 assert_eq!(repr_neg_5.to_string(), "-++");
759
760 let repr_neg_5 = Ternary::from_dec(-5);
761 assert_eq!(repr_neg_5.to_dec(), -5);
762 assert_eq!(repr_neg_5.to_string(), "-++");
763
764 let repr_neg_121 = Ternary::from_dec(-121);
765 assert_eq!(repr_neg_121.to_dec(), -121);
766 assert_eq!(repr_neg_121.to_string(), "-----");
767
768 let test = Ternary::from_dec(18887455);
769 assert_eq!(test.to_dec(), 18887455);
770 assert_eq!(test.to_string(), "++00--0--+-0++0+");
771
772 let unbalanced = Ternary::from_unbalanced("12");
773 assert_eq!(unbalanced.to_dec(), 5);
774 assert_eq!(unbalanced.to_string(), "+--");
775
776 let unbalanced = Ternary::from_unbalanced("-12");
777 assert_eq!(unbalanced.to_dec(), -5);
778 assert_eq!(unbalanced.to_string(), "-++");
779
780 let unbalanced = Ternary::from_dec(121);
781 assert_eq!(unbalanced.to_unbalanced(), "11111");
782 assert_eq!(unbalanced.to_string(), "+++++");
783}