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
use std::{
    convert::TryFrom,
    slice,
};

pub mod bigint;
pub mod num_conversions;
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 = "serde1")]
mod serde;

use crate::raw::{
    RawEncoding,
    RawEncodingBuf,
};
use std::{
    any,
    borrow::{
        Borrow,
        BorrowMut,
    },
    cmp::{
        self,
        Ordering,
    },
    fmt,
    hash,
    iter::FromIterator,
    ops::{
        Deref,
        DerefMut,
        Index,
        IndexMut,
        Range,
    },
    ptr,
};

// Reexports
pub use crate::{
    t1b1::{
        T1B1Buf,
        T1B1,
    },
    t2b1::{
        T2B1Buf,
        T2B1,
    },
    t3b1::{
        T3B1Buf,
        T3B1,
    },
    t4b1::{
        T4B1Buf,
        T4B1,
    },
    t5b1::{
        T5B1Buf,
        T5B1,
    },
    trit::{
        Btrit,
        ShiftTernary,
        Trit,
        Utrit,
    },
    tryte::{
        Tryte,
        TryteBuf,
        MAX_TRYTE_VALUE,
        MIN_TRYTE_VALUE,
    },
};

#[derive(Debug)]
pub enum Error {
    InvalidRepr,
}

#[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().all(T::is_valid));
        &*(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().all(T::is_valid));
        &mut *(T::from_raw_unchecked(raw, num_trits) as *const _ as *mut _)
    }

    pub fn try_from_raw(raw: &[i8], num_trits: usize) -> Result<&Self, Error> {
        if raw.iter().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().all(T::is_valid) {
            Ok(unsafe { Self::from_raw_unchecked_mut(raw, num_trits) })
        } else {
            Err(Error::InvalidRepr)
        }
    }

    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Will panic if slice is not byte-aligned
    // TODO: Evaluate whether this API makes sense to be `unsafe`
    pub fn as_i8_slice(&self) -> &[i8] {
        self.0.as_i8_slice()
    }

    /// Will panic if slice is not byte-aligned
    // TODO: Evaluate whether this API makes sense to be `unsafe`
    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.len());
        self.0.get_unchecked(index)
    }

    pub unsafe fn set_unchecked(&mut self, index: usize, trit: T::Trit) {
        debug_assert!(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) {
        if index < self.0.len() {
            unsafe { self.set_unchecked(index, trit) };
        } else {
            panic!(
                "Attempt to set trit at index {}, but length of slice is {}",
                index,
                self.len()
            );
        }
    }

    pub fn trits(&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 slice(&self, range: Range<usize>) -> &Self {
        assert!(range.end >= range.start && range.end <= self.len());
        unsafe { &*(self.0.slice_unchecked(range) as *const _ as *const Self) }
    }

    pub fn slice_mut(&mut self, range: Range<usize>) -> &mut Self {
        assert!(range.end >= range.start && range.end <= self.len());
        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());
        for (i, trit) in trits.trits().enumerate() {
            unsafe {
                self.set_unchecked(i, trit);
            }
        }
    }

    pub fn fill(&mut self, trit: T::Trit) {
        for i in 0..self.len() {
            self.set(i, trit);
        }
    }

    pub fn to_buf<U>(&self) -> TritBuf<U>
    where
        U: RawEncodingBuf,
        U::Slice: RawEncoding<Trit = T::Trit>,
    {
        self.trits().collect()
    }

    pub fn chunks(
        &self,
        chunk_len: usize,
    ) -> impl DoubleEndedIterator<Item = &Self> + ExactSizeIterator<Item = &Self> + '_ {
        assert!(chunk_len > 0);
        (0..self.len())
            .step_by(chunk_len)
            .map(move |i| self.slice(i..(i + chunk_len).min(self.len())))
    }

    pub fn encode<U>(&self) -> TritBuf<U>
    where
        U: RawEncodingBuf,
        U::Slice: RawEncoding<Trit = T::Trit>,
    {
        self.trits().collect()
    }
}

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()
    }

    // Q: Why isn't this method on Trits<T>?
    // A: Because overlapping slice lifetimes make this unsound on squashed encodings
    pub fn chunks_mut(&mut self, chunk_len: usize) -> impl Iterator<Item = &mut Self> + '_ {
        assert!(chunk_len > 0);
        (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)
        })
    }

    pub fn copy_raw_bytes(&mut self, trits: &Trits<T1B1>, offset: usize, count: usize) {
        assert!(self.len() >= offset + count);
        unsafe {
            ptr::copy(
                trits.as_i8_slice().as_ptr(),
                self.as_i8_slice_mut().as_mut_ptr().offset(offset as isize),
                count,
            );
        }
    }

    // Helper
    // TODO: Make this public? Is it needed?
    // Q: Why isn't this method on Trits<T>?
    // A: Because overlapping slice lifetimes make this unsound on squashed encodings
    fn split_at_mut<'a>(this: &mut &'a mut Self, idx: usize) -> (&'a mut Self, &'a mut Self) {
        assert!(idx <= this.len());
        (
            unsafe { &mut *(this.0.slice_unchecked_mut(0..idx) as *mut _ as *mut Self) },
            unsafe { &mut *(this.0.slice_unchecked_mut(idx..this.len()) as *mut _ as *mut Self) },
        )
    }

    pub fn iter<'a>(&'a self) -> slice::Iter<'a, T> {
        self.as_raw_slice().iter()
    }

    pub fn iter_mut<'a>(&'a mut self) -> slice::IterMut<'a, T> {
        self.as_raw_slice_mut().iter_mut()
    }
}

