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
//! A library for encoding/decoding Unix archive files.
//!
//! This library provides utilities necessary to manage [Unix archive
//! files](https://en.wikipedia.org/wiki/Ar_(Unix)) (as generated by the
//! standard `ar` command line utility) abstracted over a reader or writer.
//! This library provides a streaming interface that avoids having to ever load
//! a full archive entry into memory.
//!
//! The API of this crate is meant to be similar to that of the
//! [`tar`](https://crates.io/crates/tar) crate.
//!
//! # Format variants
//!
//! Unix archive files come in several variants, of which three are the most
//! common:
//!
//! * The *common variant*, used for Debian package (`.deb`) files among other
//!   things, which only supports filenames up to 16 characters.
//! * The *BSD variant*, used by the `ar` utility on BSD systems (including Mac
//!   OS X), which is backwards-compatible with the common variant, but extends
//!   it to support longer filenames and filenames containing spaces.
//! * The *GNU variant*, used by the `ar` utility on GNU and many other systems
//!   (including Windows), which is similar to the common format, but which
//!   stores filenames in a slightly different, incompatible way, and has its
//!   own strategy for supporting long filenames.
//!
//! Currently, this crate supports reading all three of these variants, but
//! only supports writing the BSD/common variant.
//!
//! # Example usage
//!
//! Writing an archive:
//!
//! ```no_run
//! use ar::Builder;
//! use std::fs::File;
//! // Create a new archive that will be written to foo.a:
//! let mut builder = Builder::new(File::create("foo.a").unwrap());
//! // Add foo/bar.txt to the archive, under the name "bar.txt":
//! builder.append_path("foo/bar.txt").unwrap();
//! // Add foo/baz.txt to the archive, under the name "hello.txt":
//! let mut file = File::open("foo/baz.txt").unwrap();
//! builder.append_file("hello.txt", &mut file).unwrap();
//! ```
//!
//! Reading an archive:
//!
//! ```no_run
//! use ar::Archive;
//! use std::fs::File;
//! use std::io;
//! // Read an archive from the file foo.a:
//! let mut archive = Archive::new(File::open("foo.a").unwrap());
//! // Iterate over all entries in the archive:
//! while let Some(entry_result) = archive.next_entry() {
//!     let mut entry = entry_result.unwrap();
//!     // Create a new file with the same name as the archive entry:
//!     let mut file = File::create(entry.header().identifier()).unwrap();
//!     // The Entry object also acts as an io::Read, so we can easily copy the
//!     // contents of the archive entry into the file:
//!     io::copy(&mut entry, &mut file).unwrap();
//! }
//! ```

#![warn(missing_docs)]

use std::ffi::OsStr;
use std::fs::{File, Metadata};
use std::io::{self, Error, ErrorKind, Read, Result, Write};
use std::path::Path;
use std::str;

#[cfg(unix)]
use std::os::unix::fs::MetadataExt;

// ========================================================================= //

const GLOBAL_HEADER_LEN: usize = 8;
const GLOBAL_HEADER: &'static [u8; GLOBAL_HEADER_LEN] = b"!<arch>\n";

const GNU_NAME_TABLE_ID: &'static str = "//";

// ========================================================================= //

/// Variants of the Unix archive format.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Variant {
    /// Used by Debian package files; allows only short filenames.
    Common,
    /// Used by BSD `ar` (and OS X); backwards-compatible with common variant.
    BSD,
    /// Used by GNU `ar` (and Windows); incompatible with common variant.
    GNU,
}

// ========================================================================= //

/// Representation of an archive entry header.
pub struct Header {
    identifier: String,
    mtime: u64,
    uid: u32,
    gid: u32,
    mode: u32,
    size: u64,
}

impl Header {
    /// Creates a header with the given file identifier and size, and all
    /// other fields set to zero.
    pub fn new(identifier: String, size: u64) -> Header {
        Header {
            identifier: identifier,
            mtime: 0,
            uid: 0,
            gid: 0,
            mode: 0,
            size: size,
        }
    }

