libpna 0.35.0

PNA(Portable-Network-Archive) decoding and encoding library
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
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
//! Metadata and permission types for archive entries.

use crate::util::bounded::{LengthExceeded, str::BoundedString};
use crate::{Duration, UnknownValueError};
use std::io::{self, Read};
use std::ops::Deref;
use std::str;

/// Metadata information about an entry.
/// # Examples
/// ```rust
/// # use std::time::SystemTimeError;
/// # fn main() -> Result<(), SystemTimeError> {
/// use libpna::{Duration, Metadata};
///
/// let since_unix_epoch = Duration::seconds(1000);
/// let metadata = Metadata::new()
///     .with_accessed(Some(since_unix_epoch))
///     .with_created(Some(since_unix_epoch))
///     .with_modified(Some(since_unix_epoch));
/// # Ok(())
/// # }
/// ```
#[allow(deprecated)]
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct Metadata {
    pub(crate) raw_file_size: Option<u128>,
    pub(crate) compressed_size: usize,
    pub(crate) created: Option<Duration>,
    pub(crate) modified: Option<Duration>,
    pub(crate) accessed: Option<Duration>,
    pub(crate) permission: Option<Permission>,
    pub(crate) link_target_type: Option<LinkTargetType>,
    pub(crate) owner_uid: Option<OwnerUid>,
    pub(crate) owner_gid: Option<OwnerGid>,
    pub(crate) owner_user_name: Option<OwnerUserName>,
    pub(crate) owner_group_name: Option<OwnerGroupName>,
    pub(crate) owner_user_sid: Option<OwnerUserSid>,
    pub(crate) owner_group_sid: Option<OwnerGroupSid>,
    pub(crate) permission_mode: Option<PermissionMode>,
}

impl Metadata {
    /// Creates a new [`Metadata`].
    #[inline]
    pub const fn new() -> Self {
        Self {
            raw_file_size: Some(0),
            compressed_size: 0,
            created: None,
            modified: None,
            accessed: None,
            permission: None,
            link_target_type: None,
            owner_uid: None,
            owner_gid: None,
            owner_user_name: None,
            owner_group_name: None,
            owner_user_sid: None,
            owner_group_sid: None,
            permission_mode: None,
        }
    }

    /// Sets the created time as the duration since the Unix epoch.
    ///
    /// # Examples
    /// ```rust
    /// # use std::time::SystemTimeError;
    /// # fn main() -> Result<(), SystemTimeError> {
    /// use libpna::{Duration, Metadata};
    ///
    /// let since_unix_epoch = Duration::seconds(1000);
    /// let metadata = Metadata::new().with_created(Some(since_unix_epoch));
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub const fn with_created(mut self, created: Option<Duration>) -> Self {
        self.created = created;
        self
    }

    /// Sets the modified time as the duration since the Unix epoch.
    ///
    /// # Examples
    /// ```rust
    /// # use std::time::SystemTimeError;
    /// # fn main() -> Result<(), SystemTimeError> {
    /// use libpna::{Duration, Metadata};
    ///
    /// let since_unix_epoch = Duration::seconds(1000);
    /// let metadata = Metadata::new().with_modified(Some(since_unix_epoch));
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub const fn with_modified(mut self, modified: Option<Duration>) -> Self {
        self.modified = modified;
        self
    }

    /// Sets the accessed time as the duration since the Unix epoch.
    ///
    /// # Examples
    /// ```rust
    /// # use std::time::SystemTimeError;
    /// # fn main() -> Result<(), SystemTimeError> {
    /// use libpna::{Duration, Metadata};
    ///
    /// let since_unix_epoch = Duration::seconds(1000);
    /// let metadata = Metadata::new().with_accessed(Some(since_unix_epoch));
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub const fn with_accessed(mut self, accessed: Option<Duration>) -> Self {
        self.accessed = accessed;
        self
    }

