tape-core 0.4.7

A decentralized object store using Solana.
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
//! Encoding profile types for erasure-coded track data.

use bytemuck::{Pod, Zeroable};
use num_enum::{IntoPrimitive, TryFromPrimitive};

#[cfg(feature = "wincode")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "wincode")]
use wincode_derive::{SchemaRead, SchemaWrite};


/// Encoding type for erasure-coded track data.
#[repr(u64)]
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, IntoPrimitive, TryFromPrimitive)]
pub enum EncodingType {

    /// Unknown encoding (default for uninitialized tracks).
    #[default]
    Unknown = 0,

    /// Basic encoding - single RS pass, testing only.
    Basic = 1,

    /// Clay encoding - Clay codes with striping and rotation.
    Clay = 2,
}

/// Encoding configuration: type + params.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Pod, Zeroable)]
#[cfg_attr(feature = "wincode", derive(Serialize, Deserialize, SchemaRead, SchemaWrite))]
pub struct EncodingProfile {

    /// Encoding type discriminant (EncodingType as u64).
    pub encoding: u64,

    /// Encoding-specific parameters (e.g., ClayParams packed).
    pub params: u64,

}

impl EncodingProfile {
    /// Get the encoding type.
    #[inline]
    pub fn encoding_type(&self) -> Option<EncodingType> {
        EncodingType::try_from(self.encoding).ok()
    }

    /// Check if this is Clay encoding.
    #[inline]
    pub fn is_clay(&self) -> bool {
        matches!(self.encoding_type(), Some(EncodingType::Clay))
    }

    /// Check if this is Basic encoding.
    #[inline]
    pub fn is_basic(&self) -> bool {
        matches!(self.encoding_type(), Some(EncodingType::Basic))
    }

    /// Create a Clay encoding profile with the given parameters.
    #[inline]
    pub const fn clay(params: ClayParams) -> Self {
        Self {
            encoding: EncodingType::Clay as u64,
            params: params.as_u64(),
        }
    }

    /// Create a Clay encoding profile with default parameters.
    pub fn clay_default() -> Self {
        Self::clay(ClayParams::default())
    }

    /// Get the Clay parameters (only valid if is_clay()).
    #[inline]
    pub const fn clay_params(&self) -> ClayParams {
        ClayParams::from_u64(self.params)
    }

    /// Create a Basic (RS) encoding profile with given parameters.
    #[inline]
    pub const fn basic(params: RSParams) -> Self {
        Self {
            encoding: EncodingType::Basic as u64,
            params: params.as_u64(),
        }
    }

    /// Create a Basic encoding profile with default parameters (k=10, m=10).
    pub fn basic_default() -> Self {
        Self::basic(RSParams::default())
    }

    /// Get the RS parameters (only valid if is_basic()).
    #[inline]
    pub const fn rs_params(&self) -> RSParams {
        RSParams::from_u64(self.params)
    }

    /// Get k (data slices) for any encoding type.
    ///
    /// # Panics
    /// Panics if encoding type is Unknown.
    #[inline]
    pub fn k(&self) -> u8 {
        match self.encoding_type() {
            Some(EncodingType::Clay) => self.clay_params().k(),
            Some(EncodingType::Basic) => self.rs_params().k(),
            Some(EncodingType::Unknown) | None => panic!("cannot get k from Unknown encoding"),
        }
    }

    /// Get m (parity slices) for any encoding type.
    ///
    /// # Panics
    /// Panics if encoding type is Unknown.
    #[inline]
    pub fn m(&self) -> u8 {
        match self.encoding_type() {
            Some(EncodingType::Clay) => self.clay_params().m(),
            Some(EncodingType::Basic) => self.rs_params().m(),
            Some(EncodingType::Unknown) | None => panic!("cannot get m from Unknown encoding"),
        }
    }

    /// Get n (total slices) for any encoding type.
    ///
    /// # Panics
    /// Panics if encoding type is Unknown.
    #[inline]
    pub fn n(&self) -> u8 {
        self.k() + self.m()
    }

    /// Pack into a byte array (for unaligned instruction data).
    pub fn pack(&self) -> [u8; 16] {
        let mut out = [0u8; 16];
        out[..8].copy_from_slice(&self.encoding.to_le_bytes());
        out[8..16].copy_from_slice(&self.params.to_le_bytes());
        out
    }

    /// Unpack from a byte array.
    pub fn unpack(data: [u8; 16]) -> Self {
        Self {
            encoding: u64::from_le_bytes(data[..8].try_into().unwrap()),
            params: u64::from_le_bytes(data[8..16].try_into().unwrap()),
        }
    }

    /// Create an Unknown encoding profile (zeroed).
    #[inline]
    pub const fn unknown() -> Self {
        Self {
            encoding: EncodingType::Unknown as u64,
            params: 0,
        }
    }
}