    /// Creates a header with the given file identifier and all other fields
    /// set from the given filesystem metadata.
    #[cfg(unix)]
    pub fn from_metadata(identifier: String, meta: &Metadata) -> Header {
        Header {
            identifier: identifier,
            mtime: meta.mtime() as u64,
            uid: meta.uid(),
            gid: meta.gid(),
            mode: meta.mode(),
            size: meta.len(),
        }
    }

    #[cfg(not(unix))]
    pub fn from_metadata(identifier: String, meta: &Metadata) -> Header {
        Header::new(identifier, meta.len())
    }

    /// Returns the file identifier.
    pub fn identifier(&self) -> &str { &self.identifier }

    /// Sets the file identifier.
    pub fn set_identifier(&mut self, identifier: String) {
        self.identifier = identifier;
    }

    /// Returns the last modification time in Unix time format.
    pub fn mtime(&self) -> u64 { self.mtime }

    /// Sets the last modification time in Unix time format.
    pub fn set_mtime(&mut self, mtime: u64) { self.mtime = mtime; }

    /// Returns the value of the owner's user ID field.
    pub fn uid(&self) -> u32 { self.uid }

    /// Sets the value of the owner's user ID field.
    pub fn set_uid(&mut self, uid: u32) { self.uid = uid; }

    /// Returns the value of the group's user ID field.
    pub fn gid(&self) -> u32 { self.gid }

    /// Returns the value of the group's user ID field.
    pub fn set_gid(&mut self, gid: u32) { self.gid = gid; }

    /// Returns the mode bits for this file.
    pub fn mode(&self) -> u32 { self.mode }

    /// Sets the mode bits for this file.
    pub fn set_mode(&mut self, mode: u32) { self.mode = mode; }

    /// Returns the length of the file, in bytes.
    pub fn size(&self) -> u64 { self.size }

    /// Sets the length of the file, in bytes.
    pub fn set_size(&mut self, size: u64) { self.size = size; }

    /// Parses the next header.  Returns `Ok(None)` if we are at EOF.
    fn read<R: Read>(reader: &mut R, variant: &mut Variant,
                     name_table: &mut Vec<u8>)
                     -> Result<Option<Header>> {
        let mut buffer = [0; 60];
        let bytes_read = try!(reader.read(&mut buffer));
        if bytes_read == 0 {
            return Ok(None);
        } else if bytes_read < buffer.len() {
            let msg = "Unexpected EOF in the middle of archive entry header";
            return Err(Error::new(ErrorKind::UnexpectedEof, msg));
        }
        let mut identifier = match str::from_utf8(&buffer[0..16]) {
            Ok(string) => string.trim_right().to_string(),
            Err(_) => {
                let msg = "Non-UTF8 bytes in entry identifier";
                return Err(Error::new(ErrorKind::InvalidData, msg));
            }
        };
        let mut size = try!(parse_number(&buffer[48..58], 10));
        if *variant != Variant::BSD && identifier.starts_with('/') {
            *variant = Variant::GNU;
            if identifier == GNU_NAME_TABLE_ID {
                *name_table = vec![0; size as usize];
                try!(reader.read_exact(name_table as &mut [u8]));
                return Ok(Some(Header::new(identifier, size)));
            }
            let start = try!(parse_number(&buffer[1..16], 10)) as usize;
            let end =
                match name_table[start..].iter().position(|&ch| ch == b'/') {
                    Some(len) => start + len,
                    None => name_table.len(),
                };
            identifier = match str::from_utf8(&name_table[start..end]) {
                Ok(string) => string.to_string(),
                Err(_) => {
                    let msg = "Non-UTF8 bytes in extended entry identifier";
                    return Err(Error::new(ErrorKind::InvalidData, msg));
                }
            };
        } else if *variant != Variant::BSD && identifier.ends_with('/') {
            *variant = Variant::GNU;
            identifier.pop();
        }
        let mtime = try!(parse_number(&buffer[16..28], 10));
        let uid = try!(parse_number(&buffer[28..34], 10)) as u32;
        let gid = try!(parse_number(&buffer[34..40], 10)) as u32;
        let mode = try!(parse_number(&buffer[40..48], 8)) as u32;
        if *variant != Variant::GNU && identifier.starts_with("#1/") {
            *variant = Variant::BSD;
            let padded_length = try!(parse_number(&buffer[3..16], 10));
            if size < padded_length {
                let msg = format!("Entry size ({}) smaller than extended \
                                   entry identifier length ({})",
                                  size,
                                  padded_length);
                return Err(Error::new(ErrorKind::InvalidData, msg));
            }
            size -= padded_length;
            let mut id_buffer = vec![0; padded_length as usize];
            let bytes_read = try!(reader.read(&mut id_buffer));
            if bytes_read < id_buffer.len() {
                let msg = "Unexpected EOF in the middle of extended entry \
                           identifier";
                return Err(Error::new(ErrorKind::UnexpectedEof, msg));
            }
            while id_buffer.last() == Some(&0) {
                id_buffer.pop();
            }
            identifier = match str::from_utf8(&id_buffer) {
                Ok(string) => string.to_string(),
                Err(_) => {
                    let msg = "Non-UTF8 bytes in extended entry identifier";
                    return Err(Error::new(ErrorKind::InvalidData, msg));
                }
            };
        }
        Ok(Some(Header {
            identifier: identifier,
            mtime: mtime,
            uid: uid,
            gid: gid,
            mode: mode,
            size: size,
        }))
    }

