ferrosys 0.8.0

Pure-Rust filesystem formatter and reader: ext4, ext3, ext2, FAT32, FAT16, FAT12, exFAT, btrfs, and APFS — rootless, in userspace, byte-reproducible
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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
//! The inode (`struct ext4_inode`), at any of the sizes ext4 stores it in.
//!
//! An inode records one file's type and permission bits, ownership, size, link
//! count, timestamps, and the 60-byte `i_block` area that either roots an extent
//! tree or holds the classic block map.
//!
//! # The extended area, and why every field past 128 bytes is conditional
//!
//! The first [`GOOD_OLD_SIZE`] bytes are the classic inode, present on every ext2,
//! ext3, and ext4 filesystem. A filesystem whose `s_inode_size` is larger carries an
//! extended area after it, and `i_extra_isize` at offset `0x80` declares how much of
//! that area is *in use*. A field in the extended area therefore exists only when the
//! inode is both large enough to hold it and declares an extra area that reaches past
//! its end (the ext4 documentation's Index Nodes page, "Inode Size" and "Inode Timestamps"),
//! which is [`Inode::fits`].
//!
//! This is not a corner case. `mke2fs` leaves the reserved inodes at
//! `i_extra_isize = 0`, so on a filesystem another tool formatted those inodes carry
//! no creation time, no sub-second timestamps, and no `i_checksum_hi` — and a reader
//! that takes those fields unconditionally recovers bytes that mean something else.
//! Whole filesystems are like this: a 128-byte inode has no extended area at all.
//!
//! Sizes, block counts, ownership, and the ACL block are held as full logical
//! values and split into the low/high halves ext4 stores. The `i_block` area is
//! kept as opaque bytes: what fills it — an inline extent tree or a classic
//! indirect map — is the mapping layer's concern, not this struct's.

use super::xattr::XATTR_MAGIC;
use super::{ParseError, get_u16, get_u32, join64, put_u16, put_u32};
use crate::time::Timestamp;

/// `S_IFDIR | 0755`, the mode of the root directory.
pub const ROOT_INODE_MODE: u16 = 0o40755;

/// `EXT2_GOOD_OLD_INODE_SIZE`: the 128-byte classic inode that every ext2, ext3, and
/// ext4 filesystem carries, and the smallest `s_inode_size` any of them declares.
/// Everything past it is the extended area, and conditional — see [`Inode::fits`].
pub const GOOD_OLD_SIZE: usize = 128;

/// The first inode a file may use on a revision-0 filesystem, where the superblock carries
/// no `s_first_ino` field and the reserved inodes are the ten the ext4 documentation's
/// Special inodes table lists, inode 11 being the first one free (its Super Block page gives
/// `s_first_ino` as a revision-1 field).
pub const GOOD_OLD_FIRST_INODE: u32 = 11;

/// The `i_extra_isize` an inode of `inode_size` carries.
///
/// A 128-byte inode ends where the extended area would begin and so declares none.
/// Every larger inode declares the 32-byte area that holds the sub-second timestamps,
/// the creation time, and `i_checksum_hi` — the value `mke2fs` writes at every inode
/// size it supports, and the one `s_want_extra_isize` advertises.
#[must_use]
pub const fn extra_isize_for(inode_size: u16) -> u16 {
    if inode_size as usize > GOOD_OLD_SIZE {
        32
    } else {
        0
    }
}

/// Inode flags (`i_flags`).
///
/// The flags this crate sets are named, and so are the ones its reader follows; a bit it
/// does not name is carried through unchanged, because what an image holds is what it holds.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub struct InodeFlags(u32);

crate::flags::flag_set!(InodeFlags: u32);

impl InodeFlags {
    /// `EXT4_EXTENTS_FL` (`0x80000`): the `i_block` area roots an extent tree
    /// rather than a classic block map.
    pub const EXTENTS: Self = Self(0x0008_0000);
    /// `EXT4_HUGE_FILE_FL` (`0x40000`): `i_blocks` counts filesystem blocks rather
    /// than 512-byte sectors, for files past the sector-count limit.
    pub const HUGE_FILE: Self = Self(0x0004_0000);
    /// `EXT4_INDEX_FL` (`0x1000`): the directory is hash-indexed (htree).
    pub const INDEX: Self = Self(0x0000_1000);
    /// `EXT4_ENCRYPT_FL` (`0x800`): the inode is encrypted. A file's data blocks, a
    /// directory's entry names, and a symbolic link's target hold ciphertext; the inode's
    /// other fields, its extended attributes, and the framing of its directory entries do
    /// not.
    pub const ENCRYPT: Self = Self(0x0000_0800);
    /// `EXT4_EA_INODE_FL` (`0x200000`): the inode holds one extended attribute's value in its
    /// data, for an attribute entry whose value is too large to keep beside it.
    pub const EA_INODE: Self = Self(0x0020_0000);
    /// `EXT4_INLINE_DATA_FL` (`0x10000000`): the inode keeps its content in its 60-byte
    /// block area and its `system.data` attribute rather than in blocks.
    pub const INLINE_DATA: Self = Self(0x1000_0000);
    /// `EXT4_CASEFOLD_FL` (`0x40000000`): the directory's names are compared, and its index
    /// hashed, with their case folded.
    pub const CASEFOLD: Self = Self(0x4000_0000);
}

/// The earliest instant an inode's time fields represent: the signed 32-bit seconds field
/// at its most negative with a zero epoch, i.e. `-2^31` seconds (1901-12-13).
pub const TIME_SECS_MIN: i64 = i32::MIN as i64;

/// The latest instant an inode's time fields represent: the signed 32-bit seconds field at
/// its most positive with the epoch at 3, i.e. `(2^31 - 1) + 3 * 2^32` seconds
/// (2446-05-10).
pub const TIME_SECS_MAX: i64 = i32::MAX as i64 + (3 << 32);

