Debian Codegraph @

src/ar/mod.rs

raw symbols SCIP
1 //! A library for encoding/decoding Unix archive files.
2 //!
3 //! This library provides utilities necessary to manage [Unix archive
4 //! files](https://en.wikipedia.org/wiki/Ar_(Unix)) (as generated by the
5 //! standard `ar` command line utility) abstracted over a reader or writer.
6 //! This library provides a streaming interface that avoids having to ever load
7 //! a full archive entry into memory.
8 //!
9 //! The API of this crate is meant to be similar to that of the
10 //! [`tar`](https://crates.io/crates/tar) crate.
11 //!
12
13 mod error;
14 mod write;
15
16 use crate::{bail, ensure, err};
17 pub use write::GnuBuilder;
18
19 // ========================================================================= //
20
21 const GLOBAL_HEADER_LEN: usize = 8;
22 const GLOBAL_HEADER: &[u8; GLOBAL_HEADER_LEN] = b"!<arch>\n";
23
24 const GNU_NAME_TABLE_ID: &str = "//";
25 const GNU_SYMBOL_LOOKUP_TABLE_ID: &str = "/";
26
27 // ========================================================================= //
28
29 /// Representation of an archive entry header.
30 #[derive(Clone, Debug, Eq, PartialEq)]
31 pub struct Header {
32 identifier: Vec<u8>,
33 mtime: u64,
34 uid: u32,
35 gid: u32,
36 mode: u32,
37 size: u64,
38 }
39
40 impl Header {
41 /// Creates a header with the given file identifier and size, and all
42 /// other fields set to zero.
43 pub fn new(identifier: Vec<u8>, size: u64) -> Header {
44 Header {
45 identifier,
46 mtime: 0,
47 uid: 0,
48 gid: 0,
49 mode: 0o644,
50 size,
51 }
52 }
53
54 /// Returns the file identifier.
55 pub fn identifier(&self) -> &[u8] {
56 &self.identifier
57 }
58
59 /// Sets the mode bits for this file.
60 pub fn set_mode(&mut self, mode: u32) {
61 self.mode = mode;
62 }
63
64 /// Returns the length of the file, in bytes.
65 pub fn size(&self) -> u64 {
66 self.size
67 }
68
69 /// Validates the header is somewhat sane against the specification.
70 pub fn validate(&self) -> std::io::Result<()> {
71 ensure!(
72 num_digits(self.mtime, 10) <= 12,
73 "MTime `{}` > 12 digits",
74 self.mtime
75 );
76 ensure!(
77 num_digits(self.uid, 10) <= 6,
78 "UID `{}` > 6 digits",
79 self.uid
80 );
81 ensure!(
82 num_digits(self.gid, 10) <= 6,
83 "GID `{}` > 6 digits",
84 self.gid
85 );
86 ensure!(
87 num_digits(self.mode, 8) <= 8,
88 "Mode `{:o}` > 8 octal digits",
89 self.mode
90 );
91 Ok(())
92 }
93 }
94
95 #[inline]
96 fn num_digits<N: Into<u64>>(val: N, radix: u64) -> u64 {
97 let mut val = val.into();
98 if val == 0 {
99 return 1;
100 }
101
102 let mut digits = 0;
103 while val != 0 {
104 val /= radix;
105 digits += 1;
106 }
107 digits
108 }