    fn write<W: Write>(&self, writer: &mut W) -> Result<()> {
        if self.identifier.len() > 16 || self.identifier.contains(' ') {
            let padding_length = (4 - self.identifier.len() % 4) % 4;
            let padded_length = self.identifier.len() + padding_length;
            try!(write!(writer,
                        "#1/{:<13}{:<12}{:<6}{:<6}{:<8o}{:<10}`\n{}",
                        padded_length,
                        self.mtime,
                        self.uid,
                        self.gid,
                        self.mode,
                        self.size + padded_length as u64,
                        self.identifier));
            writer.write_all(&vec![0; padding_length])
        } else {
            write!(writer,
                   "{:<16}{:<12}{:<6}{:<6}{:<8o}{:<10}`\n",
                   self.identifier,
                   self.mtime,
                   self.uid,
                   self.gid,
                   self.mode,
                   self.size)
        }
    }
}

fn parse_number(bytes: &[u8], radix: u32) -> Result<u64> {
    if let Ok(string) = str::from_utf8(bytes) {
        if let Ok(value) = u64::from_str_radix(string.trim_right(), radix) {
            return Ok(value);
        }
    }
    let msg = "Invalid numeric field in entry header";
    Err(Error::new(ErrorKind::InvalidData, msg))
}

// ========================================================================= //

/// A structure for reading archives.
pub struct Archive<R: Read> {
    reader: R,
    variant: Variant,
    name_table: Vec<u8>,
    started: bool,
    padding: bool,
    finished: bool,
}

impl<R: Read> Archive<R> {
    /// Create a new archive reader with the underlying reader object as the
    /// source of all data read.
    pub fn new(reader: R) -> Archive<R> {
        Archive {
            reader: reader,
            variant: Variant::Common,
            name_table: Vec::new(),
            started: false,
            padding: false,
            finished: false,
        }
    }

    /// Returns which format variant this archive appears to be so far.
    ///
    /// Note that this may not be accurate before the archive has been fully
    /// read (i.e. before the `next_entry()` method returns `None`).  In
    /// particular, a new `Archive` object that hasn't yet read any data at all
    /// will always return `Variant::Common`.
    pub fn variant(&self) -> Variant { self.variant }

