Skip to main content

04_aa_archive_stream_roundtrip/
04_aa_archive_stream_roundtrip.rs

1mod common;
2
3use common::{artifact_dir, path_string};
4use compression::{
5    ArchiveFlags, ArchiveStream, ByteStream, FieldKey, Header, DEFAULT_FILE_MODE, OPEN_CREATE,
6    OPEN_READ_ONLY, OPEN_TRUNCATE, OPEN_WRITE_ONLY,
7};
8
9fn main() -> Result<(), Box<dyn std::error::Error>> {
10    let data = b"hello from apple archive".to_vec();
11    let artifact_dir = artifact_dir("aa-archive-stream");
12    let archive_path = artifact_dir.join("sample.aar");
13    let archive_path = path_string(&archive_path);
14
15    let mut header = Header::new()?;
16    let regular_file = u64::from(b'F');
17    let data_len = u64::try_from(data.len())?;
18    header.append_field_uint(FieldKey::TYP, regular_file)?;
19    header.append_field_string(FieldKey::PAT, "greeting.txt")?;
20    header.append_field_uint(FieldKey::SIZ, data_len)?;
21    header.append_field_blob(FieldKey::DAT, data_len)?;
22
23    let byte_stream = ByteStream::open_with_path(
24        &archive_path,
25        OPEN_WRITE_ONLY | OPEN_CREATE | OPEN_TRUNCATE,
26        DEFAULT_FILE_MODE,
27    )?;
28    let mut archive = ArchiveStream::encode_output(byte_stream, ArchiveFlags::empty(), 0)?;
29    archive.write_header(&header)?;
30    archive.write_blob(FieldKey::DAT, &data)?;
31    archive.close()?;
32
33    let byte_stream = ByteStream::open_with_path(&archive_path, OPEN_READ_ONLY, 0)?;
34    let mut archive = ArchiveStream::decode_input(byte_stream, ArchiveFlags::empty(), 0)?;
35    let header = archive.read_header()?.expect("archive entry");
36    assert_eq!(header.path()?.as_deref(), Some("greeting.txt"));
37    let blob = header.blob_with_key(FieldKey::DAT)?.expect("blob field");
38    let mut decoded = vec![0_u8; usize::try_from(blob.size)?];
39    archive.read_blob(FieldKey::DAT, &mut decoded)?;
40    assert_eq!(decoded, data);
41    assert!(archive.read_header()?.is_none());
42    archive.close()?;
43
44    println!("archive path={archive_path}");
45    println!("✅ AppleArchive round-trip OK");
46    Ok(())
47}