    /// Sets the permission of the entry.
    #[deprecated(
        since = "0.34.0",
        note = "the fPRM chunk is superseded by the owner facet chunks; use Metadata::with_owner_uid/with_owner_gid/with_owner_user_name/with_owner_group_name/with_owner_user_sid/with_owner_group_sid/with_permission_mode"
    )]
    #[allow(deprecated)]
    #[inline]
    pub fn with_permission(mut self, permission: Option<Permission>) -> Self {
        self.permission = permission;
        self
    }

    /// Sets the owner user id facet (`fUId`).
    #[inline]
    pub fn with_owner_uid(mut self, value: Option<OwnerUid>) -> Self {
        self.owner_uid = value;
        self
    }
    /// Sets the owner group id facet (`fGId`).
    #[inline]
    pub fn with_owner_gid(mut self, value: Option<OwnerGid>) -> Self {
        self.owner_gid = value;
        self
    }
    /// Sets the owner user name facet (`fONm`).
    #[inline]
    pub fn with_owner_user_name(mut self, value: Option<OwnerUserName>) -> Self {
        self.owner_user_name = value;
        self
    }
    /// Sets the owner group name facet (`fGNm`).
    #[inline]
    pub fn with_owner_group_name(mut self, value: Option<OwnerGroupName>) -> Self {
        self.owner_group_name = value;
        self
    }
    /// Sets the owner user SID facet (`fOSi`).
    #[inline]
    pub fn with_owner_user_sid(mut self, value: Option<OwnerUserSid>) -> Self {
        self.owner_user_sid = value;
        self
    }
    /// Sets the owner group SID facet (`fGSi`).
    #[inline]
    pub fn with_owner_group_sid(mut self, value: Option<OwnerGroupSid>) -> Self {
        self.owner_group_sid = value;
        self
    }
    /// Sets the POSIX permission mode facet (`fMOd`).
    #[inline]
    pub fn with_permission_mode(mut self, value: Option<PermissionMode>) -> Self {
        self.permission_mode = value;
        self
    }

    /// Sets the link target type of the entry.
    /// Only meaningful for symbolic link and hard link entries.
    #[inline]
    pub const fn with_link_target_type(mut self, link_target_type: Option<LinkTargetType>) -> Self {
        self.link_target_type = link_target_type;
        self
    }

    /// Returns the raw file size of this entry's data in bytes.
    #[inline]
    pub const fn raw_file_size(&self) -> Option<u128> {
        self.raw_file_size
    }
    /// Returns the compressed size of this entry's data in bytes.
    #[inline]
    pub const fn compressed_size(&self) -> usize {
        self.compressed_size
    }
    /// Returns the created time since the Unix epoch for the entry.
    #[inline]
    pub const fn created(&self) -> Option<Duration> {
        self.created
    }
    /// Returns the modified time since the Unix epoch for the entry.
    #[inline]
    pub const fn modified(&self) -> Option<Duration> {
        self.modified
    }
    /// Returns the accessed time since the Unix epoch for the entry.
    #[inline]
    pub const fn accessed(&self) -> Option<Duration> {
        self.accessed
    }
    /// Returns the owner, group, and permission bits for the entry.
    #[deprecated(
        since = "0.34.0",
        note = "the fPRM chunk is superseded by the owner facet chunks; use Metadata::owner_uid/owner_gid/owner_user_name/owner_group_name/owner_user_sid/owner_group_sid/permission_mode"
    )]
    #[allow(deprecated)]
    #[inline]
    pub const fn permission(&self) -> Option<&Permission> {
        self.permission.as_ref()
    }
    /// Returns the owner user id facet (`fUId`), if recorded.
    #[inline]
    pub const fn owner_uid(&self) -> Option<OwnerUid> {
        self.owner_uid
    }
    /// Returns the owner group id facet (`fGId`), if recorded.
    #[inline]
    pub const fn owner_gid(&self) -> Option<OwnerGid> {
        self.owner_gid
    }
    /// Returns the owner user name facet (`fONm`), if recorded.
    #[inline]
    pub fn owner_user_name(&self) -> Option<&OwnerUserName> {
        self.owner_user_name.as_ref()
    }
    /// Returns the owner group name facet (`fGNm`), if recorded.
    #[inline]
    pub fn owner_group_name(&self) -> Option<&OwnerGroupName> {
        self.owner_group_name.as_ref()
    }
    /// Returns the owner user SID facet (`fOSi`), if recorded.
    #[inline]
    pub fn owner_user_sid(&self) -> Option<&OwnerUserSid> {
        self.owner_user_sid.as_ref()
    }
    /// Returns the owner group SID facet (`fGSi`), if recorded.
    #[inline]
    pub fn owner_group_sid(&self) -> Option<&OwnerGroupSid> {
        self.owner_group_sid.as_ref()
    }
    /// Returns the POSIX permission mode facet (`fMOd`), if recorded.
    #[inline]
    pub const fn permission_mode(&self) -> Option<PermissionMode> {
        self.permission_mode
    }

    /// Returns the link target type for this entry, if present.
    ///
    /// - `None`: fLTP chunk was absent.
    /// - `Some(Unknown)`: fLTP chunk present but target type undetermined.
    /// - `Some(File)` / `Some(Directory)`: known target type.
    #[inline]
    pub const fn link_target_type(&self) -> Option<LinkTargetType> {
        self.link_target_type
    }
}

impl Default for Metadata {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

/// Owner, group, and permission bits for an archive entry.
#[deprecated(
    since = "0.34.0",
    note = "the fPRM chunk is superseded by the owner facet chunks; use the owner facet API (Metadata::owner_uid/owner_gid/owner_user_name/owner_group_name/owner_user_sid/owner_group_sid/permission_mode and the matching EntryBuilder/with_* setters)"
)]
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct Permission {
    uid: u64,
    uname: String,
    gid: u64,
    gname: String,
    permission: u16,
}

