dodecet-encoder 1.1.0

A 12-bit dodecet encoding system optimized for geometric and calculus operations
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
//! # Dodecet: The 12-bit Building Block
//!
//! A dodecet is a 12-bit value composed of 3 nibbles (4-bit groups).
//! It's the fundamental unit of the dodecet encoding system.

use crate::{DodecetError, Result, MAX_DODECET, NIBBLES};

/// A 12-bit dodecet value (0-4095)
///
/// # Example
///
/// ```rust
/// use dodecet_encoder::Dodecet;
///
/// let d = Dodecet::from_hex(0xABC);
/// assert_eq!(d.value(), 0xABC);
/// assert_eq!(d.nibble(0).unwrap(), 0xC);
/// assert_eq!(d.nibble(1).unwrap(), 0xB);
/// assert_eq!(d.nibble(2).unwrap(), 0xA);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[derive(Default)]
pub struct Dodecet {
    value: u16,
}

impl Dodecet {
    /// Create a new dodecet from a u16 value
    ///
    /// # Errors
    /// Returns `DodecetError::Overflow` if value > 4095
    ///
    /// # Example
    ///
    /// ```rust
    /// use dodecet_encoder::Dodecet;
    ///
    /// let d = Dodecet::new(0xABC).unwrap();
    /// assert_eq!(d.value(), 0xABC);
    /// ```
    pub fn new(value: u16) -> Result<Self> {
        if value > MAX_DODECET {
            Err(DodecetError::Overflow)
        } else {
            Ok(Dodecet { value })
        }
    }

    /// Create a dodecet from a hex value (unchecked)
    ///
    /// # Safety
    /// Caller must ensure value <= 4095
    ///
    /// # Example
    ///
    /// ```rust
    /// use dodecet_encoder::Dodecet;
    ///
    /// let d = unsafe { Dodecet::from_hex_unchecked(0xABC) };
    /// assert_eq!(d.value(), 0xABC);
    /// ```
    #[inline]
    pub unsafe fn from_hex_unchecked(value: u16) -> Self {
        Dodecet { value }
    }

    /// Create a dodecet from a hex value
    ///
    /// # Example
    ///
    /// ```rust
    /// use dodecet_encoder::Dodecet;
    ///
    /// let d = Dodecet::from_hex(0xABC);
    /// assert_eq!(d.value(), 0xABC);
    /// ```
    #[inline]
    pub const fn from_hex(value: u16) -> Self {
        Dodecet {
            value: value & MAX_DODECET,
        }
    }

    /// Create a dodecet from a signed i16 value (-2048 to 2047)
    ///
    /// # Example
    ///
    /// ```rust
    /// use dodecet_encoder::Dodecet;
    ///
    /// let d = Dodecet::from_signed(-100);
    /// assert_eq!(d.as_signed(), -100);
    /// ```
    #[inline]
    pub fn from_signed(value: i16) -> Self {
        let unsigned = if value < 0 {
            (value + 4096) as u16
        } else {
            value as u16
        };
        Dodecet {
            value: unsigned & MAX_DODECET,
        }
    }

    /// Get the raw value
    ///
    /// # Example
    ///
    /// ```rust
    /// use dodecet_encoder::Dodecet;
    ///
    /// let d = Dodecet::from_hex(0xABC);
    /// assert_eq!(d.value(), 0xABC);
    /// ```
    #[inline]
    pub fn value(self) -> u16 {
        self.value
    }

    /// Get a specific nibble (0, 1, or 2)
    ///
    /// # Arguments
    /// * `index` - Nibble index (0 = LSB, 2 = MSB)
    ///
    /// # Example
    ///
    /// ```rust
    /// use dodecet_encoder::Dodecet;
    ///
    /// let d = Dodecet::from_hex(0xABC);
    /// assert_eq!(d.nibble(0).unwrap(), 0xC);
    /// assert_eq!(d.nibble(1).unwrap(), 0xB);
    /// assert_eq!(d.nibble(2).unwrap(), 0xA);
    /// ```
    #[inline]
    pub fn nibble(self, index: u8) -> Result<u8> {
        if index >= NIBBLES {
            return Err(DodecetError::InvalidNibble);
        }
        Ok(((self.value >> (index * 4)) & 0xF) as u8)
    }