/// Whether an instant reaches an inode of `inode_size` bytes without loss.
///
/// An inode larger than 128 bytes holds each time's extra word, so an instant reaches it when
/// its seconds lie within [`TIME_SECS_MIN`]`..=`[`TIME_SECS_MAX`] and its fraction divides a
/// second. A 128-byte inode ends before the extra words: it holds the signed 32-bit seconds
/// field alone, from 1901-12-13 to 2038-01-19, and no fraction of a second.
///
/// An instant that does not would have its epoch bits or its nanoseconds masked to their
/// field widths by [`encode_time`], or dropped with the words a 128-byte inode ends before,
/// so callers check here and reject with a typed error instead.
#[must_use]
pub const fn time_is_representable(t: Timestamp, inode_size: u16) -> bool {
    if inode_size as usize > GOOD_OLD_SIZE {
        t.secs >= TIME_SECS_MIN && t.secs <= TIME_SECS_MAX && t.has_proper_fraction()
    } else {
        t.secs >= TIME_SECS_MIN && t.secs <= i32::MAX as i64 && t.nanos == 0
    }
}

/// Encode an instant to the `(field, extra)` pair an inode stores.
///
/// ext4 splits a time across a 32-bit seconds field and a 32-bit "extra" field. The seconds
/// field is *signed*; the extra field's low two bits are an unsigned epoch adding a multiple
/// of `2^32` seconds on top of it, and its upper 30 bits hold nanoseconds. So the stored
/// seconds are `(i32)field + (epoch << 32)`.
///
/// The epoch is the number of `2^32`-second steps between the signed field and the true
/// seconds; for a [representable](time_is_representable) instant it is 0 to 3 and encodes
/// exactly. Outside that range the epoch and the nanoseconds are masked to their on-disk
/// widths, so callers validate first.
#[must_use]
pub const fn encode_time(t: Timestamp) -> (u32, u32) {
    let field = t.secs as u32;
    // The signed 32-bit field sign-extended back to i64; the epoch carries the
    // remaining high seconds as a count of 2^32-second steps.
    let low = field as i32 as i64;
    let epoch = ((t.secs - low) >> 32) as u32;
    let extra = (epoch & 0x3) | (t.nanos << 2);
    (field, extra)
}

/// Decode an instant from the stored `(field, extra)` pair: the signed seconds field plus
/// the epoch offset, and the nanoseconds from the extra word's upper bits.
///
/// The encoding is the ext4 documentation's (Index Nodes, "Inode Timestamps"). This reports
/// what the inode holds rather than what a valid fraction would be: the extra word's upper thirty bits
/// reach 1 073 741 823, past the 1 000 000 000 that makes a second, so a decoded
/// [`nanos`](Timestamp::nanos) is bounded by the field and not by the second it divides. A
/// caller that goes on to render or re-encode a decoded instant checks it with
/// [`time_is_representable`] first.
#[must_use]
pub const fn decode_time(field: u32, extra: u32) -> Timestamp {
    let secs = (field as i32 as i64) + (((extra & 0x3) as i64) << 32);
    Timestamp {
        secs,
        nanos: extra >> 2,
    }
}

/// Encode a device number into the inode block words `(i_block[0], i_block[1])`.
///
/// Two forms, as a Linux kernel and the pinned `debugfs` write them (observed; the format's
/// documentation says only that a device's number lives in the block area):
///
/// - **Compact**, where the major and the minor both fit in a byte: the word `i_block[0]`
///   holds the minor in bits 0 to 7 and the major in bits 8 to 15, and `i_block[1]` is
///   zero.
/// - **Wide**, for everything else: `i_block[0]` is zero, and `i_block[1]` holds the
///   minor's low byte in bits 0 to 7, the major's twelve bits in 8 to 19, and the minor's
///   remaining twelve bits in 20 to 31.
///
/// So a major has twelve bits and a minor twenty, which is the range the model admits.
#[must_use]
pub(crate) fn encode_device(major: u32, minor: u32) -> (u32, u32) {
    debug_assert!(
        major < 1 << 12 && minor < 1 << 20,
        "{major}:{minor} is out of range"
    );
    if major < 1 << 8 && minor < 1 << 8 {
        return ((major << 8) | minor, 0);
    }
    let wide = (minor & 0xff) | (major << 8) | ((minor >> 8) << 20);
    (0, wide)
}

/// Decode a device number `(major, minor)` from the two inode block words: the compact form
/// where `i_block[0]` is non-zero, and the wide form in `i_block[1]` otherwise, as
/// [`encode_device`] lays them out.
#[must_use]
pub(crate) fn decode_device(block0: u32, block1: u32) -> (u32, u32) {
    if block0 != 0 {
        return ((block0 >> 8) & 0xff, block0 & 0xff);
    }
    let major = (block1 >> 8) & 0xfff;
    let minor = (block1 & 0xff) | ((block1 >> 20) << 8);
    (major, minor)
}

