damon 0.1.1

A safe, typed Rust interface to Linux DAMON
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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
//! Receipt-verified persistent DAMON lifecycle operations.

use std::path::{Component, Path, PathBuf};
use std::sync::OnceLock;

use super::{
    ConfigurationSnapshot, Damon, DamonConfig, Error, ManagedHierarchy, ObservedConfiguration, Pid,
    Result, SessionLock, StagedOwnership, WritableConfigurationValue, with_rollback,
};

const RECEIPT_MAGIC: &[u8; 8] = b"DAMONR01";
const RECEIPT_VERSION: u32 = 1;

/// A running kdamond identity recorded in a persistent receipt.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct PersistentKdamondIdentity {
    index: usize,
    pid: Pid,
}

impl PersistentKdamondIdentity {
    /// Returns the kdamond hierarchy index.
    #[must_use]
    pub const fn index(self) -> usize {
        self.index
    }

    /// Returns the kernel-thread ID observed immediately after start.
    #[must_use]
    pub const fn pid(self) -> Pid {
        self.pid
    }
}

/// Verification data for a persistent DAMON hierarchy.
///
/// A receipt is evidence of an observed configuration and set of kernel-thread
/// IDs. It is not an ownership token. A controller that ignores the advisory
/// lock can replace a hierarchy between persistent operations.
#[must_use = "persistent receipts are required for later verified lifecycle operations"]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PersistentReceipt {
    admin_path: PathBuf,
    lock_path: PathBuf,
    boot_id: Box<str>,
    writable_values: Box<[WritableConfigurationValue]>,
    volatile_paths: Box<[PathBuf]>,
    kdamond_count: usize,
    identities: Box<[PersistentKdamondIdentity]>,
}

impl PersistentReceipt {
    fn capture(damon: &Damon, managed: &ManagedHierarchy) -> Result<Self> {
        let parts = managed.persistent_parts()?;
        let volatile_paths = parts
            .volatile_paths
            .iter()
            .map(|path| {
                path.strip_prefix(damon.admin.path())
                    .map(Path::to_path_buf)
                    .map_err(|_| Error::OwnershipLost {
                        reason: "a volatile configuration path escaped the DAMON admin root",
                    })
            })
            .collect::<Result<Vec<_>>>()?
            .into_boxed_slice();
        let identities = parts
            .identities
            .iter()
            .map(|&(index, pid)| PersistentKdamondIdentity { index, pid })
            .collect::<Vec<_>>()
            .into_boxed_slice();
        Ok(Self {
            admin_path: damon.admin.path().to_path_buf(),
            lock_path: damon.lock_path.clone(),
            boot_id: current_boot_id()?.into(),
            writable_values: parts.configuration.writable_values(),
            volatile_paths,
            kdamond_count: parts.kdamond_count,
            identities,
        })
    }

    /// Returns the DAMON admin path to which this receipt is bound.
    #[must_use]
    pub fn admin_path(&self) -> &Path {
        &self.admin_path
    }

    /// Returns the cooperative lock path to which this receipt is bound.
    #[must_use]
    pub fn lock_path(&self) -> &Path {
        &self.lock_path
    }

    /// Returns the Linux boot identifier to which this receipt is bound.
    #[must_use]
    pub const fn boot_id(&self) -> &str {
        &self.boot_id
    }

    /// Returns the running kdamond identities recorded by the receipt.
    #[must_use]
    pub const fn identities(&self) -> &[PersistentKdamondIdentity] {
        &self.identities
    }

    /// Returns the total number of configured kdamonds, including stopped ones.
    #[must_use]
    pub const fn kdamond_count(&self) -> usize {
        self.kdamond_count
    }

    /// Returns all recorded writable configuration values.
    #[must_use]
    pub const fn writable_values(&self) -> &[WritableConfigurationValue] {
        &self.writable_values
    }