    /// Unwrap this archive reader, returning the underlying reader object.
    pub fn into_inner(self) -> Result<R> { Ok(self.reader) }

    /// Reads the next entry from the archive, or returns None if there are no
    /// more.
    pub fn next_entry(&mut self) -> Option<Result<Entry<R>>> {
        loop {
            if self.finished {
                return None;
            }
            if !self.started {
                let mut buffer = [0; GLOBAL_HEADER_LEN];
                match self.reader.read_exact(&mut buffer) {
                    Ok(()) => {}
                    Err(error) => {
                        self.finished = true;
                        return Some(Err(error));
                    }
                }
                if &buffer != GLOBAL_HEADER {
                    self.finished = true;
                    let msg = "Not an archive file (invalid global header)";
                    return Some(Err(Error::new(ErrorKind::InvalidData, msg)));
                }
                self.started = true;
            }
            if self.padding {
                let mut buffer = [0; 1];
                match self.reader.read_exact(&mut buffer) {
                    Ok(()) => {}
                    Err(error) => {
                        self.finished = true;
                        return Some(Err(error));
                    }
                }
                if &buffer != b"\n" {
                    self.finished = true;
                    let msg = "Invalid padding byte";
                    return Some(Err(Error::new(ErrorKind::InvalidData, msg)));
                }
                self.padding = false;
            }
            match Header::read(&mut self.reader,
                               &mut self.variant,
                               &mut self.name_table) {
                Ok(Some(header)) => {
                    let size = header.size();
                    if size % 2 != 0 {
                        self.padding = true;
                    }
                    if self.variant == Variant::GNU &&
                       header.identifier() == GNU_NAME_TABLE_ID {
                        continue;
                    }
                    return Some(Ok(Entry {
                        header: header,
                        reader: self.reader.by_ref().take(size),
                    }));
                }
                Ok(None) => {
                    self.finished = true;
                    return None;
                }
                Err(error) => {
                    self.finished = true;
                    return Some(Err(error));
                }
            }
        }
    }
}

// ========================================================================= //

/// Representation of an archive entry.
///
/// Entry objects implement the `Read` trait, and can be used to extract the
/// data from this archive entry.
pub struct Entry<'a, R: 'a + Read> {
    header: Header,
    reader: io::Take<&'a mut R>,
}

impl<'a, R: 'a + Read> Entry<'a, R> {
    /// Returns the header for this archive entry.
    pub fn header(&self) -> &Header { &self.header }
}

impl<'a, R: 'a + Read> Read for Entry<'a, R> {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        self.reader.read(buf)
    }
}

impl<'a, R: 'a + Read> Drop for Entry<'a, R> {
    fn drop(&mut self) {
        if self.reader.limit() > 0 {
            // Consume the rest of the data in this entry.
            let _ = io::copy(&mut self.reader, &mut io::sink());
        }
    }
}

// ========================================================================= //

/// A structure for building archives.
///
/// This structure has methods for building up an archive from scratch into any
/// arbitrary writer.
pub struct Builder<W: Write> {
    writer: W,
    started: bool,
}

impl<W: Write> Builder<W> {
    /// Create a new archive builder with the underlying writer object as the
    /// destination of all data written.
    pub fn new(writer: W) -> Builder<W> {
        Builder {
            writer: writer,
            started: false,
        }
    }

    /// Unwrap this archive builder, returning the underlying writer object.
    pub fn into_inner(self) -> Result<W> { Ok(self.writer) }

    /// Adds a new entry to this archive.
    pub fn append<R: Read>(&mut self, header: &Header, mut data: R)
                           -> Result<()> {
        if !self.started {
            try!(self.writer.write_all(GLOBAL_HEADER));
            self.started = true;
        }
        try!(header.write(&mut self.writer));
        let actual_size = try!(io::copy(&mut data, &mut self.writer));
        if actual_size != header.size() {
            let msg = format!("Wrong file size (header.size() = {}, actual \
                               size was {})",
                              header.size(),
                              actual_size);
            return Err(Error::new(ErrorKind::InvalidData, msg));
        }
        if actual_size % 2 != 0 {
            try!(self.writer.write_all(&['\n' as u8]));
        }
        Ok(())
    }