/// An inode: one file's metadata and the 60-byte area that maps its blocks.
///
/// # Constructing one
///
/// Start from [`Inode::empty`], which sizes the extra area, and assign the fields that
/// differ. A `#[non_exhaustive]` structure cannot be written as a literal from outside
/// this crate, and that is about the Rust type, not the format: the byte layout is
/// [`read_from`](Self::read_from), [`write_to`](Self::write_to), and the inode size the
/// superblock declares, and none of them changes. What the attribute buys is that this crate can widen its
/// coverage of the on-disk structure — the fields it does not model — without that
/// being a breaking change for everyone reading an image.
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct Inode {
    /// Type and permission bits (`i_mode`): the `S_IF*` type in the high nibble and
    /// the permission bits below.
    pub mode: u16,
    /// Owning user id (`i_uid` + `l_i_uid_high`).
    pub uid: u32,
    /// Owning group id (`i_gid` + `l_i_gid_high`).
    pub gid: u32,
    /// File size in bytes (`i_size_lo` + `i_size_high`). For a directory this is
    /// the number of bytes its directory blocks occupy.
    pub size: u64,
    /// Link count (`i_links_count`).
    pub links_count: u16,
    /// Blocks charged to the file (`i_blocks_lo` + `l_i_blocks_high`), in 512-byte
    /// sectors unless [`InodeFlags::HUGE_FILE`] is set.
    ///
    /// Parsing joins both halves unconditionally; whether the upper one exists is a
    /// question about the `huge_file` feature, which the parse does not see. Without it the
    /// value is `i_blocks_lo` alone, and the reader that holds the feature words masks it.
    pub blocks: u64,
    /// Inode flags (`i_flags`).
    pub flags: InodeFlags,
    /// Access time (`i_atime` + `i_atime_extra`).
    pub atime: Timestamp,
    /// Change (status) time (`i_ctime` + `i_ctime_extra`).
    pub ctime: Timestamp,
    /// Modification time (`i_mtime` + `i_mtime_extra`).
    pub mtime: Timestamp,
    /// Creation time (`i_crtime` + `i_crtime_extra`), available in the 256-byte
    /// inode's extra area.
    pub crtime: Timestamp,
    /// Deletion time (`i_dtime`); zero for a live inode.
    pub dtime: u32,
    /// Generation number (`i_generation`); zero in the images this crate writes.
    pub generation: u32,
    /// Block holding this inode's out-of-line extended attributes (`i_file_acl` +
    /// `l_i_file_acl_high`); zero when there are none.
    ///
    /// Joined unconditionally, like [`blocks`](Self::blocks): the upper half exists only
    /// under `64bit`, and the reader masks it where that is clear.
    pub file_acl: u64,
    /// Size of the used extra-inode area (`i_extra_isize`); 32 in the 256-byte
    /// inode.
    pub extra_isize: u16,
    /// The 60-byte block-mapping area (`i_block`): an inline extent tree when
    /// [`InodeFlags::EXTENTS`] is set, otherwise the classic direct/indirect map.
    pub block: [u8; Self::BLOCK_BYTES],
    /// crc32c of the inode (`l_i_checksum_lo` + `i_checksum_hi`), written through
    /// the checksum seam; zero while `metadata_csum` is off.
    pub checksum: u32,
    /// The inline extended-attribute region that follows the extra fields, from
    /// byte `128 + extra_isize` to the end of the inode. Empty when the inode
    /// carries no inline attributes; otherwise the full region including its magic
    /// header, as produced by the xattr encoder.
    pub inline_xattr: Vec<u8>,
}

impl Inode {
    /// Size of the `i_block` mapping area in bytes.
    pub const BLOCK_BYTES: usize = 60;
    /// Byte offset of the `i_block` area within the inode.
    pub const BLOCK_OFFSET: usize = 0x28;

    /// Byte offset of `i_extra_isize` (`__le16`), the first field past the classic inode
    /// and the declaration of how much of the extra area is in use. The field itself is
    /// present only when the inode is large enough to hold its two bytes, so an access to
    /// it is gated on `inode_size >= EXTRA_ISIZE_OFFSET + 2` rather than on
    /// [`fits`](Self::fits), whose extra-area bound would be circular for this field.
    pub const EXTRA_ISIZE_OFFSET: usize = 0x80;

    /// Byte offset of `l_i_checksum_lo`, the low half of the inode checksum. It sits
    /// inside the classic inode and so exists on every filesystem.
    pub const CHECKSUM_LO_OFFSET: usize = 0x7c;
    /// Byte offset of `i_checksum_hi`, the high half of the inode checksum. It sits in
    /// the extended area and exists only when [`fits`](Self::fits) says so.
    pub const CHECKSUM_HI_OFFSET: usize = 0x82;

    /// Whether the extended field at `off` spanning `width` bytes exists in an inode of
    /// `inode_size` whose extra area declares `extra_isize`.
    ///
    /// The field must lie within the inode *and* within the extra area the inode
    /// declares in use. Both bounds matter: the first is what makes a 128-byte inode
    /// carry none of these fields, the second is what makes `mke2fs`'s reserved inodes
    /// (`i_extra_isize = 0`) carry none of them either despite living in a 256-byte
    /// table.
    #[must_use]
    pub const fn fits(inode_size: u16, extra_isize: u16, off: usize, width: usize) -> bool {
        let end = off + width;
        end <= inode_size as usize && end <= GOOD_OLD_SIZE + extra_isize as usize
    }

    /// Whether this inode carries `i_checksum_hi`, the high half of its checksum.
    ///
    /// When it does not, the stored checksum is the low sixteen bits alone (the ext4
    /// documentation's Checksums page), and a verifier narrows its computed value to
    /// match. Comparing a full 32-bit value against a stored half rejects a healthy inode.
    #[must_use]
    pub const fn has_checksum_hi(inode_size: u16, extra_isize: u16) -> bool {
        Self::fits(inode_size, extra_isize, Self::CHECKSUM_HI_OFFSET, 2)
    }

    /// Where `i_crtime`, the creation time's seconds, sits in the extended area.
    pub const CRTIME_OFFSET: usize = 0x90;

    /// Whether this inode carries `i_crtime`, a creation time: an inode of 128 bytes, or
    /// one whose extra area does not reach the field, records none.
    #[must_use]
    pub const fn has_crtime(inode_size: u16, extra_isize: u16) -> bool {
        Self::fits(inode_size, extra_isize, Self::CRTIME_OFFSET, 4)
    }