    /// Serializes this receipt into a stable versioned binary representation.
    pub fn to_bytes(&self) -> Result<Vec<u8>> {
        let mut output = Vec::new();
        output.extend_from_slice(RECEIPT_MAGIC);
        output.extend_from_slice(&RECEIPT_VERSION.to_le_bytes());
        encode_path(&mut output, &self.admin_path)?;
        encode_path(&mut output, &self.lock_path)?;
        encode_bytes(&mut output, self.boot_id.as_bytes())?;
        encode_len(&mut output, self.writable_values.len())?;
        for value in &self.writable_values {
            encode_path(&mut output, value.path())?;
            encode_bytes(&mut output, value.value().as_bytes())?;
        }
        encode_len(&mut output, self.volatile_paths.len())?;
        for path in &self.volatile_paths {
            encode_path(&mut output, path)?;
        }
        encode_len(&mut output, self.kdamond_count)?;
        encode_len(&mut output, self.identities.len())?;
        for identity in &self.identities {
            output.extend_from_slice(
                &u64::try_from(identity.index)
                    .map_err(|_| Error::InvalidReceipt {
                        reason: "a kdamond index cannot be serialized",
                    })?
                    .to_le_bytes(),
            );
            output.extend_from_slice(&u32::from(identity.pid).to_le_bytes());
        }
        Ok(output)
    }

    /// Parses a receipt serialized by [`Self::to_bytes`].
    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
        let mut decoder = Decoder::new(bytes);
        if decoder.take(RECEIPT_MAGIC.len())? != RECEIPT_MAGIC {
            return Err(Error::InvalidReceipt {
                reason: "has an invalid format marker",
            });
        }
        if decoder.read_u32()? != RECEIPT_VERSION {
            return Err(Error::InvalidReceipt {
                reason: "uses an unsupported format version",
            });
        }
        let admin_path = decoder.read_path()?;
        let lock_path = decoder.read_path()?;
        let boot_id =
            Box::<str>::from(std::str::from_utf8(decoder.read_bytes()?).map_err(|_| {
                Error::InvalidReceipt {
                    reason: "contains a non-UTF-8 boot identifier",
                }
            })?);
        if !admin_path.is_absolute()
            || !lock_path.is_absolute()
            || path_contains_nul(&admin_path)
            || path_contains_nul(&lock_path)
        {
            return Err(Error::InvalidReceipt {
                reason: "admin and lock paths must be absolute and contain no NUL bytes",
            });
        }
        validate_boot_id(&boot_id)?;

        let value_count = decoder.read_count()?;
        let mut writable_values = Vec::with_capacity(value_count.min(4_096));
        for _ in 0..value_count {
            let path = decoder.read_path()?;
            validate_relative_path(&path)?;
            let value = std::str::from_utf8(decoder.read_bytes()?)
                .map_err(|_| Error::InvalidReceipt {
                    reason: "contains a non-UTF-8 configuration value",
                })?
                .into();
            writable_values.push(WritableConfigurationValue::new(path, value));
        }

        let volatile_count = decoder.read_count()?;
        let mut volatile_paths = Vec::with_capacity(volatile_count.min(64));
        for _ in 0..volatile_count {
            let path = decoder.read_path()?;
            validate_relative_path(&path)?;
            volatile_paths.push(path);
        }