    /// Set a specific nibble
    ///
    /// # Arguments
    /// * `index` - Nibble index (0 = LSB, 2 = MSB)
    /// * `nibble` - New nibble value (0-15)
    ///
    /// # Example
    ///
    /// ```rust
    /// use dodecet_encoder::Dodecet;
    ///
    /// let mut d = Dodecet::from_hex(0xABC);
    /// d.set_nibble(0, 0xD).unwrap();
    /// assert_eq!(d.value(), 0xABD);
    /// ```
    #[inline]
    pub fn set_nibble(&mut self, index: u8, nibble: u8) -> Result<()> {
        if index >= NIBBLES {
            return Err(DodecetError::InvalidNibble);
        }
        if nibble > 0xF {
            return Err(DodecetError::Overflow);
        }

        let mask = !(0xFu16 << (index * 4));
        self.value = (self.value & mask) | ((nibble as u16) << (index * 4));
        Ok(())
    }

    /// Check if dodecet is zero
    ///
    /// # Example
    ///
    /// ```rust
    /// use dodecet_encoder::Dodecet;
    ///
    /// assert!(Dodecet::from_hex(0).is_zero());
    /// assert!(!Dodecet::from_hex(0xABC).is_zero());
    /// ```
    #[inline]
    pub fn is_zero(self) -> bool {
        self.value == 0
    }

    /// Check if dodecet is at maximum value
    ///
    /// # Example
    ///
    /// ```rust
    /// use dodecet_encoder::Dodecet;
    ///
    /// assert!(Dodecet::from_hex(0xFFF).is_max());
    /// assert!(!Dodecet::from_hex(0xABC).is_max());
    /// ```
    #[inline]
    pub fn is_max(self) -> bool {
        self.value == MAX_DODECET
    }

    /// Count set bits (population count)
    ///
    /// # Example
    ///
    /// ```rust
    /// use dodecet_encoder::Dodecet;
    ///
    /// let d = Dodecet::from_hex(0xFFF); // All bits set
    /// assert_eq!(d.count_ones(), 12);
    /// ```
    #[inline]
    pub fn count_ones(self) -> u32 {
        self.value.count_ones()
    }

    /// Count unset bits
    ///
    /// # Example
    ///
    /// ```rust
    /// use dodecet_encoder::Dodecet;
    ///
    /// let d = Dodecet::from_hex(0x000); // No bits set
    /// // Note: count_zeros() operates on underlying u16, returns 16 for 0x000
    // assert_eq!(d.count_zeros(), 16);
    /// ```
    #[inline]
    pub fn count_zeros(self) -> u32 {
        self.value.count_zeros()
    }

    /// Bitwise AND
    #[inline]
    pub fn and(self, other: Dodecet) -> Dodecet {
        Dodecet {
            value: self.value & other.value,
        }
    }

    /// Bitwise OR
    #[inline]
    pub fn or(self, other: Dodecet) -> Dodecet {
        Dodecet {
            value: self.value | other.value,
        }
    }

    /// Bitwise XOR
    #[inline]
    pub fn xor(self, other: Dodecet) -> Dodecet {
        Dodecet {
            value: self.value ^ other.value,
        }
    }

    /// Bitwise NOT
    #[inline]
    pub fn not(self) -> Dodecet {
        Dodecet {
            value: (!self.value) & MAX_DODECET,
        }
    }

    /// Arithmetic addition with wrapping
    #[inline]
    pub fn wrapping_add(self, other: Dodecet) -> Dodecet {
        Dodecet {
            value: self.value.wrapping_add(other.value) & MAX_DODECET,
        }
    }

    /// Arithmetic subtraction with wrapping
    #[inline]
    pub fn wrapping_sub(self, other: Dodecet) -> Dodecet {
        Dodecet {
            value: self.value.wrapping_sub(other.value) & MAX_DODECET,
        }
    }