    /// Adds a file on the local filesystem to this archive, using the file
    /// name as its identifier.
    pub fn append_path<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
        let name: &OsStr = try!(path.as_ref().file_name().ok_or_else(|| {
            let msg = "Given path doesn't have a file name";
            Error::new(ErrorKind::InvalidInput, msg)
        }));
        let name: &str = try!(name.to_str().ok_or_else(|| {
            let msg = "Given path has a non-UTF8 file name";
            Error::new(ErrorKind::InvalidData, msg)
        }));
        self.append_file(name, &mut try!(File::open(&path)))
    }

    /// Adds a file to this archive, with the given name as its identifier.
    pub fn append_file(&mut self, name: &str, file: &mut File) -> Result<()> {
        let metadata = try!(file.metadata());
        let header = Header::from_metadata(name.to_string(), &metadata);
        self.append(&header, file)
    }
}

// ========================================================================= //

#[cfg(test)]
mod tests {
    use std::io::Read;
    use std::str;
    use super::{Archive, Builder, Header, Variant};

    #[test]
    fn build_common_archive() {
        let mut builder = Builder::new(Vec::new());
        let mut header1 = Header::new("foo.txt".to_string(), 7);
        header1.set_mtime(1487552916);
        header1.set_uid(501);
        header1.set_gid(20);
        header1.set_mode(0o100644);
        builder.append(&header1, "foobar\n".as_bytes()).unwrap();
        let header2 = Header::new("baz.txt".to_string(), 4);
        builder.append(&header2, "baz\n".as_bytes()).unwrap();
        let actual = builder.into_inner().unwrap();
        let expected = "\
        !<arch>\n\
        foo.txt         1487552916  501   20    100644  7         `\n\
        foobar\n\n\
        baz.txt         0           0     0     0       4         `\n\
        baz\n";
        assert_eq!(str::from_utf8(&actual).unwrap(), expected);
    }

    #[test]
    fn build_bsd_archive_with_long_filenames() {
        let mut builder = Builder::new(Vec::new());
        let mut header1 = Header::new("short".to_string(), 1);
        header1.set_identifier("this_is_a_very_long_filename.txt".to_string());
        header1.set_mtime(1487552916);
        header1.set_uid(501);
        header1.set_gid(20);
        header1.set_mode(0o100644);
        header1.set_size(7);
        builder.append(&header1, "foobar\n".as_bytes()).unwrap();
        let header2 = Header::new("and_this_is_another_very_long_filename.txt"
                                      .to_string(),
                                  4);
        builder.append(&header2, "baz\n".as_bytes()).unwrap();
        let actual = builder.into_inner().unwrap();
        let expected = "\
        !<arch>\n\
        #1/32           1487552916  501   20    100644  39        `\n\
        this_is_a_very_long_filename.txtfoobar\n\n\
        #1/44           0           0     0     0       48        `\n\
        and_this_is_another_very_long_filename.txt\x00\x00baz\n";
        assert_eq!(str::from_utf8(&actual).unwrap(), expected);
    }

    #[test]
    fn build_bsd_archive_with_space_in_filename() {
        let mut builder = Builder::new(Vec::new());
        let header = Header::new("foo bar".to_string(), 4);
        builder.append(&header, "baz\n".as_bytes()).unwrap();
        let actual = builder.into_inner().unwrap();
        let expected = "\
        !<arch>\n\
        #1/8            0           0     0     0       12        `\n\
        foo bar\x00baz\n";
        assert_eq!(str::from_utf8(&actual).unwrap(), expected);
    }