        let kdamond_count = decoder.read_count()?;
        if kdamond_count == 0 {
            return Err(Error::InvalidReceipt {
                reason: "contains no configured kdamonds",
            });
        }
        validate_receipt_configuration(&writable_values, &volatile_paths, kdamond_count)?;
        let identity_count = decoder.read_count()?;
        if identity_count > kdamond_count {
            return Err(Error::InvalidReceipt {
                reason: "contains more running identities than configured kdamonds",
            });
        }
        let mut identities = Vec::with_capacity(identity_count.min(1_024));
        let mut previous_index = None;
        for _ in 0..identity_count {
            let index =
                usize::try_from(decoder.read_u64()?).map_err(|_| Error::InvalidReceipt {
                    reason: "contains an out-of-range kdamond index",
                })?;
            if index >= kdamond_count {
                return Err(Error::InvalidReceipt {
                    reason: "contains a running identity outside the hierarchy",
                });
            }
            if previous_index.is_some_and(|previous| previous >= index) {
                return Err(Error::InvalidReceipt {
                    reason: "running kdamond identities are not distinct and ordered",
                });
            }
            let pid = Pid::new(decoder.read_u32()?).map_err(|_| Error::InvalidReceipt {
                reason: "contains an invalid kdamond kernel-thread ID",
            })?;
            identities.push(PersistentKdamondIdentity { index, pid });
            previous_index = Some(index);
        }
        if !decoder.is_empty() {
            return Err(Error::InvalidReceipt {
                reason: "contains trailing data",
            });
        }
        Ok(Self {
            admin_path,
            lock_path,
            boot_id,
            writable_values: writable_values.into_boxed_slice(),
            volatile_paths: volatile_paths.into_boxed_slice(),
            kdamond_count,
            identities: identities.into_boxed_slice(),
        })
    }

    fn verify_binding(&self, damon: &Damon) -> Result<()> {
        if self.admin_path != damon.admin.path() {
            return Err(Error::ReceiptMismatch {
                reason: "DAMON admin path differs",
            });
        }
        if self.lock_path != damon.lock_path {
            return Err(Error::ReceiptMismatch {
                reason: "advisory lock path differs",
            });
        }
        if self.boot_id.as_ref() != current_boot_id()? {
            return Err(Error::ReceiptMismatch {
                reason: "Linux boot identifier differs",
            });
        }
        Ok(())
    }

    fn open_managed(&self, damon: &Damon) -> Result<ManagedHierarchy> {
        self.verify_binding(damon)?;
        let session_lock = SessionLock::acquire(&damon.lock_path)?;
        let configuration =
            ConfigurationSnapshot::from_writable_values(damon.admin.path(), &self.writable_values)?;
        let volatile_paths = self
            .volatile_paths
            .iter()
            .map(|path| damon.admin.path().join(path))
            .collect::<Vec<_>>();
        let staged = StagedOwnership::from_parts(configuration, volatile_paths, self.kdamond_count);
        let identities = self
            .identities
            .iter()
            .map(|identity| (identity.index, identity.pid))
            .collect::<Vec<_>>();
        ManagedHierarchy::attach_persistent(damon.admin.clone(), staged, &identities, session_lock)
    }
}

/// A persistent hierarchy handle that verifies a receipt for each operation.
///
/// This handle does not retain the advisory lock between calls. Each mutating
/// operation reacquires it and rejects configuration or PID replacement before
/// writing.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AttachedHierarchy {
    damon: Damon,
    receipt: PersistentReceipt,
}

impl AttachedHierarchy {
    /// Returns the receipt currently verified by this handle.
    pub const fn receipt(&self) -> &PersistentReceipt {
        &self.receipt
    }

    /// Consumes the handle and returns its current receipt.
    pub fn into_receipt(self) -> PersistentReceipt {
        self.receipt
    }

    /// Reads the verified known configuration.
    pub fn configuration(&self) -> Result<DamonConfig> {
        let mut managed = self.receipt.open_managed(&self.damon)?;
        let result = managed.configuration();
        managed.disarm_cleanup();
        result
    }

    /// Reads the verified known hierarchy and every writable configuration value.
    pub fn observed_configuration(&self) -> Result<ObservedConfiguration> {
        let mut managed = self.receipt.open_managed(&self.damon)?;
        let result = managed.observed_configuration();
        managed.disarm_cleanup();
        result
    }

    /// Transactionally updates every running kdamond and replaces the receipt.
    pub fn update(&mut self, config: &DamonConfig) -> Result<()> {
        let indices = self
            .receipt
            .identities
            .iter()
            .map(|identity| identity.index)
            .collect::<Vec<_>>();
        self.update_selected(config, &indices)
    }

