libpna 0.33.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
//! Metadata and permission types for archive entries.

use crate::{Duration, UnknownValueError};
use std::io::{self, Read};

/// 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(())
/// # }
/// ```
#[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>,
}

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,
        }
    }

    /// 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.
    #[inline]
    pub fn with_permission(mut self, permission: Option<Permission>) -> Self {
        self.permission = permission;
        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.
    #[inline]
    pub const fn permission(&self) -> Option<&Permission> {
        self.permission.as_ref()
    }

    /// 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.
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct Permission {
    uid: u64,
    uname: String,
    gid: u64,
    gname: String,
    permission: u16,
}

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
    ///
    /// ```
    /// use libpna::Permission;
    ///
    /// let perm = Permission::new(1000, "user".into(), 100, "group".into(), 0o755);
    /// ```
    #[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
    ///
    /// ```
    /// use libpna::Permission;
    ///
    /// let perm = Permission::new(1000, "user1".into(), 100, "group1".into(), 0o644);
    /// assert_eq!(perm.uid(), 1000);
    /// ```
    #[inline]
    pub const fn uid(&self) -> u64 {
        self.uid
    }

    /// Returns the user name associated with this permission.
    ///
    /// # Examples
    ///
    /// ```
    /// use libpna::Permission;
    ///
    /// let perm = Permission::new(1000, "user1".into(), 100, "group1".into(), 0o644);
    /// assert_eq!(perm.uname(), "user1");
    /// ```
    #[inline]
    pub fn uname(&self) -> &str {
        &self.uname
    }

    /// Returns the group ID associated with this permission.
    ///
    /// # Examples
    ///
    /// ```
    /// use libpna::Permission;
    ///
    /// let perm = Permission::new(1000, "user1".into(), 100, "group1".into(), 0o644);
    /// assert_eq!(perm.gid(), 100);
    /// ```
    #[inline]
    pub const fn gid(&self) -> u64 {
        self.gid
    }

    /// Returns the group name associated with this permission.
    ///
    /// # Examples
    ///
    /// ```
    /// use libpna::Permission;
    ///
    /// let perm = Permission::new(1000, "user1".into(), 100, "group1".into(), 0o644);
    /// assert_eq!(perm.gname(), "group1");
    /// ```
    #[inline]
    pub fn gname(&self) -> &str {
        &self.gname
    }

    /// Returns the permission bits associated with this permission.
    ///
    /// # Examples
    ///
    /// ```
    /// use libpna::Permission;
    ///
    /// let perm = Permission::new(1000, "user1".into(), 100, "group1".into(), 0o644);
    /// assert_eq!(perm.permissions(), 0o644);
    /// ```
    #[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,
        })
    }
}

/// 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;

    #[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 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),
        );
    }
}