#![deny(missing_docs)]
use core::slice;
pub mod b1t6;
pub mod convert;
pub mod raw;
pub mod t1b1;
pub mod t2b1;
pub mod t3b1;
pub mod t4b1;
pub mod t5b1;
pub mod trit;
pub mod tryte;
#[cfg(feature = "serde")]
mod serde;
use alloc::borrow::ToOwned;
use core::{
any,
borrow::{Borrow, BorrowMut},
cmp::Ordering,
convert::TryFrom,
fmt, hash,
iter::FromIterator,
ops::{
Deref, DerefMut, Index, IndexMut, Neg, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive,
},
};
use self::raw::{RawEncoding, RawEncodingBuf};
pub use self::{
t1b1::{T1B1Buf, T1B1},
t2b1::{T2B1Buf, T2B1},
t3b1::{T3B1Buf, T3B1},
t4b1::{T4B1Buf, T4B1},
t5b1::{T5B1Buf, T5B1},
trit::{Btrit, ShiftTernary, Trit, Utrit},
tryte::{Tryte, TryteBuf},
};
#[derive(Debug)]
pub enum Error {
InvalidRepr,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::InvalidRepr => write!(f, "invalid representation"),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for Error {}
#[derive(Hash)]
#[repr(transparent)]
pub struct Trits<T: RawEncoding + ?Sized = T1B1<Btrit>>(T);
impl<T> Trits<T>
where
T: RawEncoding + ?Sized,
{
pub fn empty() -> &'static Self {
unsafe { &*(T::empty() as *const _ as *const Self) }
}
pub unsafe fn from_raw_unchecked(raw: &[i8], num_trits: usize) -> &Self {
debug_assert!(
raw.iter().copied().all(T::is_valid),
"Invalid i8 slice used to create trit slice"
);
&*(T::from_raw_unchecked(raw, num_trits) as *const _ as *const _)
}
pub unsafe fn from_raw_unchecked_mut(raw: &mut [i8], num_trits: usize) -> &mut Self {
debug_assert!(
raw.iter().copied().all(T::is_valid),
"Invalid i8 slice used to create trit slice"
);
&mut *(T::from_raw_unchecked_mut(raw, num_trits) as *mut _ as *mut _)
}
pub fn try_from_raw(raw: &[i8], num_trits: usize) -> Result<&Self, Error> {
if raw.iter().copied().all(T::is_valid) {
Ok(unsafe { Self::from_raw_unchecked(raw, num_trits) })
} else {
Err(Error::InvalidRepr)
}
}
pub fn try_from_raw_mut(raw: &mut [i8], num_trits: usize) -> Result<&mut Self, Error> {
if raw.iter().copied().all(T::is_valid) {
Ok(unsafe { Self::from_raw_unchecked_mut(raw, num_trits) })
} else {
Err(Error::InvalidRepr)
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn as_i8_slice(&self) -> &[i8] {
self.0.as_i8_slice()
}
pub unsafe fn as_i8_slice_mut(&mut self) -> &mut [i8] {
self.0.as_i8_slice_mut()
}
pub unsafe fn get_unchecked(&self, index: usize) -> T::Trit {
debug_assert!(
index < self.0.len(),
"Attempt to get trit at index {}, but length of slice is {}",
index,
self.len(),
);
self.0.get_unchecked(index)
}
pub unsafe fn set_unchecked(&mut self, index: usize, trit: T::Trit) {
debug_assert!(
index < self.0.len(),
"Attempt to set trit at index {}, but length of slice is {}",
index,
self.len(),
);
self.0.set_unchecked(index, trit);
}
pub fn get(&self, index: usize) -> Option<T::Trit> {
if index < self.0.len() {
unsafe { Some(self.get_unchecked(index)) }
} else {
None
}
}
pub fn set(&mut self, index: usize, trit: T::Trit) {
assert!(
index < self.0.len(),
"Attempt to set trit at index {}, but length of slice is {}",
index,
self.len(),
);
unsafe { self.set_unchecked(index, trit) };
}
pub fn iter(&self) -> impl DoubleEndedIterator<Item = T::Trit> + ExactSizeIterator<Item = T::Trit> + '_ {
(0..self.0.len()).map(move |idx| unsafe { self.0.get_unchecked(idx) })
}
pub fn subslice(&self, range: Range<usize>) -> &Self {
assert!(
range.end >= range.start && range.end <= self.len(),
"Sub-slice range must be within the bounds of the source trit slice",
);
unsafe { &*(self.0.slice_unchecked(range) as *const _ as *const Self) }
}
pub fn subslice_mut(&mut self, range: Range<usize>) -> &mut Self {
assert!(
range.end >= range.start && range.end <= self.len(),
"Sub-slice range must be within the bounds of the source trit slice",
);
unsafe { &mut *(self.0.slice_unchecked_mut(range) as *mut _ as *mut Self) }
}
pub fn copy_from<U: RawEncoding<Trit = T::Trit> + ?Sized>(&mut self, trits: &Trits<U>) {
assert!(
self.len() == trits.len(),
"Source trit slice must be the same length as target"
);
for (i, trit) in trits.iter().enumerate() {
unsafe {
self.set_unchecked(i, trit);
}
}
}
pub fn fill(&mut self, trit: T::Trit) {
for i in 0..self.len() {
unsafe {
self.set_unchecked(i, trit);
}
}
}
pub fn to_buf<U: RawEncodingBuf<Slice = T>>(&self) -> TritBuf<U> {
self.iter().collect()
}
pub fn chunks(
&self,
chunk_len: usize,
) -> impl DoubleEndedIterator<Item = &Self> + ExactSizeIterator<Item = &Self> + '_ {
assert!(chunk_len > 0, "Chunk length must be non-zero");
(0..self.len())
.step_by(chunk_len)
.map(move |i| &self[i..(i + chunk_len).min(self.len())])
}
pub fn encode<U>(&self) -> TritBuf<U>
where
U: RawEncodingBuf,
U::Slice: RawEncoding<Trit = T::Trit>,
{
self.iter().collect()
}
}
impl<T> Trits<T>
where
T: RawEncoding<Trit = Btrit> + ?Sized,
{
pub fn iter_trytes(&self) -> impl DoubleEndedIterator<Item = Tryte> + ExactSizeIterator<Item = Tryte> + '_ {
assert!(self.len() % 3 == 0, "Trit slice length must be a multiple of 3");
self.chunks(3)
.map(|trits| Tryte::from_trits([trits.get(0).unwrap(), trits.get(1).unwrap(), trits.get(2).unwrap()]))
}
pub fn negate(&mut self) {
for i in 0..self.len() {
unsafe {
let t = self.get_unchecked(i);
self.set_unchecked(i, -t);
}
}
}
}
impl<T: Trit> Trits<T1B1<T>> {
pub fn as_raw_slice(&self) -> &[T] {
self.0.as_raw_slice()
}
pub fn as_raw_slice_mut(&mut self) -> &mut [T] {
self.0.as_raw_slice_mut()
}
pub fn chunks_mut(&mut self, chunk_len: usize) -> impl Iterator<Item = &mut Self> + '_ {
assert!(chunk_len > 0, "Chunk length must be non-zero");
(0..self.len()).step_by(chunk_len).scan(self, move |this, _| {
let idx = chunk_len.min(this.len());
let (a, b) = Trits::split_at_mut(this, idx);
*this = b;
Some(a)
})
}
fn split_at_mut<'a>(this: &mut &'a mut Self, mid: usize) -> (&'a mut Self, &'a mut Self) {
assert!(
mid <= this.len(),
"Cannot split at an index outside the trit slice bounds"
);
(
unsafe { &mut *(this.0.slice_unchecked_mut(0..mid) as *mut _ as *mut Self) },
unsafe { &mut *(this.0.slice_unchecked_mut(mid..this.len()) as *mut _ as *mut Self) },
)
}
pub fn iter_mut(&mut self) -> slice::IterMut<T> {
self.as_raw_slice_mut().iter_mut()
}
}
impl<'a, T: Trit> From<&'a [T]> for &'a Trits<T1B1<T>> {
fn from(xs: &'a [T]) -> Self {
unsafe { Trits::from_raw_unchecked(&*(xs as *const _ as *const _), xs.len()) }
}
}
impl<'a, T: Trit> From<&'a mut [T]> for &'a mut Trits<T1B1<T>> {
fn from(xs: &'a mut [T]) -> Self {
unsafe { Trits::from_raw_unchecked_mut(&mut *(xs as *mut _ as *mut _), xs.len()) }
}
}
impl<'a, T: Trit> From<&'a Trits<T1B1<T>>> for &'a [T] {
fn from(trits: &'a Trits<T1B1<T>>) -> Self {
trits.as_raw_slice()
}
}
impl<'a, T: Trit> From<&'a mut Trits<T1B1<T>>> for &'a mut [T] {
fn from(trits: &'a mut Trits<T1B1<T>>) -> Self {
trits.as_raw_slice_mut()
}
}
impl Trits<T3B1> {
pub fn as_trytes(&self) -> &[Tryte] {
assert!(self.len() % 3 == 0, "Trit slice length must be a multiple of 3");
unsafe { &*(self.as_i8_slice() as *const _ as *const _) }
}
pub fn as_trytes_mut(&mut self) -> &mut [Tryte] {
assert!(self.len() % 3 == 0, "Trit slice length must be a multiple of 3");
unsafe { &mut *(self.as_i8_slice_mut() as *mut _ as *mut _) }
}
}
impl<T, U> PartialEq<Trits<U>> for Trits<T>
where
T: RawEncoding + ?Sized,
U: RawEncoding<Trit = T::Trit> + ?Sized,
{
fn eq(&self, other: &Trits<U>) -> bool {
self.len() == other.len() && self.iter().zip(other.iter()).all(|(a, b)| a == b)
}
}
impl<T> Eq for Trits<T> where T: RawEncoding + ?Sized {}
impl<T, U> PartialOrd<Trits<U>> for Trits<T>
where
T: RawEncoding + ?Sized,
U: RawEncoding<Trit = T::Trit> + ?Sized,
T::Trit: PartialOrd,
{
fn partial_cmp(&self, other: &Trits<U>) -> Option<Ordering> {
if self.len() != other.len() {
return None;
}
for (a, b) in self.iter().zip(other.iter()) {
match a.partial_cmp(&b) {
Some(Ordering::Equal) => continue,
other_order => return other_order,
}
}
Some(Ordering::Equal)
}
}
impl<'a, T: RawEncoding + ?Sized> fmt::Debug for &'a Trits<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Trits<{}> [", any::type_name::<T>())?;
for (i, trit) in self.iter().enumerate() {
if i != 0 {
write!(f, ", ")?;
}
write!(f, "{:?}", trit)?;
}
write!(f, "]")
}
}
impl<T: RawEncoding + ?Sized> Index<usize> for Trits<T> {
type Output = T::Trit;
fn index(&self, index: usize) -> &Self::Output {
self.get(index).expect("Index out of range").as_arbitrary_ref()
}
}
impl<T: RawEncoding + ?Sized> Index<Range<usize>> for Trits<T> {
type Output = Self;
fn index(&self, range: Range<usize>) -> &Self::Output {
self.subslice(range)
}
}
impl<T: RawEncoding + ?Sized> IndexMut<Range<usize>> for Trits<T> {
fn index_mut(&mut self, range: Range<usize>) -> &mut Self::Output {
self.subslice_mut(range)
}
}
impl<T: RawEncoding + ?Sized> Index<RangeFrom<usize>> for Trits<T> {
type Output = Self;
fn index(&self, range: RangeFrom<usize>) -> &Self::Output {
self.subslice(range.start..self.len())
}
}
impl<T: RawEncoding + ?Sized> IndexMut<RangeFrom<usize>> for Trits<T> {
fn index_mut(&mut self, range: RangeFrom<usize>) -> &mut Self::Output {
self.subslice_mut(range.start..self.len())
}
}
impl<T: RawEncoding + ?Sized> Index<RangeFull> for Trits<T> {
type Output = Self;
fn index(&self, _range: RangeFull) -> &Self::Output {
self
}
}
impl<T: RawEncoding + ?Sized> IndexMut<RangeFull> for Trits<T> {
fn index_mut(&mut self, _range: RangeFull) -> &mut Self::Output {
self
}
}
impl<T: RawEncoding + ?Sized> Index<RangeInclusive<usize>> for Trits<T> {
type Output = Self;
fn index(&self, range: RangeInclusive<usize>) -> &Self::Output {
self.subslice(*range.start()..*range.end() + 1)
}
}
impl<T: RawEncoding + ?Sized> IndexMut<RangeInclusive<usize>> for Trits<T> {
fn index_mut(&mut self, range: RangeInclusive<usize>) -> &mut Self::Output {
self.subslice_mut(*range.start()..*range.end() + 1)
}
}
impl<T: RawEncoding + ?Sized> Index<RangeTo<usize>> for Trits<T> {
type Output = Self;
fn index(&self, range: RangeTo<usize>) -> &Self::Output {
self.subslice(0..range.end)
}
}
impl<T: RawEncoding + ?Sized> IndexMut<RangeTo<usize>> for Trits<T> {
fn index_mut(&mut self, range: RangeTo<usize>) -> &mut Self::Output {
self.subslice_mut(0..range.end)
}
}
impl<T: RawEncoding + ?Sized> Index<RangeToInclusive<usize>> for Trits<T> {
type Output = Self;
fn index(&self, range: RangeToInclusive<usize>) -> &Self::Output {
self.subslice(0..range.end + 1)
}
}
impl<T: RawEncoding + ?Sized> IndexMut<RangeToInclusive<usize>> for Trits<T> {
fn index_mut(&mut self, range: RangeToInclusive<usize>) -> &mut Self::Output {
self.subslice_mut(0..range.end + 1)
}
}
impl<T: RawEncoding + ?Sized> ToOwned for Trits<T> {
type Owned = TritBuf<T::Buf>;
fn to_owned(&self) -> Self::Owned {
self.to_buf()
}
}
impl<T: RawEncoding + ?Sized> fmt::Display for Trits<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[")?;
for (i, t) in self.iter().enumerate() {
if i != 0 {
write!(f, ", ")?;
}
write!(f, "{}", t)?;
}
write!(f, "]")
}
}
#[derive(Clone)]
#[repr(transparent)]
pub struct TritBuf<T: RawEncodingBuf = T1B1Buf<Btrit>>(T);
impl<T: RawEncodingBuf> TritBuf<T> {
pub fn new() -> Self {
Self::default()
}
pub fn with_capacity(cap: usize) -> Self {
Self(T::with_capacity(cap))
}
pub fn filled(len: usize, trit: <T::Slice as RawEncoding>::Trit) -> Self {
let mut this = Self::with_capacity(len);
for _ in 0..len {
this.push(trit);
}
this
}
pub fn zeros(len: usize) -> Self {
Self::filled(len, <T::Slice as RawEncoding>::Trit::zero())
}
pub fn from_trits(trits: &[<T::Slice as RawEncoding>::Trit]) -> Self {
Self(T::from_trits(trits))
}
pub fn clear(&mut self) {
self.0.clear();
}
pub fn push(&mut self, trit: <T::Slice as RawEncoding>::Trit) {
self.0.push(trit);
}
pub fn pop(&mut self) -> Option<<T::Slice as RawEncoding>::Trit> {
self.0.pop()
}
pub fn append<U: RawEncoding<Trit = <T::Slice as RawEncoding>::Trit> + ?Sized>(&mut self, trits: &Trits<U>) {
trits.iter().for_each(|t| self.push(t));
}
pub fn as_slice(&self) -> &Trits<T::Slice> {
unsafe { &*(self.0.as_slice() as *const T::Slice as *const Trits<T::Slice>) }
}
pub fn as_slice_mut(&mut self) -> &mut Trits<T::Slice> {
unsafe { &mut *(self.0.as_slice_mut() as *mut T::Slice as *mut Trits<T::Slice>) }
}
pub fn capacity(&self) -> usize {
self.0.capacity()
}
}
impl TritBuf<T3B1Buf> {
pub fn pad_zeros(&mut self) {
while self.len() % 3 != 0 {
self.push(Btrit::Zero);
}
}
#[must_use]
pub fn padded_zeros(mut self) -> Self {
self.pad_zeros();
self
}
}
impl<T: RawEncodingBuf> Neg for TritBuf<T>
where
T::Slice: RawEncoding<Trit = Btrit>,
{
type Output = Self;
#[must_use]
fn neg(mut self) -> Self {
self.negate();
self
}
}
impl<T: RawEncodingBuf> TritBuf<T>
where
T::Slice: RawEncoding<Trit = Btrit>,
{
pub fn from_i8s(trits: &[i8]) -> Result<Self, <Btrit as TryFrom<i8>>::Error> {
trits.iter().map(|x| Btrit::try_from(*x)).collect()
}
}
impl<T: RawEncodingBuf> TritBuf<T>
where
T::Slice: RawEncoding<Trit = Utrit>,
{
pub fn from_u8s(trits: &[u8]) -> Result<Self, <Btrit as TryFrom<u8>>::Error> {
trits.iter().map(|x| Utrit::try_from(*x)).collect()
}
}
impl<T: RawEncodingBuf> Default for TritBuf<T> {
fn default() -> Self {
Self(T::new())
}
}
impl<T> TritBuf<T1B1Buf<T>>
where
T: Trit,
T::Target: Trit,
{
pub fn into_shifted(self) -> TritBuf<T1B1Buf<<T as ShiftTernary>::Target>> {
TritBuf(self.0.into_shifted())
}
}
impl<T: RawEncodingBuf, U: RawEncodingBuf> PartialEq<TritBuf<U>> for TritBuf<T>
where
T::Slice: RawEncoding,
U::Slice: RawEncoding<Trit = <T::Slice as RawEncoding>::Trit>,
{
fn eq(&self, other: &TritBuf<U>) -> bool {
self.as_slice() == other.as_slice()
}
}
impl<T: RawEncodingBuf> Eq for TritBuf<T> where T::Slice: RawEncoding {}
impl<T: RawEncodingBuf> Deref for TritBuf<T> {
type Target = Trits<T::Slice>;
fn deref(&self) -> &Self::Target {
self.as_slice()
}
}
impl<T: RawEncodingBuf> DerefMut for TritBuf<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.as_slice_mut()
}
}
impl<T: RawEncodingBuf> FromIterator<<T::Slice as RawEncoding>::Trit> for TritBuf<T> {
fn from_iter<I: IntoIterator<Item = <T::Slice as RawEncoding>::Trit>>(iter: I) -> Self {
let iter = iter.into_iter();
let mut this = Self::with_capacity(iter.size_hint().0);
for trit in iter {
this.push(trit);
}
this
}
}
impl<T> hash::Hash for TritBuf<T>
where
T: RawEncodingBuf,
T::Slice: hash::Hash,
{
fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
(**self).hash(hasher)
}
}
impl<T: RawEncodingBuf> fmt::Debug for TritBuf<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "TritBuf<{}> [", any::type_name::<T>())?;
for (i, trit) in self.iter().enumerate() {
if i != 0 {
write!(f, ", ")?;
}
write!(f, "{:?}", trit)?;
}
write!(f, "]")
}
}
impl<T: RawEncodingBuf> fmt::Display for TritBuf<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.as_slice())
}
}
impl<T: RawEncodingBuf> Borrow<Trits<T::Slice>> for TritBuf<T> {
fn borrow(&self) -> &Trits<T::Slice> {
self.as_slice()
}
}
impl<T: RawEncodingBuf> BorrowMut<Trits<T::Slice>> for TritBuf<T> {
fn borrow_mut(&mut self) -> &mut Trits<T::Slice> {
self.as_slice_mut()
}
}
impl<T, U> PartialOrd<TritBuf<U>> for TritBuf<T>
where
T: RawEncodingBuf,
U: RawEncodingBuf,
U::Slice: RawEncoding<Trit = <T::Slice as RawEncoding>::Trit>,
<T::Slice as RawEncoding>::Trit: PartialOrd,
{
fn partial_cmp(&self, other: &TritBuf<U>) -> Option<Ordering> {
self.as_slice().partial_cmp(other.as_slice())
}
}