    /// Transactionally updates selected running kdamonds and replaces the receipt.
    pub fn update_selected(
        &mut self,
        config: &DamonConfig,
        kdamond_indices: &[usize],
    ) -> Result<()> {
        let mut managed = self.receipt.open_managed(&self.damon)?;
        let operation = managed.update_configuration(config, kdamond_indices);
        let receipt = PersistentReceipt::capture(&self.damon, &managed);
        managed.disarm_cleanup();
        match (operation, receipt) {
            (Ok(()), Ok(receipt)) => {
                self.receipt = receipt;
                Ok(())
            }
            (Err(operation), Ok(receipt)) => {
                self.receipt = receipt;
                Err(operation)
            }
            (operation, Err(verification)) => Err(Error::PersistentStateUncertain {
                operation: operation.err().map(Box::new),
                verification: Box::new(verification),
            }),
        }
    }

    /// Stops every kdamond whose recorded configuration and PID still match.
    ///
    /// The staged hierarchy is retained because a persistent receipt has no
    /// preceding hierarchy to restore.
    pub fn stop(&mut self) -> Result<()> {
        let mut managed = self.receipt.open_managed(&self.damon)?;
        let operation = managed.stop_all();
        let receipt = PersistentReceipt::capture(&self.damon, &managed);
        managed.disarm_cleanup();
        match (operation, receipt) {
            (Ok(()), Ok(receipt)) => {
                self.receipt = receipt;
                Ok(())
            }
            (Err(operation), Ok(receipt)) => {
                self.receipt = receipt;
                Err(operation)
            }
            (operation, Err(verification)) => Err(Error::PersistentStateUncertain {
                operation: operation.err().map(Box::new),
                verification: Box::new(verification),
            }),
        }
    }
}

impl Damon {
    /// Stages and starts a hierarchy that remains running after this call.
    ///
    /// The returned receipt must be persisted by the caller. It supports later
    /// verified attach, update, and stop operations, but cannot prevent an
    /// external controller from replacing the hierarchy between operations.
    pub fn start_persistent(&self, config: &DamonConfig) -> Result<PersistentReceipt> {
        let mut managed = self.managed_hierarchy(config)?;
        managed.start_all()?;
        match PersistentReceipt::capture(self, &managed) {
            Ok(receipt) => {
                managed.disarm_cleanup();
                Ok(receipt)
            }
            Err(operation) => Err(with_rollback(operation, managed.close_inner())),
        }
    }

    /// Attaches a receipt-verified persistent handle to this DAMON instance.
    pub fn attach(&self, receipt: &PersistentReceipt) -> Result<AttachedHierarchy> {
        let mut managed = receipt.open_managed(self)?;
        managed.disarm_cleanup();
        Ok(AttachedHierarchy {
            damon: self.clone(),
            receipt: receipt.clone(),
        })
    }
}

fn validate_relative_path(path: &Path) -> Result<()> {
    if path.as_os_str().is_empty()
        || path.is_absolute()
        || path_contains_nul(path)
        || path
            .components()
            .any(|component| !matches!(component, Component::Normal(_)))
    {
        return Err(Error::InvalidReceipt {
            reason: "contains a non-relative configuration path",
        });
    }
    Ok(())
}