    /// An empty inode with the extra area an inode of `inode_size` carries: all fields
    /// zero, the block area cleared. Reserved inodes that hold nothing (bad-blocks, the
    /// unused reserved range) serialize from this.
    ///
    /// The 128-byte inode ends where the extended area would begin, so it declares no
    /// extra area; every larger inode declares the 32-byte one that carries the
    /// creation time and the sub-second timestamps.
    #[must_use]
    pub fn empty(inode_size: u16) -> Self {
        Self {
            mode: 0,
            uid: 0,
            gid: 0,
            size: 0,
            links_count: 0,
            blocks: 0,
            flags: InodeFlags::NONE,
            atime: Timestamp::default(),
            ctime: Timestamp::default(),
            mtime: Timestamp::default(),
            crtime: Timestamp::default(),
            dtime: 0,
            generation: 0,
            file_acl: 0,
            extra_isize: extra_isize_for(inode_size),
            block: [0u8; Self::BLOCK_BYTES],
            checksum: 0,
            inline_xattr: Vec::new(),
        }
    }

    /// The bytes of the inline extended-attribute region an inode of `inode_size` with
    /// this inode's extra area has room for: what is left after the classic inode and
    /// the extra area. Zero when the inode ends at or before the region would start,
    /// which is every 128-byte inode.
    #[must_use]
    pub fn inline_xattr_capacity(&self, inode_size: u16) -> usize {
        (inode_size as usize).saturating_sub(GOOD_OLD_SIZE + self.extra_isize as usize)
    }

    /// [`Self::inline_xattr_capacity`] for an inode this crate creates at
    /// `inode_size`, whose extra area is always [`extra_isize_for`] that size. Lets a
    /// caller reason about inline room before any inode exists.
    #[must_use]
    pub fn inline_xattr_capacity_for(inode_size: u16) -> usize {
        (inode_size as usize).saturating_sub(GOOD_OLD_SIZE + extra_isize_for(inode_size) as usize)
    }

    /// Serialize into the first `inode_size` bytes of `buf`, which are cleared first.
    ///
    /// Every field in the extended area is written only when this inode
    /// [carries](Self::fits) it, so a 128-byte inode receives the classic fields alone
    /// and an inode declaring no extra area receives no creation time, no sub-second
    /// timestamps, and no `i_checksum_hi`. Those are the same conditions the kernel
    /// writes under, so the bytes match what it would have produced.
    ///
    /// # Errors
    ///
    /// [`ParseError::InvalidField`] if `inode_size` is below [`GOOD_OLD_SIZE`];
    /// [`ParseError::TooShort`] if `buf` cannot hold `inode_size` bytes.
    pub fn write_to(&self, buf: &mut [u8], inode_size: u16) -> Result<(), ParseError> {
        let size = check_inode_size(inode_size, buf.len())?;
        let b = &mut buf[..size];
        b.fill(0);

        let (atime, atime_x) = encode_time(self.atime);
        let (ctime, ctime_x) = encode_time(self.ctime);
        let (mtime, mtime_x) = encode_time(self.mtime);
        let (crtime, crtime_x) = encode_time(self.crtime);
        let fits = |off, width| Self::fits(inode_size, self.extra_isize, off, width);

        // The classic inode: present at every inode size.
        put_u16(b, 0x00, self.mode);
        put_u16(b, 0x02, self.uid as u16);
        put_u32(b, 0x04, self.size as u32);
        put_u32(b, 0x08, atime);
        put_u32(b, 0x0c, ctime);
        put_u32(b, 0x10, mtime);
        put_u32(b, 0x14, self.dtime);
        put_u16(b, 0x18, self.gid as u16);
        put_u16(b, 0x1a, self.links_count);
        put_u32(b, 0x1c, self.blocks as u32);
        put_u32(b, 0x20, self.flags.bits());
        // 0x24 i_osd1 (l_i_version) — left zero.
        b[Self::BLOCK_OFFSET..Self::BLOCK_OFFSET + Self::BLOCK_BYTES].copy_from_slice(&self.block);
        put_u32(b, 0x64, self.generation);
        put_u32(b, 0x68, self.file_acl as u32);
        put_u32(b, 0x6c, (self.size >> 32) as u32);
        // 0x70 i_obso_faddr — left zero.
        put_u16(b, 0x74, (self.blocks >> 32) as u16);
        put_u16(b, 0x76, (self.file_acl >> 32) as u16);
        put_u16(b, 0x78, (self.uid >> 16) as u16);
        put_u16(b, 0x7a, (self.gid >> 16) as u16);
        put_u16(b, Self::CHECKSUM_LO_OFFSET, self.checksum as u16);
        // 0x7e l_i_reserved — left zero.

        // The extended area. `i_extra_isize` itself is the declaration of how much of
        // it is in use, so it exists whenever the inode is large enough to hold the
        // field's own two bytes; every field after it is conditional on that declaration.
        if size >= Self::EXTRA_ISIZE_OFFSET + 2 {
            put_u16(b, Self::EXTRA_ISIZE_OFFSET, self.extra_isize);
        }
        if fits(Self::CHECKSUM_HI_OFFSET, 2) {
            put_u16(b, Self::CHECKSUM_HI_OFFSET, (self.checksum >> 16) as u16);
        }
        if fits(0x84, 4) {
            put_u32(b, 0x84, ctime_x);
        }
        if fits(0x88, 4) {
            put_u32(b, 0x88, mtime_x);
        }
        if fits(0x8c, 4) {
            put_u32(b, 0x8c, atime_x);
        }
        if fits(Self::CRTIME_OFFSET, 4) {
            put_u32(b, Self::CRTIME_OFFSET, crtime);
        }
        if fits(0x94, 4) {
            put_u32(b, 0x94, crtime_x);
        }
        // 0x98 i_version_hi, 0x9c i_projid — left zero.

        // The inline xattr region begins right after the extra area, at
        // 128 + extra_isize, and runs to the end of the inode. It is zero unless the
        // inode carries inline attributes. Clamp the length, so a hand-built inode with
        // an oversized region cannot run past the inode.
        let xoff = GOOD_OLD_SIZE + self.extra_isize as usize;
        if !self.inline_xattr.is_empty() && xoff < size {
            debug_assert!(
                xoff + self.inline_xattr.len() <= size,
                "inline xattr region overflows the inode"
            );
            let n = self.inline_xattr.len().min(size - xoff);
            b[xoff..xoff + n].copy_from_slice(&self.inline_xattr[..n]);
        }
        Ok(())
    }