    #[test]
    fn read_common_archive() {
        let input = "\
        !<arch>\n\
        foo.txt         1487552916  501   20    100644  7         `\n\
        foobar\n\n\
        bar.awesome.txt 1487552919  501   20    100644  22        `\n\
        This file is awesome!\n\
        baz.txt         1487552349  42    12345 100664  4         `\n\
        baz\n";
        let mut archive = Archive::new(input.as_bytes());
        {
            // Parse the first entry and check the header values.
            let mut entry = archive.next_entry().unwrap().unwrap();
            assert_eq!(entry.header().identifier(), "foo.txt");
            assert_eq!(entry.header().mtime(), 1487552916);
            assert_eq!(entry.header().uid(), 501);
            assert_eq!(entry.header().gid(), 20);
            assert_eq!(entry.header().mode(), 0o100644);
            assert_eq!(entry.header().size(), 7);
            // Read the first few bytes of the entry data and make sure they're
            // correct.
            let mut buffer = [0; 4];
            entry.read_exact(&mut buffer).unwrap();
            assert_eq!(&buffer, "foob".as_bytes());
            // Dropping the Entry object should automatically consume the rest
            // of the entry data so that the archive reader is ready to parse
            // the next entry.
        }
        {
            // Parse the second entry and check a couple header values.
            let mut entry = archive.next_entry().unwrap().unwrap();
            assert_eq!(entry.header().identifier(), "bar.awesome.txt");
            assert_eq!(entry.header().size(), 22);
            // Read in all the entry data.
            let mut buffer = Vec::new();
            entry.read_to_end(&mut buffer).unwrap();
            assert_eq!(&buffer as &[u8], "This file is awesome!\n".as_bytes());
        }
        {
            // Parse the third entry and check a couple header values.
            let entry = archive.next_entry().unwrap().unwrap();
            assert_eq!(entry.header().identifier(), "baz.txt");
            assert_eq!(entry.header().size(), 4);
        }
        assert_eq!(archive.variant(), Variant::Common);
    }

    #[test]
    fn read_bsd_archive_with_long_filenames() {
        let input = "\
        !<arch>\n\
        #1/32           1487552916  501   20    100644  39        `\n\
        this_is_a_very_long_filename.txtfoobar\n\n\
        #1/44           0           0     0     0       48        `\n\
        and_this_is_another_very_long_filename.txt\x00\x00baz\n";
        let mut archive = Archive::new(input.as_bytes());
        {
            // Parse the first entry and check the header values.
            let mut entry = archive.next_entry().unwrap().unwrap();
            assert_eq!(entry.header().identifier(),
                       "this_is_a_very_long_filename.txt");
            assert_eq!(entry.header().mtime(), 1487552916);
            assert_eq!(entry.header().uid(), 501);
            assert_eq!(entry.header().gid(), 20);
            assert_eq!(entry.header().mode(), 0o100644);
            // We should get the size of the actual file, not including the
            // filename, even though this is not the value that's in the size
            // field in the input.
            assert_eq!(entry.header().size(), 7);
            // Read in the entry data; we should get only the payload and not
            // the filename.
            let mut buffer = Vec::new();
            entry.read_to_end(&mut buffer).unwrap();
            assert_eq!(&buffer as &[u8], "foobar\n".as_bytes());
        }
        {
            // Parse the second entry and check a couple header values.
            let mut entry = archive.next_entry().unwrap().unwrap();
            assert_eq!(entry.header().identifier(),
                       "and_this_is_another_very_long_filename.txt");
            assert_eq!(entry.header().size(), 4);
            // Read in the entry data; we should get only the payload and not
            // the filename or the padding bytes.
            let mut buffer = Vec::new();
            entry.read_to_end(&mut buffer).unwrap();
            assert_eq!(&buffer as &[u8], "baz\n".as_bytes());
        }
        assert_eq!(archive.variant(), Variant::BSD);
    }