impl Trits<T3B1> {
    /// Will panic if the trit slice is not a multiple of 3 in length, or if the trit slice is not
    /// byte-aligned.
    pub fn as_trytes(&self) -> &[Tryte] {
        assert!(self.len() % 3 == 0);
        unsafe { &*(self.as_i8_slice() as *const _ as *const _) }
    }

    /// Will panic if the trit slice is not a multiple of 3 in length, or if the trit slice is not
    /// byte-aligned.
    pub fn as_trytes_mut(&mut self) -> &mut [Tryte] {
        assert!(self.len() % 3 == 0);
        unsafe { &mut *(self.as_i8_slice_mut() as *mut _ as *mut _) }
    }
}

impl<T, U> cmp::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.trits().zip(other.trits()).all(|(a, b)| a == b)
    }
}

impl<T, U> cmp::PartialOrd<Trits<U>> for Trits<T>
where
    T: RawEncoding + ?Sized,
    U: RawEncoding<Trit = T::Trit> + ?Sized,
    T::Trit: cmp::PartialOrd,
{
    fn partial_cmp(&self, other: &Trits<U>) -> Option<Ordering> {
        if self.len() != other.len() {
            return None;
        }

        for (a, b) in self.trits().zip(other.trits()) {
            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.trits().enumerate() {
            if i != 0 {
                write!(f, ", ")?;
            }
            write!(f, "{:?}", trit)?;
        }
        write!(f, "]")
    }
}

impl<T: RawEncoding + ?Sized> Index<Range<usize>> for Trits<T> {
    type Output = Self;

    fn index(&self, range: Range<usize>) -> &Self::Output {
        self.slice(range)
    }
}

impl<T: RawEncoding + ?Sized> IndexMut<Range<usize>> for Trits<T> {
    fn index_mut(&mut self, range: Range<usize>) -> &mut Self::Output {
        self.slice_mut(range)
    }
}

impl<T: RawEncoding + ?Sized> ToOwned for Trits<T> {
    type Owned = TritBuf<T::Buf>;

    fn to_owned(&self) -> Self::Owned {
        self.to_buf()
    }
}

#[derive(Clone)]
#[repr(transparent)]
pub struct TritBuf<T: RawEncodingBuf = T1B1Buf<Btrit>>(T);

impl<T: RawEncodingBuf> TritBuf<T> {
    pub fn new() -> Self {
        Self(T::new())
    }

    // TODO: Make public when original purged
    fn with_capacity(_cap: usize) -> Self {
        // TODO: Allocate capacity
        Self::new()
    }

    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))
    }

    // TODO: Is this a good API feature? No, it's not. Kill it with fire.
    #[deprecated]
    pub fn from_i8_unchecked(trits: &[i8]) -> Self {
        trits
            .iter()
            .map(|t| <T::Slice as RawEncoding>::Trit::try_from(*t))
            .collect::<Result<Self, _>>()
            .unwrap_or_else(|_| panic!("Invalid i8 when converting to trit."))
    }

    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 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>) }
    }
}

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> 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> Index<Range<usize>> for TritBuf<T> {
    type Output = Trits<T::Slice>;

    fn index(&self, range: Range<usize>) -> &Self::Output {
        self.slice(range)
    }
}

impl<T: RawEncodingBuf> IndexMut<Range<usize>> for TritBuf<T> {
    fn index_mut(&mut self, range: Range<usize>) -> &mut Self::Output {
        self.slice_mut(range)
    }
}

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.trits().enumerate() {
            if i != 0 {
                write!(f, ", ")?;
            }
            write!(f, "{:?}", trit)?;
        }
        write!(f, "]")
    }
}

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()
    }
}