    /// Serialize to a fresh `inode_size`-byte buffer.
    ///
    /// # Errors
    ///
    /// As [`write_to`](Self::write_to).
    pub fn to_bytes(&self, inode_size: u16) -> Result<Vec<u8>, ParseError> {
        let mut b = vec![0u8; inode_size as usize];
        self.write_to(&mut b, inode_size)?;
        Ok(b)
    }

    /// Parse an `inode_size`-byte inode from the front of `buf`.
    ///
    /// Fields in the extended area are recovered only when this inode
    /// [carries](Self::fits) them, and default to zero otherwise: a 128-byte inode
    /// yields second-granularity timestamps and no creation time, because that is all
    /// its bytes hold. `extra_isize` is taken as declared and is not trusted to be in
    /// range — a value that overruns the inode simply leaves every conditional field
    /// absent rather than reading past it.
    ///
    /// # Errors
    ///
    /// [`ParseError::InvalidField`] if `inode_size` is below [`GOOD_OLD_SIZE`];
    /// [`ParseError::TooShort`] if `buf` is shorter than `inode_size`.
    pub fn read_from(buf: &[u8], inode_size: u16) -> Result<Self, ParseError> {
        let size = check_inode_size(inode_size, buf.len())?;
        let mut block = [0u8; Self::BLOCK_BYTES];
        block.copy_from_slice(&buf[Self::BLOCK_OFFSET..Self::BLOCK_OFFSET + Self::BLOCK_BYTES]);

        // `i_extra_isize` exists whenever the inode is large enough to hold the field's
        // own two bytes; a 128-byte inode, or one too small to fit even this field,
        // declares no extra area, so nothing after this point exists. Gating on the
        // field's own span keeps the read within `buf` for any `inode_size` a caller
        // passes, not only the power-of-two sizes a real filesystem uses.
        let extra_isize = if size >= Self::EXTRA_ISIZE_OFFSET + 2 {
            get_u16(buf, Self::EXTRA_ISIZE_OFFSET)
        } else {
            0
        };
        let fits = |off, width| Self::fits(inode_size, extra_isize, off, width);
        let extra = |off| if fits(off, 4) { get_u32(buf, off) } else { 0 };

        // The inline xattr region runs from 128 + extra_isize to the inode's end.
        // Retain it only when it carries the xattr magic; an all-zero tail is no
        // attributes, and keeping it empty makes the round trip exact. A declared
        // `extra_isize` past the inode's end yields no region at all rather than a
        // panic.
        let xoff = GOOD_OLD_SIZE + extra_isize as usize;
        let inline_xattr = match buf.get(xoff..size) {
            Some(region) if region.len() >= 4 && get_u32(region, 0) == XATTR_MAGIC => {
                region.to_vec()
            }
            _ => Vec::new(),
        };

        // The stored checksum is the low half alone unless the inode carries the high
        // one. Reconstructing a 32-bit value from an absent high half would fabricate a
        // zero and reject a healthy inode.
        let checksum = {
            let lo = u32::from(get_u16(buf, Self::CHECKSUM_LO_OFFSET));
            if Self::has_checksum_hi(inode_size, extra_isize) {
                lo | (u32::from(get_u16(buf, Self::CHECKSUM_HI_OFFSET)) << 16)
            } else {
                lo
            }
        };

        // The word at 0x6c holds the high half of a *regular file's* size. Under every
        // other file type it is `i_dir_acl` — a directory ACL pointer in ext2, reserved
        // since — so an inode type that is not a regular file takes its size from the
        // low word alone. Joining unconditionally would read a foreign directory's
        // leftover pointer as four gigabytes of size per unit, and a walk would then try
        // to map it.
        let mode = get_u16(buf, 0x00);
        let size_hi = if mode & 0o170000 == 0o100000 {
            get_u32(buf, 0x6c)
        } else {
            0
        };

        Ok(Self {
            mode,
            uid: u32::from(get_u16(buf, 0x02)) | (u32::from(get_u16(buf, 0x78)) << 16),
            gid: u32::from(get_u16(buf, 0x18)) | (u32::from(get_u16(buf, 0x7a)) << 16),
            size: join64(get_u32(buf, 0x04), size_hi),
            links_count: get_u16(buf, 0x1a),
            // Joined whether or not `huge_file` says the upper bytes are a high half:
            // that is a question about the feature words, which this layer does not have.
            // Without the feature they are ext2's `l_i_frag` and `l_i_fsize`, and the
            // reader masks them off once it knows.
            blocks: join64(get_u32(buf, 0x1c), u32::from(get_u16(buf, 0x74))),
            flags: InodeFlags::from_bits(get_u32(buf, 0x20)),
            atime: decode_time(get_u32(buf, 0x08), extra(0x8c)),
            ctime: decode_time(get_u32(buf, 0x0c), extra(0x84)),
            mtime: decode_time(get_u32(buf, 0x10), extra(0x88)),
            crtime: decode_time(extra(Self::CRTIME_OFFSET), extra(0x94)),
            dtime: get_u32(buf, 0x14),
            generation: get_u32(buf, 0x64),
            // The same, gated on `64bit` rather than on `huge_file`: without it 0x76 is
            // `i_pad1`.
            file_acl: join64(get_u32(buf, 0x68), u32::from(get_u16(buf, 0x76))),
            extra_isize,
            block,
            checksum,
            inline_xattr,
        })
    }
}