#[allow(deprecated)]
impl Permission {
    /// Creates a new [`Permission`] with the given user, group, and permission bits.
    ///
    /// The `uid`/`gid` are numeric POSIX IDs, `uname`/`gname` are the
    /// corresponding names, and `permission` holds the file mode bits (e.g. `0o755`).
    ///
    /// # Examples
    ///
    /// ```
    /// # #![allow(deprecated)]
    /// use libpna::Permission;
    ///
    /// let perm = Permission::new(1000, "user".into(), 100, "group".into(), 0o755);
    /// ```
    #[deprecated(
        since = "0.34.0",
        note = "the fPRM chunk is superseded by the owner facet chunks; use the owner facet API (Metadata::owner_uid/owner_gid/owner_user_name/owner_group_name/owner_user_sid/owner_group_sid/permission_mode and the matching EntryBuilder/with_* setters)"
    )]
    #[inline]
    pub const fn new(uid: u64, uname: String, gid: u64, gname: String, permission: u16) -> Self {
        Self {
            uid,
            uname,
            gid,
            gname,
            permission,
        }
    }
    /// Returns the user ID associated with this permission.
    ///
    /// # Examples
    ///
    /// ```
    /// # #![allow(deprecated)]
    /// use libpna::Permission;
    ///
    /// let perm = Permission::new(1000, "user1".into(), 100, "group1".into(), 0o644);
    /// assert_eq!(perm.uid(), 1000);
    /// ```
    #[deprecated(
        since = "0.34.0",
        note = "the fPRM chunk is superseded by the owner facet chunks; use the owner facet API (Metadata::owner_uid/owner_gid/owner_user_name/owner_group_name/owner_user_sid/owner_group_sid/permission_mode and the matching EntryBuilder/with_* setters)"
    )]
    #[inline]
    pub const fn uid(&self) -> u64 {
        self.uid
    }

    /// Returns the user name associated with this permission.
    ///
    /// # Examples
    ///
    /// ```
    /// # #![allow(deprecated)]
    /// use libpna::Permission;
    ///
    /// let perm = Permission::new(1000, "user1".into(), 100, "group1".into(), 0o644);
    /// assert_eq!(perm.uname(), "user1");
    /// ```
    #[deprecated(
        since = "0.34.0",
        note = "the fPRM chunk is superseded by the owner facet chunks; use the owner facet API (Metadata::owner_uid/owner_gid/owner_user_name/owner_group_name/owner_user_sid/owner_group_sid/permission_mode and the matching EntryBuilder/with_* setters)"
    )]
    #[inline]
    pub fn uname(&self) -> &str {
        &self.uname
    }

    /// Returns the group ID associated with this permission.
    ///
    /// # Examples
    ///
    /// ```
    /// # #![allow(deprecated)]
    /// use libpna::Permission;
    ///
    /// let perm = Permission::new(1000, "user1".into(), 100, "group1".into(), 0o644);
    /// assert_eq!(perm.gid(), 100);
    /// ```
    #[deprecated(
        since = "0.34.0",
        note = "the fPRM chunk is superseded by the owner facet chunks; use the owner facet API (Metadata::owner_uid/owner_gid/owner_user_name/owner_group_name/owner_user_sid/owner_group_sid/permission_mode and the matching EntryBuilder/with_* setters)"
    )]
    #[inline]
    pub const fn gid(&self) -> u64 {
        self.gid
    }

    /// Returns the group name associated with this permission.
    ///
    /// # Examples
    ///
    /// ```
    /// # #![allow(deprecated)]
    /// use libpna::Permission;
    ///
    /// let perm = Permission::new(1000, "user1".into(), 100, "group1".into(), 0o644);
    /// assert_eq!(perm.gname(), "group1");
    /// ```
    #[deprecated(
        since = "0.34.0",
        note = "the fPRM chunk is superseded by the owner facet chunks; use the owner facet API (Metadata::owner_uid/owner_gid/owner_user_name/owner_group_name/owner_user_sid/owner_group_sid/permission_mode and the matching EntryBuilder/with_* setters)"
    )]
    #[inline]
    pub fn gname(&self) -> &str {
        &self.gname
    }

    /// Returns the permission bits associated with this permission.
    ///
    /// # Examples
    ///
    /// ```
    /// # #![allow(deprecated)]
    /// use libpna::Permission;
    ///
    /// let perm = Permission::new(1000, "user1".into(), 100, "group1".into(), 0o644);
    /// assert_eq!(perm.permissions(), 0o644);
    /// ```
    #[deprecated(
        since = "0.34.0",
        note = "the fPRM chunk is superseded by the owner facet chunks; use the owner facet API (Metadata::owner_uid/owner_gid/owner_user_name/owner_group_name/owner_user_sid/owner_group_sid/permission_mode and the matching EntryBuilder/with_* setters)"
    )]
    #[inline]
    pub const fn permissions(&self) -> u16 {
        self.permission
    }

    pub(crate) fn to_bytes(&self) -> Vec<u8> {
        let mut bytes = Vec::with_capacity(20 + self.uname.len() + self.gname.len());
        bytes.extend_from_slice(&self.uid.to_be_bytes());
        bytes.extend_from_slice(&(self.uname.len() as u8).to_be_bytes());
        bytes.extend_from_slice(self.uname.as_bytes());
        bytes.extend_from_slice(&self.gid.to_be_bytes());
        bytes.extend_from_slice(&(self.gname.len() as u8).to_be_bytes());
        bytes.extend_from_slice(self.gname.as_bytes());
        bytes.extend_from_slice(&self.permission.to_be_bytes());
        bytes
    }

    pub(crate) fn try_from_bytes(mut bytes: &[u8]) -> io::Result<Self> {
        let uid = u64::from_be_bytes({
            let mut buf = [0; 8];
            bytes.read_exact(&mut buf)?;
            buf
        });
        let uname_len = {
            let mut buf = [0; 1];
            bytes.read_exact(&mut buf)?;
            buf[0] as usize
        };
        let uname = String::from_utf8({
            let mut buf = vec![0; uname_len];
            bytes.read_exact(&mut buf)?;
            buf
        })
        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
        let gid = u64::from_be_bytes({
            let mut buf = [0; 8];
            bytes.read_exact(&mut buf)?;
            buf
        });
        let gname_len = {
            let mut buf = [0; 1];
            bytes.read_exact(&mut buf)?;
            buf[0] as usize
        };
        let gname = String::from_utf8({
            let mut buf = vec![0; gname_len];
            bytes.read_exact(&mut buf)?;
            buf
        })
        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
        let permission = u16::from_be_bytes({
            let mut buf = [0; 2];
            bytes.read_exact(&mut buf)?;
            buf
        });
        Ok(Self {
            uid,
            uname,
            gid,
            gname,
            permission,
        })
    }
}

