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
//! Implements the basic reader/writer functionality for HFF.
#![warn(missing_docs)]

// Reexport needed types.
#[cfg(feature = "compression")]
pub use hff_core::read::decompress;

// Pull in core if special behavior is needed.
pub use hff_core;

// Pull in common needs.  Aka: prelude.
pub use hff_core::{
    read::{ChunkView, Hff, TableView},
    utilities,
    write::{chunk, hff, table, ChunkDesc, DataSource, HffDesc, TableBuilder},
    ByteOrder, ChunkCache, ContentInfo, Ecc, Error, IdType, Result, Version, BE, LE, NE, OP,
};

// Helper traits which provide blanket implementations over the
// required trait combinations.

mod write_seek;
pub use write_seek::WriteSeek;

mod read_seek;
pub use read_seek::ReadSeek;

/// Create a new builder instance.
pub fn build<'a>(
    tables: impl IntoIterator<Item = hff_core::write::TableBuilder<'a>>,
) -> Result<hff_core::write::HffDesc<'a>> {
    Ok(hff_core::write::hff(tables))
}

mod read;
pub use read::*;

mod write;
pub use write::*;

#[cfg(test)]
mod tests {
    use super::*;

    fn test_table<'a>() -> Result<HffDesc<'a>> {
        Ok(hff([
            table((Ecc::new("Test"), Ecc::new("TestSub")))
            .metadata("This is some metadata attached to the table.")?
            .chunks([
                chunk((Ecc::new("TRC0"), Ecc::new("TRS0")), "Chunks can be most types.  This is passed as an arbitrary byte array.".as_bytes())?,
                chunk(
                    (Ecc::new("TRC1"),
                    Ecc::new("TRS1")),
                    "Chunks provided to the table will maintain their order.",
                )?,
                chunk(
                    (Ecc::new("TRC2"),
                    Ecc::new("TRS2")),
                    "So, iterating through the chunks has the same order as presented here.",
                )?,
                chunk(
                    (Ecc::new("TRC3"),
                    Ecc::new("TRS3")),
                    "Chunks can be supplied with data from multiple sources.",
                )?,
                chunk(
                    (Ecc::new("TRC4"),
                    Ecc::new("TRS4")),
                    "In fact, providing a std::path::Path will pull the content of a file in as the chunk data.",
                )?,
                // Compress the string if compression is enabled.
                #[cfg(feature = "compression")]
                chunk(
                    (Ecc::new("TRC5"),
                    Ecc::new("TRS5")),
                    // Compressing chunks is just sending in a tuple with the compression level.
                    // Using lzma for compression and the level is expected to be between 0 and 9.
                    (9, "In the case of a lazy_write, the file will be opened and streamed directly to the writer without being buffered in memory."),
                )?,
                // Don't compress the string if compression is disabled.
                #[cfg(not(feature = "compression"))]
                chunk(
                    (Ecc::new("TRC5"),
                    Ecc::new("TRS5")),
                    "In the case of a lazy_write, the file will be opened and streamed directly to the writer without being buffered in memory.",
                )?,
            ])
            .children([
                table((Ecc::new("C0Prime"), Ecc::new("C0Sub")))
                .metadata("Each table has its own metadata.")?
                .chunks([chunk((Ecc::new("C0C0"), Ecc::new("C0S0")), "Each table also has its own set of chunks.")?])
                .children([
                    table((Ecc::new("C1Prime"), Ecc::new("C1Sub")))
                    .chunks([
                        chunk(
                            (Ecc::new("C1C0"),
                            Ecc::new("C1S0")),
                            "They will only be listed while iterating that specific table.",
                        )?
                    ]),
                    table((Ecc::new("C2Prime"), Ecc::new("C2Sub")))
                    .children([
                        table((Ecc::new("C3Prime"), Ecc::new("C3Sub")))
                        .chunks([
                            chunk((Ecc::new("C2C0"), Ecc::new("C2S0")), "Tables don't *have* to have chunks, tables can be used to simply contain other tables.")?
                        ])
                    ])
                ]),
                table((Ecc::new("C4Prime"), Ecc::new("C4Sub"))).chunks([
                    chunk((Ecc::new("C4C0"), Ecc::new("C4S0")),"The last chunk in the overall file.")?
                ])
                .metadata("And we're done.")?
            ])
        ]))
    }