/// Validate an inode size and the buffer offered for it, returning the size as a
/// `usize`. Every accessor below indexes within the classic inode, so a buffer holding
/// at least `GOOD_OLD_SIZE` bytes bounds them all.
fn check_inode_size(inode_size: u16, available: usize) -> Result<usize, ParseError> {
    let size = inode_size as usize;
    if size < GOOD_OLD_SIZE {
        return Err(ParseError::InvalidField {
            structure: "Inode",
            field: "s_inode_size",
            value: u64::from(inode_size),
        });
    }
    if available < size {
        return Err(ParseError::TooShort {
            structure: "Inode",
            need: size,
            got: available,
        });
    }
    Ok(size)
}

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

    /// The inode size this crate writes by default, and the one the fixed vectors
    /// below are expressed at.
    const S: u16 = 256;

    fn root_like() -> Inode {
        let t = Timestamp::from_secs(1_700_000_000);
        let mut ino = Inode::empty(S);
        ino.mode = ROOT_INODE_MODE;
        ino.size = 4096;
        ino.links_count = 3;
        ino.blocks = 8;
        ino.flags = InodeFlags::EXTENTS;
        ino.atime = t;
        ino.ctime = t;
        ino.mtime = t;
        ino.crtime = t;
        ino
    }

    fn bytes(ino: &Inode, size: u16) -> Vec<u8> {
        ino.to_bytes(size).expect("serializes")
    }

    #[test]
    fn round_trips() {
        let ino = root_like();
        assert_eq!(Inode::read_from(&bytes(&ino, S), S).unwrap(), ino);
    }

    #[test]
    fn matches_ground_truth_root_fields() {
        // Root inode of the 64 MiB baseline: mode 040755, extents flag, size 4096,
        // links 3, blockcount 8, extra isize 32, ctime 0x6553f100 extra 0.
        let ino = root_like();
        let b = bytes(&ino, S);
        assert_eq!(get_u16(&b, 0x00), 0o40755);
        assert_eq!(get_u32(&b, 0x20), InodeFlags::EXTENTS.bits());
        assert_eq!(get_u32(&b, 0x04), 4096);
        assert_eq!(get_u16(&b, 0x1a), 3);
        assert_eq!(get_u32(&b, 0x1c), 8);
        assert_eq!(get_u16(&b, 0x80), 32);
        assert_eq!(get_u32(&b, 0x0c), 0x6553_f100);
        assert_eq!(get_u32(&b, 0x84), 0, "ctime_extra: nanos 0, epoch bits 0");
    }

    #[test]
    fn large_size_and_blocks_split_across_halves() {
        // The resize inode has size 4299210752 (needs the high half) and lives on a
        // classic block map (no extents flag).
        let mut ino = Inode::empty(S);
        ino.mode = 0o100600;
        ino.size = 4_299_210_752;
        ino.blocks = 80;
        ino.links_count = 1;
        let b = bytes(&ino, S);
        assert_eq!(get_u32(&b, 0x04), 0x0040_c000, "size low");
        assert_eq!(get_u32(&b, 0x6c), 1, "size high");
        assert_eq!(Inode::read_from(&b, S).unwrap(), ino);
    }

    #[test]
    fn only_a_regular_file_takes_its_size_from_both_words() {
        // The word at 0x6c is the size's high half for a regular file and `i_dir_acl`
        // for every other type. A foreign directory carrying a leftover pointer there
        // must not read as four gigabytes of size per unit — a size a walk would then
        // try to map, one entry per logical block.
        let mut b = vec![0u8; S as usize];
        put_u16(&mut b, 0x00, ROOT_INODE_MODE);
        put_u32(&mut b, 0x04, 4096);
        put_u32(&mut b, 0x6c, 1);
        assert_eq!(
            Inode::read_from(&b, S).unwrap().size,
            4096,
            "a directory's size is the low word alone"
        );

        put_u16(&mut b, 0x00, 0o120777);
        assert_eq!(
            Inode::read_from(&b, S).unwrap().size,
            4096,
            "and so is a symlink's"
        );

        // The same bytes under a regular file's mode do join: that is the one type
        // whose size spans both words.
        put_u16(&mut b, 0x00, 0o100644);
        assert_eq!(Inode::read_from(&b, S).unwrap().size, 4096 + (1 << 32));
    }

    #[test]
    fn high_uid_gid_and_blocks_round_trip() {
        let mut ino = Inode::empty(S);
        ino.uid = 0x0012_3456;
        ino.gid = 0x0065_4321;
        ino.blocks = 0x1_0000_0000;
        ino.file_acl = 0x1_0000_2000;
        assert_eq!(Inode::read_from(&bytes(&ino, S), S).unwrap(), ino);
    }

    #[test]
    fn round_trips_at_every_inode_size() {
        // The extra area exists at 256 and above; the 128-byte inode ends before it, so
        // it carries no creation time and no sub-second fraction, and a round trip
        // through its bytes is exact only for what those bytes can hold.
        for size in [128u16, 256, 512, 1024] {
            let mut ino = Inode::empty(size);
            ino.mode = ROOT_INODE_MODE;
            ino.size = 4096;
            ino.links_count = 3;
            ino.mtime = Timestamp::from_secs(1_700_000_000);
            let b = bytes(&ino, size);
            assert_eq!(
                b.len(),
                size as usize,
                "serializes exactly s_inode_size bytes"
            );
            assert_eq!(
                Inode::read_from(&b, size).unwrap(),
                ino,
                "round trip at inode_size={size}"
            );
        }
    }

    #[test]
    fn the_classic_inode_carries_no_extended_field() {
        // A 128-byte inode has no extra area: no i_extra_isize, no sub-second
        // timestamps, no creation time, no i_checksum_hi. Asking it for one is not an
        // error — the field simply is not there.
        assert_eq!(extra_isize_for(128), 0);
        assert!(!Inode::has_checksum_hi(128, 0));
        assert!(!Inode::fits(128, 0, 0x84, 4), "no ctime_extra");
        assert!(!Inode::fits(128, 0, 0x90, 4), "no crtime");

        let mut ino = Inode::empty(128);
        ino.mtime = Timestamp {
            secs: 1_700_000_000,
            nanos: 123_456_789,
        };
        ino.crtime = Timestamp::from_secs(1_700_000_000);
        let back = Inode::read_from(&bytes(&ino, 128), 128).unwrap();
        assert_eq!(back.mtime.secs, 1_700_000_000, "seconds survive");
        assert_eq!(back.mtime.nanos, 0, "the fraction has nowhere to live");
        assert_eq!(back.crtime, Timestamp::default(), "no creation time exists");
    }

    #[test]
    fn the_checksum_high_half_exists_only_when_the_extra_area_reaches_it() {
        // The field at 0x82 is two bytes, so it exists where 0x82 + 2 <= 128 +
        // i_extra_isize, i.e. i_extra_isize >= 4. mke2fs leaves the reserved inodes at
        // zero, so on a foreign filesystem they store the low half alone.
        assert!(!Inode::has_checksum_hi(256, 0), "mke2fs's reserved inodes");
        assert!(!Inode::has_checksum_hi(256, 3));
        assert!(Inode::has_checksum_hi(256, 4), "the exact threshold");
        assert!(Inode::has_checksum_hi(256, 32), "the usual extra area");
        assert!(!Inode::has_checksum_hi(128, 32), "no extra area at all");

        // An inode declaring no extra area stores the low half, and parsing must not
        // fabricate a zero high half from the bytes that follow it.
        let mut ino = Inode::empty(256);
        ino.extra_isize = 0;
        ino.checksum = 0xdead_beef;
        let b = bytes(&ino, 256);
        assert_eq!(get_u16(&b, 0x7c), 0xbeef, "the low half is written");
        assert_eq!(get_u16(&b, 0x82), 0, "the high half is not");
        assert_eq!(
            Inode::read_from(&b, 256).unwrap().checksum,
            0x0000_beef,
            "and reads back as the low half alone"
        );
    }

    #[test]
    fn a_declared_extra_area_past_the_inode_reads_no_fields_and_does_not_panic() {
        // A hostile i_extra_isize must leave the conditional fields absent rather than
        // index past the inode.
        let mut b = vec![0u8; 256];
        put_u16(&mut b, 0x80, 0xffff);
        let ino = Inode::read_from(&b, 256).expect("parses");
        assert_eq!(ino.extra_isize, 0xffff);
        assert!(ino.inline_xattr.is_empty());
        assert_eq!(ino.crtime, Timestamp::default());
    }

    #[test]
    fn an_inode_size_below_the_classic_one_is_refused() {
        let b = vec![0u8; 256];
        assert!(matches!(
            Inode::read_from(&b, 64),
            Err(ParseError::InvalidField { field, .. }) if field == "s_inode_size"
        ));
    }

    #[test]
    fn an_odd_inode_size_short_of_the_extra_field_reads_and_writes_without_panic() {
        // `read_from`/`write_to` accept any `inode_size >= 128`, not only the power-of-two
        // sizes a real filesystem uses. A 129-byte inode reaches one byte past the classic
        // inode yet cannot hold the two-byte `i_extra_isize` at 0x80, so both directions
        // must treat it as carrying no extra area rather than indexing byte 129 of a
        // 129-byte buffer.
        for size in [129u16, 130] {
            let buf = vec![0u8; size as usize];
            let ino = Inode::read_from(&buf, size).expect("parses without panic");
            assert_eq!(ino.extra_isize, 0);
            assert!(ino.inline_xattr.is_empty());

            // Serializing into a buffer of exactly `inode_size` must not index past it.
            let mut out = vec![0u8; size as usize];
            let mut written = Inode::empty(size);
            written.extra_isize = 0;
            written
                .write_to(&mut out, size)
                .expect("serializes without panic");
            assert_eq!(out.len(), size as usize);
        }

        // At 130 bytes the field just fits (0x80..0x82), so a declaration survives the
        // round trip; the two bytes it occupies are the inode's last two.
        let mut ino = Inode::empty(130);
        ino.extra_isize = 2;
        let mut out = vec![0u8; 130];
        ino.write_to(&mut out, 130).expect("serializes");
        assert_eq!(
            get_u16(&out, 0x80),
            2,
            "i_extra_isize occupies the last two bytes"
        );
        assert_eq!(Inode::read_from(&out, 130).unwrap().extra_isize, 2);
    }

    #[test]
    fn timestamp_encodes_seconds_and_nanoseconds() {
        let t = Timestamp {
            secs: 1_700_000_000,
            nanos: 123_456_789,
        };
        let (field, extra) = encode_time(t);
        assert_eq!(field, 1_700_000_000);
        assert_eq!(extra & 0x3, 0, "epoch high bits");
        assert_eq!(extra >> 2, 123_456_789, "nanoseconds");
        assert_eq!(decode_time(field, extra), t);
    }

    #[test]
    fn timestamp_matches_kernel_epoch_scheme() {
        // The on-disk seconds are (i32)field + (epoch << 32), not a sign-extended
        // 34-bit integer. These vectors are the exact bytes e2fsprogs/debugfs write —
        // a self-round-trip test passes under either scheme, so it cannot catch a wrong
        // one. Confirmed against `debugfs stat`: 2038-01-19 stores as 0x80000000:1.
        for (secs, field, epoch) in [
            (-86_400i64, 0xfffe_ae80u32, 0u32), // 1969-12-31, pre-epoch, epoch 0
            (-1, 0xffff_ffff, 0),               // one second before 1970
            (2_147_483_648, 0x8000_0000, 1),    // 2038-01-19, first post-2038 second
            (4_294_967_296, 0x0000_0000, 1),    // 2106, exactly 2^32
            (1_700_000_000, 0x6553_f100, 0),    // an in-range recent time
        ] {
            let (f, e) = encode_time(Timestamp::from_secs(secs));
            assert_eq!(f, field, "field for secs={secs}");
            assert_eq!(e & 0x3, epoch, "epoch for secs={secs}");
            assert_eq!(
                decode_time(f, e),
                Timestamp::from_secs(secs),
                "round-trip for secs={secs}"
            );
        }
    }

    #[test]
    fn timestamp_representable_range_tracks_the_on_disk_limits() {
        assert_eq!(TIME_SECS_MIN, -(1 << 31));
        assert_eq!(TIME_SECS_MAX, (1 << 31) - 1 + (3 << 32));
        let held = |t: Timestamp| time_is_representable(t, 256);
        assert!(held(Timestamp::from_secs(0)));
        assert!(held(Timestamp::from_secs(TIME_SECS_MIN)));
        assert!(held(Timestamp::from_secs(TIME_SECS_MAX)));
        assert!(!held(Timestamp::from_secs(TIME_SECS_MIN - 1)));
        assert!(!held(Timestamp::from_secs(TIME_SECS_MAX + 1)));
        // A nanosecond fraction at or past one second cannot be represented.
        assert!(!held(Timestamp {
            secs: 0,
            nanos: Timestamp::NANOS_PER_SEC
        }));
    }

    #[test]
    fn an_inode_with_no_extra_words_holds_a_signed_second_and_no_fraction() {
        let held = |t: Timestamp| time_is_representable(t, 128);
        assert!(held(Timestamp::from_secs(TIME_SECS_MIN)));
        assert!(held(Timestamp::from_secs(i64::from(i32::MAX))));
        assert!(!held(Timestamp::from_secs(i64::from(i32::MAX) + 1)));
        assert!(!held(Timestamp { secs: 0, nanos: 1 }));
        // What either would lose: the 128-byte inode writes the seconds field alone.
        let t = Timestamp {
            secs: i64::from(i32::MAX) + 1,
            nanos: 5,
        };
        let mut ino = Inode::empty(128);
        ino.mtime = t;
        let mut buf = vec![0u8; 128];
        ino.write_to(&mut buf, 128).expect("writes");
        let back = Inode::read_from(&buf, 128).expect("parses");
        assert_ne!(back.mtime, t, "the instant does not survive");
        assert!(time_is_representable(t, 256));
    }

    #[test]
    fn a_device_number_is_laid_out_as_a_kernel_and_debugfs_lay_it_out() {
        // (major, minor) -> (i_block[0], i_block[1]), read out of device nodes a Linux 7.1
        // kernel made (`mknod`) and the pinned `debugfs` made (`mknod`), then dumped.
        let observed = [
            ((1, 3), (0x0000_0103, 0)),
            ((8, 0), (0x0000_0800, 0)),
            ((0, 1), (0x0000_0001, 0)),
            ((255, 255), (0x0000_ffff, 0)),
            ((0, 0), (0, 0)),
            ((256, 0), (0, 0x0001_0000)),
            ((0, 256), (0, 0x0010_0000)),
            ((255, 256), (0, 0x0010_ff00)),
            ((256, 255), (0, 0x0001_00ff)),
            ((300, 5), (0, 0x0001_2c05)),
            ((4095, 0), (0, 0x000f_ff00)),
            ((0, 65_535), (0, 0x0ff0_00ff)),
            ((255, 65_536), (0, 0x1000_ff00)),
            ((0x123, 0x4_5678), (0, 0x4561_2378)),
            ((0, 1_048_575), (0, 0xfff0_00ff)),
            ((4095, 1_048_575), (0, 0xffff_ffff)),
        ];
        for ((major, minor), words) in observed {
            assert_eq!(encode_device(major, minor), words, "{major}:{minor}");
            assert_eq!(
                decode_device(words.0, words.1),
                (major, minor),
                "{words:x?}"
            );
        }
    }

    #[test]
    fn every_device_number_in_range_round_trips() {
        for major in (0..4096).step_by(7).chain([255, 256, 4095]) {
            for minor in (0..1 << 20)
                .step_by(4099)
                .chain([255, 256, 65_535, 1_048_575])
            {
                let (b0, b1) = encode_device(major, minor);
                assert_eq!(decode_device(b0, b1), (major, minor), "{major}:{minor}");
                assert!(b0 == 0 || b1 == 0, "one form at a time");
            }
        }
    }

    #[test]
    fn inline_xattr_region_round_trips() {
        let mut ino = root_like();
        // A minimal inline region: magic then a zero terminator, padded to 96 bytes.
        let mut region = vec![0u8; 96];
        region[0..4].copy_from_slice(&XATTR_MAGIC.to_le_bytes());
        ino.inline_xattr = region.clone();
        let b = bytes(&ino, S);
        // The region lands at 0xa0 (128 + extra_isize of 32).
        assert_eq!(get_u32(&b, 0xa0), 0xEA02_0000);
        let back = Inode::read_from(&b, S).unwrap();
        assert_eq!(back.inline_xattr, region);
        assert_eq!(back, ino);
    }

    #[test]
    fn absent_inline_xattr_stays_empty() {
        let ino = root_like();
        let back = Inode::read_from(&bytes(&ino, S), S).unwrap();
        assert!(back.inline_xattr.is_empty());
        assert_eq!(back, ino);
    }

    #[test]
    fn the_inline_xattr_region_grows_with_the_inode() {
        // The region is what is left after the classic inode and the extra area, so it
        // scales with s_inode_size — and a 128-byte inode has none.
        let ino = root_like();
        assert_eq!(ino.inline_xattr_capacity(128), 0);
        assert_eq!(ino.inline_xattr_capacity(256), 96);
        assert_eq!(ino.inline_xattr_capacity(512), 352);
        assert_eq!(ino.inline_xattr_capacity(1024), 864);

        // A region sized for the larger inode round-trips through it.
        let mut big = Inode::empty(512);
        let mut region = vec![0u8; big.inline_xattr_capacity(512)];
        region[0..4].copy_from_slice(&XATTR_MAGIC.to_le_bytes());
        big.inline_xattr = region.clone();
        let back = Inode::read_from(&bytes(&big, 512), 512).unwrap();
        assert_eq!(back.inline_xattr, region);
    }
}