libpna 0.38.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
//! Chunk type codes and validation for PNA archive chunks.

use std::{
    error::Error,
    fmt::{self, Debug, Display, Formatter},
    io,
};

/// [`ChunkType`] validation error.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub enum ChunkTypeError {
    /// Value contains a non-ASCII-alphabetic byte.
    NonAsciiAlphabetic,
    /// The second byte is not lowercase.
    NonPrivateChunkType,
    /// The third byte is not uppercase.
    Reserved,
}

impl Display for ChunkTypeError {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        Display::fmt(
            match self {
                Self::NonAsciiAlphabetic => "all characters must be ASCII alphabetic",
                Self::NonPrivateChunkType => "the second character must be lowercase",
                Self::Reserved => "the third character must be uppercase",
            },
            f,
        )
    }
}

impl Error for ChunkTypeError {}

impl From<ChunkTypeError> for io::Error {
    #[inline]
    fn from(e: ChunkTypeError) -> Self {
        io::Error::new(io::ErrorKind::InvalidData, e)
    }
}

/// A 4-byte chunk type code.
///
/// PNA uses a chunk-based format inspired by PNG. Each chunk has a 4-character
/// type code that determines how the chunk should be interpreted.
///
/// # Chunk Type Naming Convention
///
/// The case of each letter in the chunk type encodes important properties:
///
/// | Position | Uppercase | Lowercase |
/// |----------|-----------|-----------|
/// | 1st | Critical (must understand) | Ancillary (can ignore) |
/// | 2nd | Public (standardized) | Private (application-specific) |
/// | 3rd | Reserved (must be uppercase) | - |
/// | 4th | Unsafe to copy | Safe to copy if unknown |
///
/// # Critical Chunks
///
/// These chunks are essential for reading the archive structure:
///
/// - **Archive structure**: [`AHED`](Self::AHED) (header), [`AEND`](Self::AEND) (end),
///   [`ANXT`](Self::ANXT) (next part)
/// - **Entry structure**: [`FHED`](Self::FHED) (header), [`FDAT`](Self::FDAT) (data),
///   [`FEND`](Self::FEND) (end)
/// - **Solid mode**: [`SHED`](Self::SHED) (header), [`SDAT`](Self::SDAT) (data),
///   [`SEND`](Self::SEND) (end)
/// - **Encryption**: [`PHSF`](Self::PHSF) (password hash string format)
///
/// # Ancillary Chunks
///
/// These chunks contain optional metadata that can be safely ignored:
///
/// - **Timestamps**: [`cTIM`](Self::cTIM), [`mTIM`](Self::mTIM), [`aTIM`](Self::aTIM)
///   (seconds), [`cTNS`](Self::cTNS), [`mTNS`](Self::mTNS), [`aTNS`](Self::aTNS) (nanoseconds)
/// - **File info**: [`fSIZ`](Self::fSIZ) (size), [`fPRM`](Self::fPRM) (permissions)
/// - **Link info**: [`fLTP`](Self::fLTP) (link target type)
/// - **Extended attributes**: [`xATR`](Self::xATR)
///
/// # Creating Private Chunks
///
/// Use [`ChunkType::private`] to create application-specific chunk types:
///
/// ```rust
/// use libpna::ChunkType;
///
/// // Private chunk type must have lowercase second letter
/// let my_chunk = ChunkType::private(*b"myTy").unwrap();
/// assert!(my_chunk.is_private());
/// ```
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct ChunkType([u8; 4]);

impl ChunkType {
    // -- Critical chunks --
    /// Archive header.
    pub const AHED: ChunkType = ChunkType(*b"AHED");
    /// Archive end marker.
    pub const AEND: ChunkType = ChunkType(*b"AEND");
    /// Archive next part marker.
    pub const ANXT: ChunkType = ChunkType(*b"ANXT");
    /// Entry header.
    pub const FHED: ChunkType = ChunkType(*b"FHED");
    /// Password hash string format.
    pub const PHSF: ChunkType = ChunkType(*b"PHSF");
    /// Entry data stream.
    pub const FDAT: ChunkType = ChunkType(*b"FDAT");
    /// Entry data stream end marker.
    pub const FEND: ChunkType = ChunkType(*b"FEND");
    /// Solid mode data header.
    pub const SHED: ChunkType = ChunkType(*b"SHED");
    /// Solid mode data stream.
    pub const SDAT: ChunkType = ChunkType(*b"SDAT");
    /// Solid mode data stream end marker.
    pub const SEND: ChunkType = ChunkType(*b"SEND");