/// Maximum owner-facet string byte length (the `fONm`/`fGNm`/`fOSi`/`fGSi`
/// chunk Body uses a 1-byte length prefix).
const OWNER_STR_MAX: usize = u8::MAX as usize;

/// Owner user name (`fONm`).
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default)]
#[repr(transparent)]
pub struct OwnerUserName(BoundedString<OWNER_STR_MAX>);

impl OwnerUserName {
    /// Constructs an [`OwnerUserName`].
    ///
    /// # Errors
    ///
    /// Returns [`LengthExceeded`] when the byte length exceeds 255.
    #[inline]
    pub fn new(value: impl Into<Box<str>>) -> Result<Self, LengthExceeded> {
        BoundedString::new(value).map(Self)
    }
    /// Returns the name as a string slice.
    #[inline]
    #[must_use]
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }
    pub(crate) fn to_bytes(&self) -> Vec<u8> {
        let b = self.0.as_str().as_bytes();
        let mut v = Vec::with_capacity(1 + b.len());
        // Type guarantees b.len() <= 255 (BoundedString<255> invariant).
        v.push(b.len() as u8);
        v.extend_from_slice(b);
        v
    }
    pub(crate) fn try_from_bytes(bytes: &[u8]) -> io::Result<Self> {
        let (&len, rest) = bytes.split_first().ok_or(io::ErrorKind::UnexpectedEof)?;
        let s = rest
            .get(..len as usize)
            .ok_or(io::ErrorKind::UnexpectedEof)?;
        let s = str::from_utf8(s).map_err(|_| io::ErrorKind::InvalidData)?;
        Self::new(s.to_owned()).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
    }
}

impl Deref for OwnerUserName {
    type Target = str;
    #[inline]
    fn deref(&self) -> &str {
        self.0.as_str()
    }
}
impl TryFrom<String> for OwnerUserName {
    type Error = LengthExceeded;
    #[inline]
    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}
impl TryFrom<&str> for OwnerUserName {
    type Error = LengthExceeded;
    #[inline]
    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}
impl From<OwnerUserName> for String {
    #[inline]
    fn from(value: OwnerUserName) -> Self {
        value.0.into()
    }
}

/// Owner group name (`fGNm`).
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default)]
#[repr(transparent)]
pub struct OwnerGroupName(BoundedString<OWNER_STR_MAX>);

impl OwnerGroupName {
    /// Constructs an [`OwnerGroupName`].
    ///
    /// # Errors
    ///
    /// Returns [`LengthExceeded`] when the byte length exceeds 255.
    #[inline]
    pub fn new(value: impl Into<Box<str>>) -> Result<Self, LengthExceeded> {
        BoundedString::new(value).map(Self)
    }
    /// Returns the name as a string slice.
    #[inline]
    #[must_use]
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }
    pub(crate) fn to_bytes(&self) -> Vec<u8> {
        let b = self.0.as_str().as_bytes();
        let mut v = Vec::with_capacity(1 + b.len());
        // Type guarantees b.len() <= 255 (BoundedString<255> invariant).
        v.push(b.len() as u8);
        v.extend_from_slice(b);
        v
    }
    pub(crate) fn try_from_bytes(bytes: &[u8]) -> io::Result<Self> {
        let (&len, rest) = bytes.split_first().ok_or(io::ErrorKind::UnexpectedEof)?;
        let s = rest
            .get(..len as usize)
            .ok_or(io::ErrorKind::UnexpectedEof)?;
        let s = str::from_utf8(s).map_err(|_| io::ErrorKind::InvalidData)?;
        Self::new(s.to_owned()).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
    }
}

impl Deref for OwnerGroupName {
    type Target = str;
    #[inline]
    fn deref(&self) -> &str {
        self.0.as_str()
    }
}
impl TryFrom<String> for OwnerGroupName {
    type Error = LengthExceeded;
    #[inline]
    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}
impl TryFrom<&str> for OwnerGroupName {
    type Error = LengthExceeded;
    #[inline]
    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}
impl From<OwnerGroupName> for String {
    #[inline]
    fn from(value: OwnerGroupName) -> Self {
        value.0.into()
    }
}

/// Owner user SID (`fOSi`).
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default)]
#[repr(transparent)]
pub struct OwnerUserSid(BoundedString<OWNER_STR_MAX>);

impl OwnerUserSid {
    /// Constructs an [`OwnerUserSid`].
    ///
    /// # Errors
    ///
    /// Returns [`LengthExceeded`] when the byte length exceeds 255.
    #[inline]
    pub fn new(value: impl Into<Box<str>>) -> Result<Self, LengthExceeded> {
        BoundedString::new(value).map(Self)
    }
    /// Returns the name as a string slice.
    #[inline]
    #[must_use]
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }
    pub(crate) fn to_bytes(&self) -> Vec<u8> {
        let b = self.0.as_str().as_bytes();
        let mut v = Vec::with_capacity(1 + b.len());
        // Type guarantees b.len() <= 255 (BoundedString<255> invariant).
        v.push(b.len() as u8);
        v.extend_from_slice(b);
        v
    }
    pub(crate) fn try_from_bytes(bytes: &[u8]) -> io::Result<Self> {
        let (&len, rest) = bytes.split_first().ok_or(io::ErrorKind::UnexpectedEof)?;
        let s = rest
            .get(..len as usize)
            .ok_or(io::ErrorKind::UnexpectedEof)?;
        let s = str::from_utf8(s).map_err(|_| io::ErrorKind::InvalidData)?;
        Self::new(s.to_owned()).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
    }
}