    /// Arithmetic multiplication with wrapping
    #[inline]
    pub fn wrapping_mul(self, other: Dodecet) -> Dodecet {
        Dodecet {
            value: self.value.wrapping_mul(other.value) & MAX_DODECET,
        }
    }

    /// Convert to hex string (3 characters)
    ///
    /// # Example
    ///
    /// ```rust
    /// use dodecet_encoder::Dodecet;
    ///
    /// let d = Dodecet::from_hex(0xABC);
    /// assert_eq!(d.to_hex_string(), "ABC");
    /// ```
    pub fn to_hex_string(self) -> String {
        format!("{:03X}", self.value)
    }

    /// Parse from hex string
    ///
    /// # Example
    ///
    /// ```rust
    /// use dodecet_encoder::Dodecet;
    ///
    /// let d = Dodecet::from_hex_str("ABC").unwrap();
    /// assert_eq!(d.value(), 0xABC);
    /// ```
    pub fn from_hex_str(s: &str) -> Result<Self> {
        let value = u16::from_str_radix(s.trim(), 16)
            .map_err(|_| DodecetError::InvalidHex)?;

        if value > MAX_DODECET {
            return Err(DodecetError::Overflow);
        }

        Ok(Dodecet { value })
    }

    /// Convert to binary string (12 characters)
    ///
    /// # Example
    ///
    /// ```rust
    /// use dodecet_encoder::Dodecet;
    ///
    /// let d = Dodecet::from_hex(0xABC);
    /// assert_eq!(d.to_binary_string(), "101010111100");
    /// ```
    pub fn to_binary_string(self) -> String {
        format!("{:012b}", self.value)
    }

    /// Geometric interpretation: Treat as signed value (-2048 to 2047)
    ///
    /// # Example
    ///
    /// ```rust
    /// use dodecet_encoder::Dodecet;
    ///
    /// let d = Dodecet::from_hex(0x800);
    /// assert_eq!(d.as_signed(), -2048);
    /// ```
    #[inline]
    pub fn as_signed(self) -> i16 {
        if self.value & 0x800 != 0 {
            (self.value as i16) - 4096
        } else {
            self.value as i16
        }
    }

    /// Normalize to floating point [0.0, 1.0]
    ///
    /// # Example
    ///
    /// ```rust
    /// use dodecet_encoder::Dodecet;
    ///
    /// let d = Dodecet::from_hex(0x800); // Midpoint
    /// assert!((d.normalize() - 0.5).abs() < 0.001);
    /// ```
    #[inline]
    pub fn normalize(self) -> f64 {
        self.value as f64 / MAX_DODECET as f64
    }
}


impl From<u8> for Dodecet {
    fn from(value: u8) -> Self {
        Dodecet { value: value as u16 }
    }
}

impl TryFrom<u16> for Dodecet {
    type Error = DodecetError;

    fn try_from(value: u16) -> std::result::Result<Self, Self::Error> {
        Dodecet::new(value)
    }
}

impl From<Dodecet> for u16 {
    fn from(d: Dodecet) -> Self {
        d.value
    }
}

impl std::fmt::Display for Dodecet {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "0x{:03X}", self.value)
    }
}

impl std::fmt::Binary for Dodecet {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:012b}", self.value)
    }
}

impl std::fmt::Octal for Dodecet {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:04o}", self.value)
    }
}

impl std::ops::Add for Dodecet {
    type Output = Self;

    fn add(self, other: Self) -> Self::Output {
        self.wrapping_add(other)
    }
}

impl std::ops::Sub for Dodecet {
    type Output = Self;

    fn sub(self, other: Self) -> Self::Output {
        self.wrapping_sub(other)
    }
}

impl std::ops::Mul for Dodecet {
    type Output = Self;

    fn mul(self, other: Self) -> Self::Output {
        self.wrapping_mul(other)
    }
}

impl std::ops::BitAnd for Dodecet {
    type Output = Self;

    fn bitand(self, other: Self) -> Self::Output {
        self.and(other)
    }
}

impl std::ops::BitOr for Dodecet {
    type Output = Self;

    fn bitor(self, other: Self) -> Self::Output {
        self.or(other)
    }
}