fn validate_receipt_configuration(
    writable_values: &[WritableConfigurationValue],
    volatile_paths: &[PathBuf],
    kdamond_count: usize,
) -> Result<()> {
    if writable_values
        .windows(2)
        .any(|values| values[0].path() >= values[1].path())
    {
        return Err(Error::InvalidReceipt {
            reason: "writable configuration paths are not distinct and ordered",
        });
    }
    if volatile_paths.windows(2).any(|paths| paths[0] >= paths[1]) {
        return Err(Error::InvalidReceipt {
            reason: "volatile configuration paths are not distinct and ordered",
        });
    }

    let count_path = Path::new("kdamonds/nr_kdamonds");
    let count_index = writable_values
        .binary_search_by(|value| value.path().cmp(count_path))
        .map_err(|_| Error::InvalidReceipt {
            reason: "does not contain the kdamond count",
        })?;
    let recorded_count = writable_values[count_index]
        .value()
        .trim()
        .parse::<usize>()
        .map_err(|_| Error::InvalidReceipt {
            reason: "contains an invalid writable kdamond count",
        })?;
    if recorded_count != kdamond_count {
        return Err(Error::InvalidReceipt {
            reason: "contains inconsistent kdamond counts",
        });
    }

    let expected_volatile = expected_volatile_paths(writable_values, kdamond_count)?;
    if volatile_paths != expected_volatile {
        return Err(Error::InvalidReceipt {
            reason: "contains inconsistent auto-tuned interval paths",
        });
    }
    Ok(())
}

fn expected_volatile_paths(
    writable_values: &[WritableConfigurationValue],
    kdamond_count: usize,
) -> Result<Vec<PathBuf>> {
    let mut paths = Vec::new();
    for value in writable_values {
        let Some(intervals_path) = tuned_intervals_path(value.path(), kdamond_count) else {
            continue;
        };
        let aggregation_intervals =
            value
                .value()
                .trim()
                .parse::<u64>()
                .map_err(|_| Error::InvalidReceipt {
                    reason: "contains an invalid interval-goal aggregation count",
                })?;
        if aggregation_intervals == 0 {
            continue;
        }
        for name in ["aggr_us", "sample_us"] {
            let path = intervals_path.join(name);
            if writable_values
                .binary_search_by(|value| value.path().cmp(&path))
                .is_err()
            {
                return Err(Error::InvalidReceipt {
                    reason: "omits an auto-tuned writable interval",
                });
            }
            paths.push(path);
        }
    }
    paths.sort_unstable();
    paths.dedup();
    Ok(paths)
}

fn tuned_intervals_path(path: &Path, kdamond_count: usize) -> Option<&Path> {
    let mut components = path.iter();
    if components.next()? != "kdamonds" {
        return None;
    }
    let kdamond_index = components.next()?.to_str()?.parse::<usize>().ok()?;
    if kdamond_index >= kdamond_count || components.next()? != "contexts" {
        return None;
    }
    components.next()?.to_str()?.parse::<usize>().ok()?;
    for expected in ["monitoring_attrs", "intervals", "intervals_goal", "aggrs"] {
        if components.next()? != expected {
            return None;
        }
    }
    if components.next().is_some() {
        return None;
    }
    path.parent()?.parent()
}

fn current_boot_id() -> Result<&'static str> {
    #[cfg(target_os = "linux")]
    {
        const BOOT_ID_PATH: &str = "/proc/sys/kernel/random/boot_id";
        static BOOT_ID: OnceLock<Box<str>> = OnceLock::new();

        if let Some(value) = BOOT_ID.get() {
            return Ok(value);
        }
        let value = std::fs::read_to_string(BOOT_ID_PATH).map_err(|source| Error::Io {
            operation: "read Linux boot identifier",
            path: PathBuf::from(BOOT_ID_PATH),
            source,
        })?;
        let value = value.trim();
        validate_boot_id(value)?;
        let value: Box<str> = value.into();
        Ok(BOOT_ID.get_or_init(|| value))
    }
    #[cfg(not(target_os = "linux"))]
    {
        Err(Error::UnsupportedPlatform)
    }
}

fn validate_boot_id(value: &str) -> Result<()> {
    let valid = value.len() == 36
        && value.bytes().enumerate().all(|(index, byte)| {
            if matches!(index, 8 | 13 | 18 | 23) {
                byte == b'-'
            } else {
                byte.is_ascii_hexdigit()
            }
        });
    if !valid {
        return Err(Error::InvalidReceipt {
            reason: "contains an invalid Linux boot identifier",
        });
    }
    Ok(())
}