impl Deref for OwnerUserSid {
    type Target = str;
    #[inline]
    fn deref(&self) -> &str {
        self.0.as_str()
    }
}
impl TryFrom<String> for OwnerUserSid {
    type Error = LengthExceeded;
    #[inline]
    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}
impl TryFrom<&str> for OwnerUserSid {
    type Error = LengthExceeded;
    #[inline]
    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}
impl From<OwnerUserSid> for String {
    #[inline]
    fn from(value: OwnerUserSid) -> Self {
        value.0.into()
    }
}

/// Owner group SID (`fGSi`).
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default)]
#[repr(transparent)]
pub struct OwnerGroupSid(BoundedString<OWNER_STR_MAX>);

impl OwnerGroupSid {
    /// Constructs an [`OwnerGroupSid`].
    ///
    /// # Errors
    ///
    /// Returns [`LengthExceeded`] when the byte length exceeds 255.
    #[inline]
    pub fn new(value: impl Into<Box<str>>) -> Result<Self, LengthExceeded> {
        BoundedString::new(value).map(Self)
    }
    /// Returns the name as a string slice.
    #[inline]
    #[must_use]
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }
    pub(crate) fn to_bytes(&self) -> Vec<u8> {
        let b = self.0.as_str().as_bytes();
        let mut v = Vec::with_capacity(1 + b.len());
        // Type guarantees b.len() <= 255 (BoundedString<255> invariant).
        v.push(b.len() as u8);
        v.extend_from_slice(b);
        v
    }
    pub(crate) fn try_from_bytes(bytes: &[u8]) -> io::Result<Self> {
        let (&len, rest) = bytes.split_first().ok_or(io::ErrorKind::UnexpectedEof)?;
        let s = rest
            .get(..len as usize)
            .ok_or(io::ErrorKind::UnexpectedEof)?;
        let s = str::from_utf8(s).map_err(|_| io::ErrorKind::InvalidData)?;
        Self::new(s.to_owned()).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
    }
}

impl Deref for OwnerGroupSid {
    type Target = str;
    #[inline]
    fn deref(&self) -> &str {
        self.0.as_str()
    }
}
impl TryFrom<String> for OwnerGroupSid {
    type Error = LengthExceeded;
    #[inline]
    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}
impl TryFrom<&str> for OwnerGroupSid {
    type Error = LengthExceeded;
    #[inline]
    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}
impl From<OwnerGroupSid> for String {
    #[inline]
    fn from(value: OwnerGroupSid) -> Self {
        value.0.into()
    }
}

/// Owner user id (`fUId`).
#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default)]
#[repr(transparent)]
pub struct OwnerUid(u64);

impl OwnerUid {
    /// Returns the raw user id.
    #[inline]
    #[must_use]
    pub const fn get(self) -> u64 {
        self.0
    }
    pub(crate) fn to_bytes(self) -> [u8; 8] {
        self.0.to_be_bytes()
    }
    pub(crate) fn try_from_bytes(bytes: &[u8]) -> io::Result<Self> {
        let a: [u8; 8] = bytes
            .try_into()
            .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "fUId must be 8 bytes"))?;
        Ok(Self(u64::from_be_bytes(a)))
    }
}
impl From<u64> for OwnerUid {
    #[inline]
    fn from(v: u64) -> Self {
        Self(v)
    }
}

/// Owner group id (`fGId`).
#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default)]
#[repr(transparent)]
pub struct OwnerGid(u64);

impl OwnerGid {
    /// Returns the raw group id.
    #[inline]
    #[must_use]
    pub const fn get(self) -> u64 {
        self.0
    }
    pub(crate) fn to_bytes(self) -> [u8; 8] {
        self.0.to_be_bytes()
    }
    pub(crate) fn try_from_bytes(bytes: &[u8]) -> io::Result<Self> {
        let a: [u8; 8] = bytes
            .try_into()
            .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "fGId must be 8 bytes"))?;
        Ok(Self(u64::from_be_bytes(a)))
    }
}
impl From<u64> for OwnerGid {
    #[inline]
    fn from(v: u64) -> Self {
        Self(v)
    }
}

/// POSIX permission mode (`fMOd`). Reserved bits outside `0o7777`
/// (the rwx + setuid/setgid/sticky bits) are masked to 0 on construction.
#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default)]
#[repr(transparent)]
pub struct PermissionMode(u16);

impl PermissionMode {
    /// Returns the permission bits (`0o7777`-masked).
    #[inline]
    #[must_use]
    pub const fn get(self) -> u16 {
        self.0
    }
    pub(crate) fn to_bytes(self) -> [u8; 2] {
        self.0.to_be_bytes()
    }
    pub(crate) fn try_from_bytes(bytes: &[u8]) -> io::Result<Self> {
        let a: [u8; 2] = bytes
            .try_into()
            .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "fMOd must be 2 bytes"))?;
        Ok(Self::from(u16::from_be_bytes(a)))
    }
}
impl From<u16> for PermissionMode {
    #[inline]
    fn from(v: u16) -> Self {
        Self(v & 0o7777)
    }
}