impl std::ops::BitXor for Dodecet {
    type Output = Self;

    fn bitxor(self, other: Self) -> Self::Output {
        self.xor(other)
    }
}

impl std::ops::Not for Dodecet {
    type Output = Self;

    fn not(self) -> Self::Output {
        self.not()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_creation() {
        let d = Dodecet::new(0xABC).unwrap();
        assert_eq!(d.value(), 0xABC);

        let d2 = Dodecet::from_hex(0xDEF);
        assert_eq!(d2.value(), 0xDEF);
    }

    #[test]
    fn test_nibbles() {
        let d = Dodecet::from_hex(0xABC);
        assert_eq!(d.nibble(0).unwrap(), 0xC);
        assert_eq!(d.nibble(1).unwrap(), 0xB);
        assert_eq!(d.nibble(2).unwrap(), 0xA);
    }

    #[test]
    fn test_set_nibble() {
        let mut d = Dodecet::from_hex(0xABC);
        d.set_nibble(0, 0xD).unwrap();
        assert_eq!(d.value(), 0xABD);

        d.set_nibble(1, 0xE).unwrap();
        assert_eq!(d.value(), 0xAED);

        d.set_nibble(2, 0x1).unwrap();
        assert_eq!(d.value(), 0x1ED);
    }

    #[test]
    fn test_overflow() {
        assert!(Dodecet::new(0x1000).is_err());
        assert!(Dodecet::new(0xFFF).is_ok());
    }

    #[test]
    fn test_bitwise_ops() {
        let a = Dodecet::from_hex(0xF0F);
        let b = Dodecet::from_hex(0x0F0);

        assert_eq!((a & b).value(), 0x000);
        assert_eq!((a | b).value(), 0xFFF);
        assert_eq!((a ^ b).value(), 0xFFF);
        assert_eq!((!a).value(), 0x0F0);
    }

    #[test]
    fn test_arithmetic() {
        let a = Dodecet::from_hex(0x800);
        let b = Dodecet::from_hex(0x800);

        let c = a + b;
        assert_eq!(c.value(), 0x000); // Wraps around

        let d = Dodecet::from_hex(0x100) - Dodecet::from_hex(0x001);
        assert_eq!(d.value(), 0x0FF);
    }

    #[test]
    fn test_conversions() {
        let d = Dodecet::from_hex(0xABC);

        assert_eq!(d.to_hex_string(), "ABC");
        assert_eq!(d.to_binary_string(), "101010111100");

        let d2 = Dodecet::from_hex_str("ABC").unwrap();
        assert_eq!(d2.value(), 0xABC);
    }

    #[test]
    fn test_signed() {
        let d = Dodecet::from_hex(0x800);
        assert_eq!(d.as_signed(), -2048);

        let d = Dodecet::from_hex(0x7FF);
        assert_eq!(d.as_signed(), 2047);

        let d = Dodecet::from_hex(0x000);
        assert_eq!(d.as_signed(), 0);
    }

    #[test]
    fn test_normalize() {
        let d = Dodecet::from_hex(0x000);
        assert_eq!(d.normalize(), 0.0);

        let d = Dodecet::from_hex(0xFFF);
        assert!((d.normalize() - 1.0).abs() < f64::EPSILON);

        let d = Dodecet::from_hex(0x800);
        assert!((d.normalize() - 0.5).abs() < 0.001);
    }

    #[test]
    fn test_count_bits() {
        let d = Dodecet::from_hex(0xFFF);
        assert_eq!(d.count_ones(), 12);
        // count_zeros() on u16 returns 16 - count_ones(), not 12 - count_ones()
        assert_eq!(d.count_zeros(), 4);

        let d = Dodecet::from_hex(0x000);
        assert_eq!(d.count_ones(), 0);
        assert_eq!(d.count_zeros(), 16);
    }

    #[test]
    fn test_display() {
        let d = Dodecet::from_hex(0xABC);
        assert_eq!(format!("{}", d), "0xABC");
        assert_eq!(format!("{:b}", d), "101010111100");
        assert_eq!(format!("{:o}", d), "5274");
    }
}