    fn checks(hff: &Hff<ChunkCache>) {
        {
            // Check the content of root is as expected.
            let root = hff.tables().next().unwrap();
            assert_eq!(
                root.identifier(),
                (Ecc::new("Test"), Ecc::new("TestSub")).into()
            );
            assert_eq!(root.child_count(), 2);
            assert_eq!(root.chunk_count(), 6);

            // Check that we get a proper child iterator from the root.
            let mut root_children = root.iter();
            let c0 = root_children.next().unwrap();
            assert_eq!(c0.identifier().as_ecc2().0, "C0Prime".into());
            let c4 = root_children.next().unwrap();
            assert_eq!(c4.identifier().as_ecc2().0, "C4Prime".into());
            assert!(root_children.next().is_none());
        }

        {
            // Check the metadata for the root.
            let root = hff.tables().next().unwrap();
            // The resulting reader is just a reference to the data
            // in the content.  You can take a &mut Read on it if you
            // wish to use it with std::io methods such as copy.
            let metadata = hff.read(&root).unwrap();
            assert!(std::str::from_utf8(metadata)
                .unwrap()
                .starts_with("This is some metadata"));

            // Check the last table (second root child) metadata.
            let mut children = hff.tables().next().unwrap().iter();
            children.next();
            let c4 = children.next().unwrap();
            let metadata = hff.read(&c4).unwrap();
            assert!(std::str::from_utf8(metadata)
                .unwrap()
                .starts_with("And we're done."));
        }

        {
            // Check the root chunks are as expected.
            let root = hff.tables().next().unwrap();

            let test_data = [
                ("TRC0", "TRS0", "Chunks can be most types.  This is passed as an arbitrary byte array."),
                (
                    "TRC1",
                    "TRS1",
                    "Chunks provided to the table will maintain their order.",
                ),
                (
                    "TRC2",
                    "TRS2",
                    "So, iterating through the chunks has the same order as presented here.",
                ),
                (
                    "TRC3",
                    "TRS3",
                    "Chunks can be supplied with data from multiple sources.",
                ),
                (
                    "TRC4",
                    "TRS4",
                    "In fact, providing a std::path::Path will pull the content of a file in as the chunk data.",
                ),
                (
                    "TRC5",
                    "TRS5",
                    "In the case of a lazy_write, the file will be opened and streamed directly to the writer without being buffered in memory.",
                )
            ];
            for (index, chunk) in root.chunks().enumerate() {
                let test_entry = test_data[index];
                let (primary, secondary): (Ecc, Ecc) = chunk.identifier().into();
                assert_eq!(Ecc::new(test_entry.0), primary);
                assert_eq!(Ecc::new(test_entry.1), secondary);

                #[cfg(feature = "compression")]
                let (_, secondary): (Ecc, Ecc) = chunk.identifier().into();
                if secondary == Ecc::new("TRS5") {
                    let decompressed = decompress(hff.read(&chunk).unwrap()).unwrap();
                    assert_eq!(decompressed.len(), test_entry.2.len());
                    assert_eq!(decompressed, Vec::from(test_entry.2.as_bytes()));
                } else {
                    assert_eq!(chunk.size(), test_entry.2.len());
                    assert_eq!(
                        hff.read(&chunk).unwrap(),
                        Vec::from(test_entry.2.as_bytes())
                    );
                }
                #[cfg(not(feature = "compression"))]
                {
                    assert_eq!(chunk.size(), test_entry.2.len());
                    assert_eq!(
                        hff.read(&chunk).unwrap(),
                        Vec::from(test_entry.2.as_bytes())
                    );
                }
            }

            {
                let test_data = [
                    (0, "Test", "TestSub"),
                    (1, "C0Prime", "C0Sub"),
                    (2, "C1Prime", "C1Sub"),
                    (2, "C2Prime", "C2Sub"),
                    (3, "C3Prime", "C3Sub"),
                    (1, "C4Prime", "C4Sub"),
                ];
                // Test depth first iteration.
                for ((depth, table), data) in hff.depth_first().zip(test_data.iter()) {
                    assert_eq!(depth, data.0);
                    assert_eq!(
                        table.identifier(),
                        (Ecc::new(data.1), Ecc::new(data.2)).into()
                    );
                }
            }
        }
    }

    #[test]
    fn test() {
        use std::io::Seek;

        // Simple dev test for structure.
        {
            let content = test_table().unwrap();
            let buffer = vec![];
            let mut writer = std::io::Cursor::new(buffer);
            assert!(content
                .lazy_write::<hff_core::NE>(IdType::Ecc2, "Test", &mut writer)
                .is_ok());

            // Read it back in and iterate.
            writer.rewind().unwrap();
            let access = crate::read::read(&mut writer).unwrap();
            checks(&access);
        }

        // Simple dev test for structure.
        {
            let content = test_table().unwrap();
            let mut buffer = vec![];

            assert!(content
                .write::<hff_core::OP>(IdType::Ecc2, "Test", &mut buffer)
                .is_ok());

            // Read it back in and iterate.
            let access = crate::read::read(&mut buffer.as_slice()).unwrap();
            checks(&access);
        }
    }
}