/// Link target type for link entries.
///
/// Stored in the `fLTP` ancillary chunk. Indicates whether the link target
/// is a file or a directory. The semantic interpretation depends on the
/// entry's [`DataKind`](crate::DataKind):
///
/// | `DataKind` | `Unknown` | `File` | `Directory` |
/// |---|---|---|---|
/// | `SymbolicLink` | Symlink (target unknown) | File symlink | Directory symlink |
/// | `HardLink` | Hard link (target unknown) | File hard link | Directory hard link |
///
/// `HardLink` + `Directory` represents a directory hard link — a hard link
/// whose target is a directory. On systems that prohibit hard links to
/// directories, implementations may fall back to a symbolic link.
///
/// # Value assignments
///
/// - `Unknown` (0): Explicit unknown — the target type was not determined.
/// - `File` (1): Target is a file.
/// - `Directory` (2): Target is a directory.
/// - Values 3–63 are reserved for future public extensions.
/// - Values 64–255 are reserved for private extensions.
/// - Both ranges are currently unrecognized and fall back to `None`.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
#[repr(u8)]
pub enum LinkTargetType {
    /// Link target type is unknown.
    Unknown = 0,
    /// Link target is a file.
    File = 1,
    /// Link target is a directory.
    Directory = 2,
}

impl TryFrom<u8> for LinkTargetType {
    type Error = UnknownValueError;

    #[inline]
    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            0 => Ok(Self::Unknown),
            1 => Ok(Self::File),
            2 => Ok(Self::Directory),
            value => Err(UnknownValueError(value)),
        }
    }
}

impl LinkTargetType {
    pub(crate) fn to_bytes(self) -> [u8; 1] {
        [self as u8]
    }

    /// Parse fLTP chunk data.
    ///
    /// - Known values (0, 1, 2): `Ok(Some(variant))`
    /// - Unrecognized values (3-255): `Ok(None)` (graceful fallback)
    /// - Insufficient data: `Err`
    pub(crate) fn try_from_bytes(mut bytes: &[u8]) -> io::Result<Option<Self>> {
        let mut buf = [0u8; 1];
        bytes.read_exact(&mut buf)?;
        Ok(Self::try_from(buf[0]).ok())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(all(target_family = "wasm", target_os = "unknown"))]
    use wasm_bindgen_test::wasm_bindgen_test as test;

    #[allow(deprecated)]
    #[test]
    fn permission() {
        let perm = Permission::new(1000, "user1".into(), 100, "group1".into(), 0o644);
        assert_eq!(perm, Permission::try_from_bytes(&perm.to_bytes()).unwrap());
    }

    #[test]
    fn owner_string_newtype_bound_and_codec() {
        use crate::entry::OwnerUserName;
        assert!(OwnerUserName::new("").is_ok());
        assert!(OwnerUserName::new("alice").is_ok());
        assert!(OwnerUserName::new("a".repeat(255)).is_ok());
        assert!(OwnerUserName::new("a".repeat(256)).is_err());
        let n = OwnerUserName::new("alice").unwrap();
        assert_eq!(n.to_bytes(), vec![5, b'a', b'l', b'i', b'c', b'e']);
        assert_eq!(OwnerUserName::try_from_bytes(&n.to_bytes()).unwrap(), n);
        assert_eq!(OwnerUserName::try_from_bytes(&[0]).unwrap().as_str(), "");
        assert_eq!(
            OwnerUserName::try_from_bytes(&[3, b'a', b'b', b'c', 0xFF])
                .unwrap()
                .as_str(),
            "abc"
        );
        assert!(OwnerUserName::try_from_bytes(&[]).is_err());
        assert!(OwnerUserName::try_from_bytes(&[5, b'a']).is_err());
        assert!(OwnerUserName::try_from_bytes(&[1, 0xFF]).is_err());
    }

    #[test]
    fn owner_uid_and_permission_mode_codec() {
        use crate::entry::{OwnerUid, PermissionMode};
        let u = OwnerUid::from(1000u64);
        assert_eq!(u.get(), 1000);
        assert_eq!(u.to_bytes(), 1000u64.to_be_bytes());
        assert_eq!(OwnerUid::try_from_bytes(&u.to_bytes()).unwrap(), u);
        assert!(OwnerUid::try_from_bytes(&[0, 0, 0]).is_err());
        assert_eq!(PermissionMode::from(0o7777u16).get(), 0o7777);
        assert_eq!(PermissionMode::from(0o170755u16).get(), 0o0755);
        let m = PermissionMode::from(0o644u16);
        assert_eq!(m.to_bytes(), 0o644u16.to_be_bytes());
        assert_eq!(PermissionMode::try_from_bytes(&m.to_bytes()).unwrap(), m);
        assert_eq!(
            PermissionMode::try_from_bytes(&0o170644u16.to_be_bytes())
                .unwrap()
                .get(),
            0o0644
        );
        assert!(PermissionMode::try_from_bytes(&[0]).is_err());
    }

    #[test]
    fn metadata_owner_facets_default_none() {
        let m = Metadata::new();
        assert_eq!(m.owner_uid(), None);
        assert_eq!(m.owner_gid(), None);
        assert_eq!(m.owner_user_name(), None);
        assert_eq!(m.owner_group_name(), None);
        assert_eq!(m.owner_user_sid(), None);
        assert_eq!(m.owner_group_sid(), None);
        assert_eq!(m.permission_mode(), None);
    }