    // -- Ancillary chunks --
    /// Raw file size.
    #[allow(non_upper_case_globals)]
    pub const fSIZ: ChunkType = ChunkType(*b"fSIZ");
    /// Creation datetime.
    #[allow(non_upper_case_globals)]
    pub const cTIM: ChunkType = ChunkType(*b"cTIM");
    /// Last modified datetime.
    #[allow(non_upper_case_globals)]
    pub const mTIM: ChunkType = ChunkType(*b"mTIM");
    /// Last accessed datetime.
    #[allow(non_upper_case_globals)]
    pub const aTIM: ChunkType = ChunkType(*b"aTIM");
    /// Nanoseconds for creation datetime.
    #[allow(non_upper_case_globals)]
    pub const cTNS: ChunkType = ChunkType(*b"cTNS");
    /// Nanoseconds for last modified datetime.
    #[allow(non_upper_case_globals)]
    pub const mTNS: ChunkType = ChunkType(*b"mTNS");
    /// Nanoseconds for last accessed datetime.
    #[allow(non_upper_case_globals)]
    pub const aTNS: ChunkType = ChunkType(*b"aTNS");
    /// Entry permissions.
    #[allow(non_upper_case_globals)]
    #[deprecated(
        since = "0.34.0",
        note = "the fPRM chunk is superseded by the owner facet chunks fUId/fGId/fONm/fGNm/fOSi/fGSi/fMOd"
    )]
    pub const fPRM: ChunkType = ChunkType(*b"fPRM");
    /// Extended attribute.
    #[allow(non_upper_case_globals)]
    pub const xATR: ChunkType = ChunkType(*b"xATR");
    /// Link target type.
    #[allow(non_upper_case_globals)]
    pub const fLTP: ChunkType = ChunkType(*b"fLTP");
    /// Owner user id.
    #[allow(non_upper_case_globals)]
    pub const fUId: ChunkType = ChunkType(*b"fUId");
    /// Owner group id.
    #[allow(non_upper_case_globals)]
    pub const fGId: ChunkType = ChunkType(*b"fGId");
    /// Owner user name.
    #[allow(non_upper_case_globals)]
    pub const fONm: ChunkType = ChunkType(*b"fONm");
    /// Owner group name.
    #[allow(non_upper_case_globals)]
    pub const fGNm: ChunkType = ChunkType(*b"fGNm");
    /// Owner user SID.
    #[allow(non_upper_case_globals)]
    pub const fOSi: ChunkType = ChunkType(*b"fOSi");
    /// Owner group SID.
    #[allow(non_upper_case_globals)]
    pub const fGSi: ChunkType = ChunkType(*b"fGSi");
    /// POSIX permission mode.
    #[allow(non_upper_case_globals)]
    pub const fMOd: ChunkType = ChunkType(*b"fMOd");

    /// Returns the length of the chunk type code.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use libpna::ChunkType;
    ///
    /// let chunk_type = ChunkType::AHED;
    ///
    /// assert_eq!(chunk_type.len(), 4);
    /// ```
    #[allow(clippy::len_without_is_empty)]
    #[inline]
    pub const fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns the raw 4-byte chunk type code.
    #[inline]
    pub(crate) const fn as_bytes(&self) -> &[u8; 4] {
        &self.0
    }

    /// Creates a [`ChunkType`] from raw bytes, validating that all bytes are ASCII alphabetic.
    ///
    /// # Errors
    ///
    /// Returns [`ChunkTypeError::NonAsciiAlphabetic`] if any byte is not in `a..=z` or `A..=Z`.
    #[inline]
    pub(crate) const fn new(ty: [u8; 4]) -> Result<Self, ChunkTypeError> {
        // NOTE: use a while statement for const context.
        let mut idx = 0;
        while idx < ty.len() {
            if !ty[idx].is_ascii_alphabetic() {
                return Err(ChunkTypeError::NonAsciiAlphabetic);
            }
            idx += 1;
        }
        Ok(Self(ty))
    }

    /// Creates a private [`ChunkType`].
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Any byte is not an ASCII alphabetic character.
    /// - The second byte is not lowercase.
    /// - The third byte is not uppercase.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use libpna::{ChunkType, ChunkTypeError};
    /// assert!(ChunkType::private(*b"myTy").is_ok());
    /// assert_eq!(
    ///     ChunkType::private(*b"zeR\0").unwrap_err(),
    ///     ChunkTypeError::NonAsciiAlphabetic
    /// );
    /// assert_eq!(
    ///     ChunkType::private(*b"pRIv").unwrap_err(),
    ///     ChunkTypeError::NonPrivateChunkType
    /// );
    /// assert_eq!(
    ///     ChunkType::private(*b"rese").unwrap_err(),
    ///     ChunkTypeError::Reserved
    /// );
    /// ```
    #[inline]
    pub const fn private(ty: [u8; 4]) -> Result<Self, ChunkTypeError> {
        // NOTE: use a while statement for const context.
        let mut idx = 0;
        while idx < ty.len() {
            if !ty[idx].is_ascii_alphabetic() {
                return Err(ChunkTypeError::NonAsciiAlphabetic);
            }
            idx += 1;
        }
        if !ty[1].is_ascii_lowercase() {
            return Err(ChunkTypeError::NonPrivateChunkType);
        }
        if !ty[2].is_ascii_uppercase() {
            return Err(ChunkTypeError::Reserved);
        }
        Ok(Self(ty))
    }

    /// Creates a custom [`ChunkType`] without validation.
    ///
    /// # Display behavior
    /// If bytes are invalid UTF-8, they are rendered as lowercase hex bytes.
    /// ```rust
    /// # use libpna::ChunkType;
    ///
    /// let custom_chunk_type = unsafe { ChunkType::from_unchecked([0xe3, 0x81, 0x82, 0xe3]) };
    /// assert_eq!(format!("{}", custom_chunk_type), "[e3, 81, 82, e3]");
    /// ```
    ///
    /// # Safety
    /// Callers must ensure the value consists only of ASCII alphabetic
    /// characters ('a'..'z' and 'A'..'Z').
    /// ```rust
    /// # use libpna::ChunkType;
    ///
    /// let custom_chunk_type = unsafe { ChunkType::from_unchecked(*b"myTy") };
    /// format!("{}", custom_chunk_type);
    /// ```
    #[inline]
    pub const unsafe fn from_unchecked(ty: [u8; 4]) -> Self {
        Self(ty)
    }

    // -- Chunk type determination --

    /// Returns `true` if the chunk is critical.
    #[inline]
    pub const fn is_critical(&self) -> bool {
        self.0[0] & 32 == 0
    }

    /// Returns `true` if the chunk is private.
    #[inline]
    pub const fn is_private(&self) -> bool {
        self.0[1] & 32 != 0
    }

    /// Returns `true` if the reserved bit of the chunk name is set.
    ///
    /// If it is set, the chunk name is invalid.
    #[inline]
    pub const fn is_set_reserved(&self) -> bool {
        self.0[2] & 32 != 0
    }

    /// Returns `true` if the chunk is safe to copy if unknown.
    #[inline]
    pub const fn is_safe_to_copy(&self) -> bool {
        self.0[3] & 32 != 0
    }

    /// Returns `true` if consecutive chunks of this type form a single
    /// datastream, making their boundaries arbitrary and re-chunkable.
    #[inline]
    pub(crate) fn is_stream(&self) -> bool {
        *self == Self::FDAT || *self == Self::SDAT
    }
}