    #[test]
    fn read_bsd_archive_with_space_in_filename() {
        let input = "\
        !<arch>\n\
        #1/8            0           0     0     0       12        `\n\
        foo bar\x00baz\n";
        let mut archive = Archive::new(input.as_bytes());
        {
            let mut entry = archive.next_entry().unwrap().unwrap();
            assert_eq!(entry.header().identifier(), "foo bar");
            assert_eq!(entry.header().size(), 4);
            let mut buffer = Vec::new();
            entry.read_to_end(&mut buffer).unwrap();
            assert_eq!(&buffer as &[u8], "baz\n".as_bytes());
        }
        assert_eq!(archive.variant(), Variant::BSD);
    }

    #[test]
    fn read_gnu_archive() {
        let input = "\
        !<arch>\n\
        foo.txt/        1487552916  501   20    100644  7         `\n\
        foobar\n\n\
        bar.awesome.txt/1487552919  501   20    100644  22        `\n\
        This file is awesome!\n\
        baz.txt/        1487552349  42    12345 100664  4         `\n\
        baz\n";
        let mut archive = Archive::new(input.as_bytes());
        {
            let entry = archive.next_entry().unwrap().unwrap();
            assert_eq!(entry.header().identifier(), "foo.txt");
            assert_eq!(entry.header().size(), 7);
        }
        {
            let entry = archive.next_entry().unwrap().unwrap();
            assert_eq!(entry.header().identifier(), "bar.awesome.txt");
            assert_eq!(entry.header().size(), 22);
        }
        {
            let entry = archive.next_entry().unwrap().unwrap();
            assert_eq!(entry.header().identifier(), "baz.txt");
            assert_eq!(entry.header().size(), 4);
        }
        assert_eq!(archive.variant(), Variant::GNU);
    }

    #[test]
    fn read_gnu_archive_with_long_filenames() {
        let input = "\
        !<arch>\n\
        //                                              78        `\n\
        this_is_a_very_long_filename.txt/\n\
        and_this_is_another_very_long_filename.txt/\n\
        /0              1487552916  501   20    100644  7         `\n\
        foobar\n\n\
        /34             0           0     0     0       4         `\n\
        baz\n";
        let mut archive = Archive::new(input.as_bytes());
        {
            let mut entry = archive.next_entry().unwrap().unwrap();
            assert_eq!(entry.header().identifier(),
                       "this_is_a_very_long_filename.txt");
            assert_eq!(entry.header().mtime(), 1487552916);
            assert_eq!(entry.header().uid(), 501);
            assert_eq!(entry.header().gid(), 20);
            assert_eq!(entry.header().mode(), 0o100644);
            assert_eq!(entry.header().size(), 7);
            let mut buffer = Vec::new();
            entry.read_to_end(&mut buffer).unwrap();
            assert_eq!(&buffer as &[u8], "foobar\n".as_bytes());
        }
        {
            let mut entry = archive.next_entry().unwrap().unwrap();
            assert_eq!(entry.header().identifier(),
                       "and_this_is_another_very_long_filename.txt");
            assert_eq!(entry.header().size(), 4);
            let mut buffer = Vec::new();
            entry.read_to_end(&mut buffer).unwrap();
            assert_eq!(&buffer as &[u8], "baz\n".as_bytes());
        }
        assert_eq!(archive.variant(), Variant::GNU);
    }

    #[test]
    fn read_gnu_archive_with_space_in_filename() {
        let input = "\
        !<arch>\n\
        foo bar/        0           0     0     0       4         `\n\
        baz\n";
        let mut archive = Archive::new(input.as_bytes());
        {
            let mut entry = archive.next_entry().unwrap().unwrap();
            assert_eq!(entry.header().identifier(), "foo bar");
            assert_eq!(entry.header().size(), 4);
            let mut buffer = Vec::new();
            entry.read_to_end(&mut buffer).unwrap();
            assert_eq!(&buffer as &[u8], "baz\n".as_bytes());
        }
        assert_eq!(archive.variant(), Variant::GNU);
    }
}

// ========================================================================= //