fn path_contains_nul(path: &Path) -> bool {
    #[cfg(unix)]
    {
        use std::os::unix::ffi::OsStrExt;

        path.as_os_str().as_bytes().contains(&0)
    }
    #[cfg(not(unix))]
    {
        path.to_string_lossy().contains('\0')
    }
}

fn encode_len(output: &mut Vec<u8>, len: usize) -> Result<()> {
    let len = u64::try_from(len).map_err(|_| Error::InvalidReceipt {
        reason: "contains a value too large to serialize",
    })?;
    output.extend_from_slice(&len.to_le_bytes());
    Ok(())
}

fn encode_bytes(output: &mut Vec<u8>, bytes: &[u8]) -> Result<()> {
    encode_len(output, bytes.len())?;
    output.extend_from_slice(bytes);
    Ok(())
}

fn encode_path(output: &mut Vec<u8>, path: &Path) -> Result<()> {
    #[cfg(unix)]
    {
        use std::os::unix::ffi::OsStrExt;

        encode_bytes(output, path.as_os_str().as_bytes())
    }
    #[cfg(not(unix))]
    {
        let value = path.to_str().ok_or(Error::InvalidReceipt {
            reason: "contains a platform path that is not valid UTF-8",
        })?;
        encode_bytes(output, value.as_bytes())
    }
}

struct Decoder<'a> {
    bytes: &'a [u8],
    offset: usize,
}

impl<'a> Decoder<'a> {
    const fn new(bytes: &'a [u8]) -> Self {
        Self { bytes, offset: 0 }
    }

    fn take(&mut self, len: usize) -> Result<&'a [u8]> {
        let end = self.offset.checked_add(len).ok_or(Error::InvalidReceipt {
            reason: "contains an overflowing length",
        })?;
        let value = self
            .bytes
            .get(self.offset..end)
            .ok_or(Error::InvalidReceipt {
                reason: "is truncated",
            })?;
        self.offset = end;
        Ok(value)
    }

    fn read_u32(&mut self) -> Result<u32> {
        let bytes = self
            .take(size_of::<u32>())?
            .try_into()
            .map_err(|_| Error::InvalidReceipt {
                reason: "contains an invalid 32-bit field",
            })?;
        Ok(u32::from_le_bytes(bytes))
    }

    fn read_u64(&mut self) -> Result<u64> {
        let bytes = self
            .take(size_of::<u64>())?
            .try_into()
            .map_err(|_| Error::InvalidReceipt {
                reason: "contains an invalid 64-bit field",
            })?;
        Ok(u64::from_le_bytes(bytes))
    }

    fn read_count(&mut self) -> Result<usize> {
        let count = usize::try_from(self.read_u64()?).map_err(|_| Error::InvalidReceipt {
            reason: "contains an out-of-range element count",
        })?;
        if count > self.bytes.len().saturating_sub(self.offset) {
            return Err(Error::InvalidReceipt {
                reason: "contains an impossible element count",
            });
        }
        Ok(count)
    }

    fn read_bytes(&mut self) -> Result<&'a [u8]> {
        let len = self.read_count()?;
        self.take(len)
    }

    fn read_path(&mut self) -> Result<PathBuf> {
        let bytes = self.read_bytes()?;
        #[cfg(unix)]
        {
            use std::ffi::OsString;
            use std::os::unix::ffi::OsStringExt;

            Ok(PathBuf::from(OsString::from_vec(bytes.to_vec())))
        }
        #[cfg(not(unix))]
        {
            Ok(PathBuf::from(std::str::from_utf8(bytes).map_err(|_| {
                Error::InvalidReceipt {
                    reason: "contains a platform path that is not valid UTF-8",
                }
            })?))
        }
    }

    fn is_empty(&self) -> bool {
        self.offset == self.bytes.len()
    }
}