    #[test]
    fn owner_id_facets_round_trip_via_entry() {
        use crate::entry::{OwnerGid, OwnerUid};
        use crate::{Archive, EntryBuilder, WriteOptions};
        let mut buf = Vec::new();
        {
            let mut archive = Archive::write_header(&mut buf).unwrap();
            let mut b = EntryBuilder::new_file("f".into(), WriteOptions::store()).unwrap();
            b.owner_uid(OwnerUid::from(1000));
            b.owner_gid(OwnerGid::from(2000));
            let entry = b.build().unwrap();
            archive.add_entry(entry).unwrap();
            archive.finalize().unwrap();
        }
        let mut archive = Archive::read_header(&buf[..]).unwrap();
        let entry = archive.entries().skip_solid().next().unwrap().unwrap();
        let m = entry.metadata();
        assert_eq!(m.owner_uid().map(|v| v.get()), Some(1000));
        assert_eq!(m.owner_gid().map(|v| v.get()), Some(2000));
    }

    #[test]
    fn owner_name_facets_round_trip_via_entry() {
        use crate::entry::{OwnerGroupName, OwnerUserName};
        use crate::{Archive, EntryBuilder, WriteOptions};
        let mut buf = Vec::new();
        {
            let mut archive = Archive::write_header(&mut buf).unwrap();
            let mut b = EntryBuilder::new_file("f".into(), WriteOptions::store()).unwrap();
            b.owner_user_name(OwnerUserName::new("alice").unwrap());
            b.owner_group_name(OwnerGroupName::new("").unwrap());
            let entry = b.build().unwrap();
            archive.add_entry(entry).unwrap();
            archive.finalize().unwrap();
        }
        let mut archive = Archive::read_header(&buf[..]).unwrap();
        let entry = archive.entries().skip_solid().next().unwrap().unwrap();
        let m = entry.metadata();
        assert_eq!(m.owner_user_name().map(|v| v.as_str()), Some("alice"));
        assert_eq!(m.owner_group_name().map(|v| v.as_str()), Some("")); // recorded empty name, NOT absent
    }

    #[test]
    fn owner_sid_facets_round_trip_via_entry() {
        use crate::entry::{OwnerGroupSid, OwnerUserSid};
        use crate::{Archive, EntryBuilder, WriteOptions};
        let mut buf = Vec::new();
        {
            let mut archive = Archive::write_header(&mut buf).unwrap();
            let mut b = EntryBuilder::new_file("f".into(), WriteOptions::store()).unwrap();
            b.owner_user_sid(OwnerUserSid::new("S-1-5-21-1-2-3-1001").unwrap());
            b.owner_group_sid(OwnerGroupSid::new("S-1-5-32-544").unwrap());
            let entry = b.build().unwrap();
            archive.add_entry(entry).unwrap();
            archive.finalize().unwrap();
        }
        let mut archive = Archive::read_header(&buf[..]).unwrap();
        let entry = archive.entries().skip_solid().next().unwrap().unwrap();
        let m = entry.metadata();
        assert_eq!(
            m.owner_user_sid().map(|v| v.as_str()),
            Some("S-1-5-21-1-2-3-1001")
        );
        assert_eq!(
            m.owner_group_sid().map(|v| v.as_str()),
            Some("S-1-5-32-544")
        );
    }

    #[test]
    fn fosi_length_prefixed_round_trip_and_empty() {
        use crate::entry::{OwnerGroupSid, OwnerUserSid};
        use crate::{Archive, EntryBuilder, WriteOptions};
        let mut buf = Vec::new();
        {
            let mut a = Archive::write_header(&mut buf).unwrap();
            let mut b = EntryBuilder::new_file("f".into(), WriteOptions::store()).unwrap();
            b.owner_user_sid(OwnerUserSid::new("S-1-5-21-1-2-3-1001").unwrap());
            b.owner_group_sid(OwnerGroupSid::new("").unwrap()); // empty -> [0] -> Some("")
            a.add_entry(b.build().unwrap()).unwrap();
            a.finalize().unwrap();
        }
        let mut a = Archive::read_header(&buf[..]).unwrap();
        let e = a.entries().skip_solid().next().unwrap().unwrap();
        assert_eq!(
            e.metadata().owner_user_sid().map(|v| v.as_str()),
            Some("S-1-5-21-1-2-3-1001")
        );
        assert_eq!(e.metadata().owner_group_sid().map(|v| v.as_str()), Some(""));
    }

    #[test]
    fn permission_mode_facet_round_trip_via_entry() {
        use crate::entry::PermissionMode;
        use crate::{Archive, EntryBuilder, WriteOptions};
        let mut buf = Vec::new();
        {
            let mut archive = Archive::write_header(&mut buf).unwrap();
            let mut b = EntryBuilder::new_file("f".into(), WriteOptions::store()).unwrap();
            b.permission_mode(PermissionMode::from(0o750));
            let entry = b.build().unwrap();
            archive.add_entry(entry).unwrap();
            archive.finalize().unwrap();
        }
        let mut archive = Archive::read_header(&buf[..]).unwrap();
        let entry = archive.entries().skip_solid().next().unwrap().unwrap();
        assert_eq!(
            entry.metadata().permission_mode().map(|v| v.get()),
            Some(0o750)
        );
    }

    #[test]
    fn link_target_type_roundtrip_unknown() {
        let ltp = LinkTargetType::Unknown;
        assert_eq!(
            Some(ltp),
            LinkTargetType::try_from_bytes(&ltp.to_bytes()).unwrap()
        );
    }