impl Default for EncodingProfile {
    fn default() -> Self {
        Self::clay_default()
    }
}

/// Clay erasure code parameters, packed into u64.
///
/// Supports Clay codes with parameters:
/// - k: data slices (1-255)
/// - m: parity slices (1-255), where n = k + m
/// - d: helper count for repair (k+1 <= d <= n-1)
///
/// Constraints (from clay-codes):
/// - k >= 1, m >= 1, k + m = n
/// - d >= k + 1, d <= n - 1
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Pod, Zeroable)]
pub struct ClayParams {
    /// Packed parameters: byte 0 = n, byte 1 = k, byte 2 = d
    packed: u64,
}

impl ClayParams {
    /// Create new Clay parameters.
    ///
    /// # Arguments
    /// - `n`: total slices (k + m)
    /// - `k`: data slices needed for reconstruction
    /// - `d`: helper count for repair
    #[inline]
    pub const fn new(n: u8, k: u8, d: u8) -> Self {
        Self {
            packed: (n as u64) | ((k as u64) << 8) | ((d as u64) << 16),
        }
    }

    /// Total slices (n = k + m).
    #[inline]
    pub const fn n(&self) -> u8 {
        (self.packed & 0xFF) as u8
    }

    /// Data slices needed for reconstruction.
    #[inline]
    pub const fn k(&self) -> u8 {
        ((self.packed >> 8) & 0xFF) as u8
    }

    /// Helper count for repair.
    #[inline]
    pub const fn d(&self) -> u8 {
        ((self.packed >> 16) & 0xFF) as u8
    }

    /// Parity slices (m = n - k).
    #[inline]
    pub const fn m(&self) -> u8 {
        self.n().saturating_sub(self.k())
    }

    /// Sub-chunks per chunk: alpha = q^t with q = d - k + 1 and t = ceil(n/q).
    #[inline]
    pub const fn alpha(&self) -> u64 {
        let q = (self.d() - self.k() + 1) as u64;
        let n = self.n() as u64;
        let t = (n + q - 1) / q;
        let mut out = 1u64;
        let mut i = 0;
        while i < t {
            out *= q;
            i += 1;
        }
        out
    }

    /// Encode granularity in bytes: stripe inputs pad to k * alpha * 2.
    #[inline]
    pub const fn stripe_alignment(&self) -> u64 {
        self.k() as u64 * self.alpha() * 2
    }

    /// Convert to raw u64 for storage.
    #[inline]
    pub const fn as_u64(&self) -> u64 {
        self.packed
    }

    /// Create from raw u64.
    #[inline]
    pub const fn from_u64(v: u64) -> Self {
        Self { packed: v }
    }
}

/// Default Clay parameters: n=20, k=7, d=16 -> m=13 parity
impl ClayParams {
    pub const DEFAULT: Self = Self::new(20, 7, 16);
}

impl Default for ClayParams {
    fn default() -> Self {
        Self::DEFAULT
    }
}

/// Reed-Solomon erasure code parameters, packed into u64.
///
/// Basic RS encoding with parameters:
/// - k: data slices (1-255)
/// - m: parity slices (1-255), where n = k + m
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Pod, Zeroable)]
pub struct RSParams {
    /// Packed parameters: byte 0 = n, byte 1 = k
    packed: u64,
}

impl RSParams {
    /// Create new RS parameters.
    ///
    /// # Arguments
    /// - `k`: data slices needed for reconstruction
    /// - `m`: parity slices
    #[inline]
    pub const fn new(k: u8, m: u8) -> Self {
        let n = k + m;
        Self {
            packed: (n as u64) | ((k as u64) << 8),
        }
    }

    /// Total slices (n = k + m).
    #[inline]
    pub const fn n(&self) -> u8 {
        (self.packed & 0xFF) as u8
    }

    /// Data slices needed for reconstruction.
    #[inline]
    pub const fn k(&self) -> u8 {
        ((self.packed >> 8) & 0xFF) as u8
    }

    /// Parity slices (m = n - k).
    #[inline]
    pub const fn m(&self) -> u8 {
        self.n().saturating_sub(self.k())
    }

    /// Convert to raw u64 for storage.
    #[inline]
    pub const fn as_u64(&self) -> u64 {
        self.packed
    }

    /// Create from raw u64.
    #[inline]
    pub const fn from_u64(v: u64) -> Self {
        Self { packed: v }
    }
}