impl Debug for ChunkType {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        struct DebugType([u8; 4]);

        impl Debug for DebugType {
            #[inline]
            fn fmt(&self, f: &mut Formatter) -> fmt::Result {
                for &c in &self.0[..] {
                    write!(f, "{}", char::from(c).escape_debug())?;
                }
                Ok(())
            }
        }

        f.debug_struct("ChunkType")
            .field("type", &DebugType(self.0))
            .field("critical", &self.is_critical())
            .field("private", &self.is_private())
            .field("reserved", &self.is_set_reserved())
            .field("safe_to_copy", &self.is_safe_to_copy())
            .finish()
    }
}

impl Display for ChunkType {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match std::str::from_utf8(&self.0) {
            Ok(s) => Display::fmt(s, f),
            Err(_) => write!(f, "{:02x?}", self.0),
        }
    }
}

#[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 to_string() {
        assert_eq!("AHED", ChunkType::AHED.to_string());
    }

    #[test]
    fn is_critical() {
        assert!(ChunkType::AHED.is_critical());
        assert!(!ChunkType::cTIM.is_critical());
    }

    #[test]
    fn is_private() {
        assert!(!ChunkType::AHED.is_private());
        assert!(ChunkType::private(*b"myTy").unwrap().is_private());
    }

    #[test]
    fn is_set_reserved() {
        assert!(!ChunkType::AHED.is_set_reserved());
    }

    #[test]
    fn is_safe_to_copy() {
        assert!(!ChunkType::AHED.is_safe_to_copy());
    }

    #[test]
    fn new_rejects_non_ascii() {
        assert_eq!(
            ChunkType::new(*b"AB\x00D"),
            Err(ChunkTypeError::NonAsciiAlphabetic)
        );
        assert_eq!(
            ChunkType::new(*b"AB1D"),
            Err(ChunkTypeError::NonAsciiAlphabetic)
        );
    }

    #[test]
    fn new_accepts_valid() {
        assert!(ChunkType::new(*b"AHED").is_ok());
        assert!(ChunkType::new(*b"myTy").is_ok());
    }
}