    #[test]
    fn link_target_type_roundtrip_file() {
        let ltp = LinkTargetType::File;
        assert_eq!(
            Some(ltp),
            LinkTargetType::try_from_bytes(&ltp.to_bytes()).unwrap()
        );
    }

    #[test]
    fn link_target_type_roundtrip_directory() {
        let ltp = LinkTargetType::Directory;
        assert_eq!(
            Some(ltp),
            LinkTargetType::try_from_bytes(&ltp.to_bytes()).unwrap()
        );
    }

    #[test]
    fn link_target_type_unknown_values_return_none() {
        assert_eq!(LinkTargetType::try_from_bytes(&[0x03]).unwrap(), None);
        assert_eq!(LinkTargetType::try_from_bytes(&[0xFF]).unwrap(), None);
    }

    #[test]
    fn link_target_type_empty_bytes() {
        assert!(LinkTargetType::try_from_bytes(&[]).is_err());
    }

    #[test]
    fn link_target_type_try_from_u8() {
        assert_eq!(
            LinkTargetType::try_from(0u8).unwrap(),
            LinkTargetType::Unknown
        );
        assert_eq!(LinkTargetType::try_from(1u8).unwrap(), LinkTargetType::File);
        assert_eq!(
            LinkTargetType::try_from(2u8).unwrap(),
            LinkTargetType::Directory
        );
        assert!(LinkTargetType::try_from(3u8).is_err());
    }

    #[test]
    fn link_target_type_trailing_bytes_ignored() {
        // read_exact reads only 1 byte; trailing bytes are silently ignored
        assert_eq!(
            LinkTargetType::try_from_bytes(&[0x01, 0xFF, 0xFF]).unwrap(),
            Some(LinkTargetType::File),
        );
    }

    #[allow(deprecated)]
    #[test]
    fn all_owner_facets_and_fprm_coexist_round_trip() {
        use crate::entry::{
            OwnerGid, OwnerGroupName, OwnerGroupSid, OwnerUid, OwnerUserName, OwnerUserSid,
            PermissionMode,
        };
        use crate::{Archive, EntryBuilder, WriteOptions};
        let mut buf = Vec::new();
        {
            let mut archive = Archive::write_header(&mut buf).unwrap();
            let mut b = EntryBuilder::new_file("f".into(), WriteOptions::store()).unwrap();
            // Legacy fPRM (Permission uses plain String uname/gname on this branch).
            b.permission(Permission::new(
                7,
                "legacy".to_string(),
                8,
                "grp".to_string(),
                0o600,
            ));
            // All 7 new owner facets.
            b.owner_uid(OwnerUid::from(1));
            b.owner_gid(OwnerGid::from(2));
            b.owner_user_name(OwnerUserName::new("u").unwrap());
            b.owner_group_name(OwnerGroupName::new("g").unwrap());
            b.owner_user_sid(OwnerUserSid::new("S-1-1").unwrap());
            b.owner_group_sid(OwnerGroupSid::new("S-1-2").unwrap());
            b.permission_mode(PermissionMode::from(0o644));
            let entry = b.build().unwrap();
            archive.add_entry(entry).unwrap();
            archive.finalize().unwrap();
        }
        let mut archive = Archive::read_header(&buf[..]).unwrap();
        let entry = archive.entries().skip_solid().next().unwrap().unwrap();
        let m = entry.metadata();
        // All 7 new facets survived.
        assert_eq!(m.owner_uid().map(|v| v.get()), Some(1));
        assert_eq!(m.owner_gid().map(|v| v.get()), Some(2));
        assert_eq!(m.owner_user_name().map(|v| v.as_str()), Some("u"));
        assert_eq!(m.owner_group_name().map(|v| v.as_str()), Some("g"));
        assert_eq!(m.owner_user_sid().map(|v| v.as_str()), Some("S-1-1"));
        assert_eq!(m.owner_group_sid().map(|v| v.as_str()), Some("S-1-2"));
        assert_eq!(m.permission_mode().map(|v| v.get()), Some(0o644));
        // Legacy fPRM still round-trips intact, independently of the new owner facets.
        let p = m
            .permission()
            .expect("fPRM permission must still be present");
        assert_eq!(p.uid(), 7);
        assert_eq!(p.uname(), "legacy");
        assert_eq!(p.gid(), 8);
        assert_eq!(p.gname(), "grp");
        assert_eq!(p.permissions(), 0o600);
    }

    #[test]
    fn fonm_trailing_bytes_after_length_are_ignored() {
        use crate::{Archive, ChunkType, EntryBuilder, RawChunk, WriteOptions};
        let mut buf = Vec::new();
        {
            let mut a = Archive::write_header(&mut buf).unwrap();
            let mut b = EntryBuilder::new_file("g".into(), WriteOptions::store()).unwrap();
            b.add_extra_chunk(RawChunk::from_data(
                ChunkType::fONm,
                vec![3, b'a', b'b', b'c', 0xFF],
            ));
            a.add_entry(b.build().unwrap()).unwrap();
            a.finalize().unwrap();
        }
        let mut a = Archive::read_header(&buf[..]).unwrap();
        let e = a.entries().skip_solid().next().unwrap().unwrap();
        assert_eq!(
            e.metadata().owner_user_name().map(|v| v.as_str()),
            Some("abc")
        );
    }
}