impl Default for RSParams {
    fn default() -> Self {
        // k=10, m=10 (standard default)
        Self::new(10, 10)
    }
}

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

    #[test]
    fn test_clay_params_new() {
        let params = ClayParams::new(20, 10, 19);
        assert_eq!(params.n(), 20);
        assert_eq!(params.k(), 10);
        assert_eq!(params.d(), 19);
        assert_eq!(params.m(), 10);
    }

    #[test]
    fn test_clay_params_default() {
        let params = ClayParams::default();
        assert_eq!(params.n(), 20);
        assert_eq!(params.k(), 7);
        assert_eq!(params.d(), 16);
        assert_eq!(params.m(), 13);
    }

    #[test]
    fn test_clay_params_roundtrip() {
        let params = ClayParams::new(20, 10, 19);
        let packed = params.as_u64();
        let recovered = ClayParams::from_u64(packed);
        assert_eq!(params, recovered);
    }

    #[test]
    fn test_encoding_profile_clay() {
        let params = ClayParams::new(20, 10, 19);
        let profile = EncodingProfile::clay(params);

        assert!(profile.is_clay());
        assert!(!profile.is_basic());
        assert_eq!(profile.encoding_type(), Some(EncodingType::Clay));
        assert_eq!(profile.clay_params(), params);
    }

    #[test]
    fn test_encoding_profile_clay_default() {
        let profile = EncodingProfile::clay_default();
        assert!(profile.is_clay());
        assert_eq!(profile.clay_params(), ClayParams::default());
    }

    #[test]
    fn test_encoding_profile_basic() {
        let params = RSParams::new(10, 10);
        let profile = EncodingProfile::basic(params);

        assert!(profile.is_basic());
        assert!(!profile.is_clay());
        assert_eq!(profile.encoding_type(), Some(EncodingType::Basic));
        assert_eq!(profile.rs_params(), params);
    }

    #[test]
    fn test_encoding_profile_basic_default() {
        let profile = EncodingProfile::basic_default();
        assert!(profile.is_basic());
        assert_eq!(profile.rs_params(), RSParams::default());
        assert_eq!(profile.k(), 10);
        assert_eq!(profile.m(), 10);
        assert_eq!(profile.n(), 20);
    }

    #[test]
    fn test_rs_params_new() {
        let params = RSParams::new(10, 10);
        assert_eq!(params.n(), 20);
        assert_eq!(params.k(), 10);
        assert_eq!(params.m(), 10);
    }

    #[test]
    fn test_rs_params_default() {
        let params = RSParams::default();
        assert_eq!(params.n(), 20);
        assert_eq!(params.k(), 10);
        assert_eq!(params.m(), 10);
    }

    #[test]
    fn test_rs_params_roundtrip() {
        let params = RSParams::new(8, 4);
        let packed = params.as_u64();
        let recovered = RSParams::from_u64(packed);
        assert_eq!(params, recovered);
    }

    #[test]
    fn test_rs_params_size() {
        assert_eq!(std::mem::size_of::<RSParams>(), 8);
    }

    #[test]
    fn test_profile_k_m_n_clay() {
        let profile = EncodingProfile::clay_default();
        assert_eq!(profile.k(), 7);
        assert_eq!(profile.m(), 13);
        assert_eq!(profile.n(), 20);
    }

    #[test]
    fn test_profile_k_m_n_basic() {
        let profile = EncodingProfile::basic(RSParams::new(8, 4));
        assert_eq!(profile.k(), 8);
        assert_eq!(profile.m(), 4);
        assert_eq!(profile.n(), 12);
    }

    #[test]
    #[should_panic(expected = "cannot get k from Unknown encoding")]
    fn test_profile_k_unknown_panics() {
        let profile = EncodingProfile::unknown();
        let _ = profile.k();
    }

    #[test]
    fn test_encoding_profile_unknown() {
        let profile = EncodingProfile::unknown();
        assert_eq!(profile.encoding_type(), Some(EncodingType::Unknown));
    }

    #[test]
    fn test_encoding_profile_zeroed() {
        let profile = EncodingProfile::zeroed();
        assert_eq!(profile.encoding_type(), Some(EncodingType::Unknown));
    }

    #[test]
    fn test_encoding_profile_size() {
        assert_eq!(std::mem::size_of::<EncodingProfile>(), 16);
    }

    #[test]
    fn test_clay_params_size() {
        assert_eq!(std::mem::size_of::<ClayParams>(), 8);
    }

    #[test]
    fn test_encoding_type_values() {
        assert_eq!(EncodingType::Unknown as u64, 0);
        assert_eq!(EncodingType::Basic as u64, 1);
        assert_eq!(EncodingType::Clay as u64, 2);
    }

    #[test]
    fn test_different_clay_params() {
        // Test with k=6, m=14 (n=20, d=19)
        let params1 = ClayParams::new(20, 6, 19);
        assert_eq!(params1.k(), 6);
        assert_eq!(params1.m(), 14);

        // Test with k=14, m=6 (n=20, d=19)
        let params2 = ClayParams::new(20, 14, 19);
        assert_eq!(params2.k(), 14);
        assert_eq!(params2.m(), 6);

        // They should be different
        assert_ne!(params1, params2);
    }
}