aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Cargo.toml1
-rw-r--r--src/error.rs10
-rw-r--r--src/structs/de.rs365
-rw-r--r--src/structs/error.rs12
-rw-r--r--src/structs/mod.rs1
-rw-r--r--src/structs/ser.rs67
-rw-r--r--src/structs/settings.rs82
-rw-r--r--src/structs/tests.rs95
-rw-r--r--src/zip/driver.rs55
-rw-r--r--src/zip/structs.rs9
-rw-r--r--tests/usage.rs19
11 files changed, 567 insertions, 149 deletions
diff --git a/Cargo.toml b/Cargo.toml
index d511387..71fef29 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -12,6 +12,5 @@ categories = ["compression", "filesystem"]
12exclude = [".vscode/"] 12exclude = [".vscode/"]
13 13
14[dependencies] 14[dependencies]
15bincode = "1.3.3"
16chrono = "0.4.29" 15chrono = "0.4.29"
17serde = { version = "1.0.203", features = ["derive"] } 16serde = { version = "1.0.203", features = ["derive"] }
diff --git a/src/error.rs b/src/error.rs
index 9252762..7172d04 100644
--- a/src/error.rs
+++ b/src/error.rs
@@ -27,15 +27,7 @@ impl<E: Error> Display for ArchiveError<E> {
27 } 27 }
28} 28}
29 29
30impl<E: Error> Error for ArchiveError<E> { 30impl<E: Error> Error for ArchiveError<E> {}
31 fn source(&self) -> Option<&(dyn Error + 'static)> {
32 match self {
33 Self::IO { error } => Some(error),
34 Self::Serde { .. } => None,
35 Self::Archivator { module, error } => None,
36 }
37 }
38}
39 31
40impl<E: Error> serde::ser::Error for ArchiveError<E> { 32impl<E: Error> serde::ser::Error for ArchiveError<E> {
41 fn custom<T: Display>(msg: T) -> Self { 33 fn custom<T: Display>(msg: T) -> Self {
diff --git a/src/structs/de.rs b/src/structs/de.rs
index e69de29..9158d90 100644
--- a/src/structs/de.rs
+++ b/src/structs/de.rs
@@ -0,0 +1,365 @@
1use crate::structs::{Settings, StructError, StructResult};
2use crate::ArchiveError;
3use serde::de;
4
5pub struct ArchiveDeserializer<'de> {
6 bytes: &'de [u8],
7 pointer: usize,
8 settings: Settings,
9}
10
11struct SeqDeserializer<'a, 'de: 'a> {
12 de: &'a mut ArchiveDeserializer<'de>,
13 len: usize,
14}
15
16struct EnumDeserializer<'a, 'de: 'a> {
17 de: &'a mut ArchiveDeserializer<'de>,
18}
19
20impl<'de> ArchiveDeserializer<'de> {
21 pub fn new(bytes: &'de [u8], settings: Settings) -> Self {
22 Self {
23 bytes,
24 pointer: 0,
25 settings,
26 }
27 }
28
29 fn take<const S: usize>(&mut self) -> StructResult<[u8; S]> {
30 let bytes = self
31 .bytes
32 .get(self.pointer..self.pointer + S)
33 .ok_or(StructError::UnexpectedEOF)?
34 .try_into()
35 .unwrap();
36 self.pointer += S;
37 Ok(bytes)
38 }
39
40 fn take_byte(&mut self) -> StructResult<u8> {
41 let byte = self
42 .bytes
43 .get(self.pointer)
44 .ok_or(StructError::UnexpectedEOF)?;
45 self.pointer += 1;
46 Ok(*byte)
47 }
48}
49
50impl<'a, 'de> SeqDeserializer<'a, 'de> {
51 pub fn new(de: &'a mut ArchiveDeserializer<'de>, len: usize) -> Self {
52 Self { de, len }
53 }
54}
55
56impl<'a, 'de> EnumDeserializer<'a, 'de> {
57 pub fn new(de: &'a mut ArchiveDeserializer<'de>) -> Self {
58 Self { de }
59 }
60}
61
62impl<'de> de::Deserializer<'de> for &mut ArchiveDeserializer<'de> {
63 type Error = ArchiveError<StructError>;
64
65 fn deserialize_any<V>(self, _visitor: V) -> StructResult<V::Value>
66 where
67 V: de::Visitor<'de>,
68 {
69 Err(StructError::DeserializationNotSupported { type_name: "any" }.into())
70 }
71
72 fn deserialize_bool<V>(self, visitor: V) -> StructResult<V::Value>
73 where
74 V: de::Visitor<'de>,
75 {
76 visitor.visit_bool(self.take_byte()? != 0)
77 }
78
79 fn deserialize_i8<V>(self, visitor: V) -> StructResult<V::Value>
80 where
81 V: de::Visitor<'de>,
82 {
83 visitor.visit_i8(self.take_byte()? as i8)
84 }
85
86 fn deserialize_i16<V>(self, visitor: V) -> StructResult<V::Value>
87 where
88 V: de::Visitor<'de>,
89 {
90 let bytes = self.take()?;
91 visitor.visit_i16(self.settings.byte_order.to_i16(bytes))
92 }
93
94 fn deserialize_i32<V>(self, visitor: V) -> StructResult<V::Value>
95 where
96 V: de::Visitor<'de>,
97 {
98 let bytes = self.take()?;
99 visitor.visit_i32(self.settings.byte_order.to_i32(bytes))
100 }
101
102 fn deserialize_i64<V>(self, visitor: V) -> StructResult<V::Value>
103 where
104 V: de::Visitor<'de>,
105 {
106 let bytes = self.take()?;
107 visitor.visit_i64(self.settings.byte_order.to_i64(bytes))
108 }
109
110 fn deserialize_u8<V>(self, visitor: V) -> StructResult<V::Value>
111 where
112 V: de::Visitor<'de>,
113 {
114 visitor.visit_u8(self.take_byte()?)
115 }
116
117 fn deserialize_u16<V>(self, visitor: V) -> StructResult<V::Value>
118 where
119 V: de::Visitor<'de>,
120 {
121 let bytes = self.take()?;
122 visitor.visit_u16(self.settings.byte_order.to_u16(bytes))
123 }
124
125 fn deserialize_u32<V>(self, visitor: V) -> StructResult<V::Value>
126 where
127 V: de::Visitor<'de>,
128 {
129 let bytes = self.take()?;
130 visitor.visit_u32(self.settings.byte_order.to_u32(bytes))
131 }
132
133 fn deserialize_u64<V>(self, visitor: V) -> StructResult<V::Value>
134 where
135 V: de::Visitor<'de>,
136 {
137 let bytes = self.take()?;
138 visitor.visit_u64(self.settings.byte_order.to_u64(bytes))
139 }
140
141 fn deserialize_f32<V>(self, visitor: V) -> StructResult<V::Value>
142 where
143 V: de::Visitor<'de>,
144 {
145 let bytes = self.take()?;
146 visitor.visit_f32(self.settings.byte_order.to_f32(bytes))
147 }
148
149 fn deserialize_f64<V>(self, visitor: V) -> StructResult<V::Value>
150 where
151 V: de::Visitor<'de>,
152 {
153 let bytes = self.take()?;
154 visitor.visit_f64(self.settings.byte_order.to_f64(bytes))
155 }
156
157 fn deserialize_char<V>(self, _visitor: V) -> StructResult<V::Value>
158 where
159 V: de::Visitor<'de>,
160 {
161 Err(StructError::DeserializationNotSupported { type_name: "char" }.into())
162 }
163
164 fn deserialize_str<V>(self, _visitor: V) -> StructResult<V::Value>
165 where
166 V: de::Visitor<'de>,
167 {
168 Err(StructError::DeserializationNotSupported { type_name: "str" }.into())
169 }
170
171 fn deserialize_string<V>(self, _visitor: V) -> StructResult<V::Value>
172 where
173 V: de::Visitor<'de>,
174 {
175 Err(StructError::DeserializationNotSupported {
176 type_name: "string",
177 }
178 .into())
179 }
180
181 fn deserialize_bytes<V>(self, _visitor: V) -> StructResult<V::Value>
182 where
183 V: de::Visitor<'de>,
184 {
185 Err(StructError::DeserializationNotSupported { type_name: "bytes" }.into())
186 }
187
188 fn deserialize_byte_buf<V>(self, _visitor: V) -> StructResult<V::Value>
189 where
190 V: de::Visitor<'de>,
191 {
192 Err(StructError::DeserializationNotSupported { type_name: "bytes" }.into())
193 }
194
195 fn deserialize_option<V>(self, _visitor: V) -> StructResult<V::Value>
196 where
197 V: de::Visitor<'de>,
198 {
199 Err(StructError::DeserializationNotSupported {
200 type_name: "optional",
201 }
202 .into())
203 }
204
205 fn deserialize_unit<V>(self, visitor: V) -> StructResult<V::Value>
206 where
207 V: de::Visitor<'de>,
208 {
209 visitor.visit_unit()
210 }
211
212 fn deserialize_unit_struct<V>(self, _name: &'static str, visitor: V) -> StructResult<V::Value>
213 where
214 V: de::Visitor<'de>,
215 {
216 self.deserialize_unit(visitor)
217 }
218
219 fn deserialize_newtype_struct<V>(
220 self,
221 _name: &'static str,
222 visitor: V,
223 ) -> StructResult<V::Value>
224 where
225 V: de::Visitor<'de>,
226 {
227 visitor.visit_newtype_struct(self)
228 }
229
230 fn deserialize_seq<V>(self, _visitor: V) -> StructResult<V::Value>
231 where
232 V: de::Visitor<'de>,
233 {
234 Err(StructError::DeserializationNotSupported { type_name: "seq" }.into())
235 }
236
237 fn deserialize_tuple<V>(self, len: usize, visitor: V) -> StructResult<V::Value>
238 where
239 V: de::Visitor<'de>,
240 {
241 visitor.visit_seq(SeqDeserializer::new(self, len))
242 }
243
244 fn deserialize_tuple_struct<V>(
245 self,
246 _name: &'static str,
247 len: usize,
248 visitor: V,
249 ) -> StructResult<V::Value>
250 where
251 V: de::Visitor<'de>,
252 {
253 self.deserialize_tuple(len, visitor)
254 }
255
256 fn deserialize_map<V>(self, _visitor: V) -> StructResult<V::Value>
257 where
258 V: de::Visitor<'de>,
259 {
260 Err(StructError::DeserializationNotSupported { type_name: "map" }.into())
261 }
262
263 fn deserialize_struct<V>(
264 self,
265 _name: &'static str,
266 fields: &'static [&'static str],
267 visitor: V,
268 ) -> StructResult<V::Value>
269 where
270 V: de::Visitor<'de>,
271 {
272 self.deserialize_tuple(fields.len(), visitor)
273 }
274
275 fn deserialize_enum<V>(
276 self,
277 _name: &'static str,
278 _variants: &'static [&'static str],
279 visitor: V,
280 ) -> StructResult<V::Value>
281 where
282 V: de::Visitor<'de>,
283 {
284 visitor.visit_enum(EnumDeserializer::new(self))
285 }
286
287 fn deserialize_identifier<V>(self, visitor: V) -> StructResult<V::Value>
288 where
289 V: de::Visitor<'de>,
290 {
291 match self.settings.variant_index_type {
292 super::VariantIndexType::U8 => self.deserialize_u8(visitor),
293 super::VariantIndexType::U16 => self.deserialize_u16(visitor),
294 super::VariantIndexType::U32 => self.deserialize_u32(visitor),
295 super::VariantIndexType::U64 => self.deserialize_u64(visitor),
296 }
297 }
298
299 #[inline]
300 fn deserialize_ignored_any<V>(self, visitor: V) -> StructResult<V::Value>
301 where
302 V: de::Visitor<'de>,
303 {
304 self.deserialize_any(visitor)
305 }
306}
307
308impl<'a, 'de> de::SeqAccess<'de> for SeqDeserializer<'a, 'de> {
309 type Error = ArchiveError<StructError>;
310
311 fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
312 where
313 T: de::DeserializeSeed<'de>,
314 {
315 if self.len == 0 {
316 return Ok(None);
317 }
318 seed.deserialize(&mut *self.de).map(Some)
319 }
320}
321
322impl<'a, 'de> de::EnumAccess<'de> for EnumDeserializer<'a, 'de> {
323 type Error = ArchiveError<StructError>;
324 type Variant = Self;
325
326 fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
327 where
328 V: de::DeserializeSeed<'de>,
329 {
330 Ok((seed.deserialize(&mut *self.de)?, self))
331 }
332}
333
334impl<'a, 'de> de::VariantAccess<'de> for EnumDeserializer<'a, 'de> {
335 type Error = ArchiveError<StructError>;
336
337 fn unit_variant(self) -> Result<(), Self::Error> {
338 Ok(())
339 }
340
341 fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
342 where
343 T: de::DeserializeSeed<'de>,
344 {
345 seed.deserialize(&mut *self.de)
346 }
347
348 fn tuple_variant<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
349 where
350 V: de::Visitor<'de>,
351 {
352 de::Deserializer::deserialize_tuple(self.de, len, visitor)
353 }
354
355 fn struct_variant<V>(
356 self,
357 fields: &'static [&'static str],
358 visitor: V,
359 ) -> Result<V::Value, Self::Error>
360 where
361 V: de::Visitor<'de>,
362 {
363 de::Deserializer::deserialize_tuple(self.de, fields.len(), visitor)
364 }
365}
diff --git a/src/structs/error.rs b/src/structs/error.rs
index b9d765d..f08c9a3 100644
--- a/src/structs/error.rs
+++ b/src/structs/error.rs
@@ -6,7 +6,9 @@ pub type StructResult<T> = ArchiveResult<T, StructError>;
6 6
7#[derive(Debug)] 7#[derive(Debug)]
8pub enum StructError { 8pub enum StructError {
9 IncorrectEnumVariant, 9 SerializationNotSupported { type_name: &'static str },
10 DeserializationNotSupported { type_name: &'static str },
11 UnexpectedEOF,
10} 12}
11 13
12impl From<StructError> for ArchiveError<StructError> { 14impl From<StructError> for ArchiveError<StructError> {
@@ -21,7 +23,13 @@ impl From<StructError> for ArchiveError<StructError> {
21impl Display for StructError { 23impl Display for StructError {
22 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 24 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
23 match self { 25 match self {
24 StructError::IncorrectEnumVariant => write!(f, "Can't cast enum variant type"), 26 StructError::SerializationNotSupported { type_name } => {
27 writeln!(f, "Serialization for type '{type_name}' not supported")
28 }
29 StructError::DeserializationNotSupported { type_name } => {
30 writeln!(f, "Deserialization for type '{type_name}' not supported")
31 }
32 StructError::UnexpectedEOF => writeln!(f, "Unexpected EOF"),
25 } 33 }
26 } 34 }
27} 35}
diff --git a/src/structs/mod.rs b/src/structs/mod.rs
index feb37dd..36bc33e 100644
--- a/src/structs/mod.rs
+++ b/src/structs/mod.rs
@@ -3,6 +3,7 @@ mod error;
3pub mod ser; 3pub mod ser;
4mod settings; 4mod settings;
5 5
6pub use de::ArchiveDeserializer;
6pub use error::{StructError, StructResult}; 7pub use error::{StructError, StructResult};
7pub use ser::ArchiveSerializer; 8pub use ser::ArchiveSerializer;
8pub use settings::{ByteOrder, Settings, VariantIndexType}; 9pub use settings::{ByteOrder, Settings, VariantIndexType};
diff --git a/src/structs/ser.rs b/src/structs/ser.rs
index 8aa95a5..6833fb8 100644
--- a/src/structs/ser.rs
+++ b/src/structs/ser.rs
@@ -43,17 +43,17 @@ impl ser::Serializer for &mut ArchiveSerializer {
43 } 43 }
44 44
45 fn serialize_i16(self, v: i16) -> StructResult<()> { 45 fn serialize_i16(self, v: i16) -> StructResult<()> {
46 self.bytes.append(&mut self.settings.byte_order.i16(v)); 46 self.bytes.append(&mut self.settings.byte_order.form_i16(v));
47 Ok(()) 47 Ok(())
48 } 48 }
49 49
50 fn serialize_i32(self, v: i32) -> StructResult<()> { 50 fn serialize_i32(self, v: i32) -> StructResult<()> {
51 self.bytes.append(&mut self.settings.byte_order.i32(v)); 51 self.bytes.append(&mut self.settings.byte_order.form_i32(v));
52 Ok(()) 52 Ok(())
53 } 53 }
54 54
55 fn serialize_i64(self, v: i64) -> StructResult<()> { 55 fn serialize_i64(self, v: i64) -> StructResult<()> {
56 self.bytes.append(&mut self.settings.byte_order.i64(v)); 56 self.bytes.append(&mut self.settings.byte_order.form_i64(v));
57 Ok(()) 57 Ok(())
58 } 58 }
59 59
@@ -63,54 +63,57 @@ impl ser::Serializer for &mut ArchiveSerializer {
63 } 63 }
64 64
65 fn serialize_u16(self, v: u16) -> StructResult<()> { 65 fn serialize_u16(self, v: u16) -> StructResult<()> {
66 self.bytes.append(&mut self.settings.byte_order.u16(v)); 66 self.bytes.append(&mut self.settings.byte_order.form_u16(v));
67 Ok(()) 67 Ok(())
68 } 68 }
69 69
70 fn serialize_u32(self, v: u32) -> StructResult<()> { 70 fn serialize_u32(self, v: u32) -> StructResult<()> {
71 self.bytes.append(&mut self.settings.byte_order.u32(v)); 71 self.bytes.append(&mut self.settings.byte_order.form_u32(v));
72 Ok(()) 72 Ok(())
73 } 73 }
74 74
75 fn serialize_u64(self, v: u64) -> StructResult<()> { 75 fn serialize_u64(self, v: u64) -> StructResult<()> {
76 self.bytes.append(&mut self.settings.byte_order.u64(v)); 76 self.bytes.append(&mut self.settings.byte_order.form_u64(v));
77 Ok(()) 77 Ok(())
78 } 78 }
79 79
80 fn serialize_f32(self, v: f32) -> StructResult<()> { 80 fn serialize_f32(self, v: f32) -> StructResult<()> {
81 self.bytes.append(&mut self.settings.byte_order.f32(v)); 81 self.bytes.append(&mut self.settings.byte_order.form_f32(v));
82 Ok(()) 82 Ok(())
83 } 83 }
84 84
85 fn serialize_f64(self, v: f64) -> StructResult<()> { 85 fn serialize_f64(self, v: f64) -> StructResult<()> {
86 self.bytes.append(&mut self.settings.byte_order.f64(v)); 86 self.bytes.append(&mut self.settings.byte_order.form_f64(v));
87 Ok(()) 87 Ok(())
88 } 88 }
89 89
90 fn serialize_char(self, v: char) -> StructResult<()> { 90 fn serialize_char(self, v: char) -> StructResult<()> {
91 self.bytes.push(v as u8); 91 Err(StructError::SerializationNotSupported { type_name: "char" }.into())
92 Ok(())
93 } 92 }
94 93
95 fn serialize_str(self, v: &str) -> StructResult<()> { 94 fn serialize_str(self, _v: &str) -> StructResult<()> {
96 self.bytes.append(&mut v.as_bytes().to_vec()); 95 Err(StructError::SerializationNotSupported { type_name: "str" }.into())
97 Ok(())
98 } 96 }
99 97
100 fn serialize_bytes(self, v: &[u8]) -> StructResult<()> { 98 fn serialize_bytes(self, _v: &[u8]) -> StructResult<()> {
101 self.bytes.append(&mut v.to_vec()); 99 Err(StructError::SerializationNotSupported { type_name: "bytes" }.into())
102 Ok(())
103 } 100 }
104 101
105 fn serialize_none(self) -> StructResult<()> { 102 fn serialize_none(self) -> StructResult<()> {
106 Ok(()) 103 Err(StructError::SerializationNotSupported {
104 type_name: "optional",
105 }
106 .into())
107 } 107 }
108 108
109 fn serialize_some<T>(self, value: &T) -> StructResult<()> 109 fn serialize_some<T>(self, value: &T) -> StructResult<()>
110 where 110 where
111 T: ?Sized + Serialize, 111 T: ?Sized + Serialize,
112 { 112 {
113 value.serialize(self) 113 Err(StructError::SerializationNotSupported {
114 type_name: "optional",
115 }
116 .into())
114 } 117 }
115 118
116 fn serialize_unit(self) -> StructResult<()> { 119 fn serialize_unit(self) -> StructResult<()> {
@@ -131,7 +134,7 @@ impl ser::Serializer for &mut ArchiveSerializer {
131 &mut self 134 &mut self
132 .settings 135 .settings
133 .variant_index_type 136 .variant_index_type
134 .cast(variant_index, &self.settings.byte_order)?, 137 .cast(variant_index, &self.settings.byte_order),
135 ); 138 );
136 Ok(()) 139 Ok(())
137 } 140 }
@@ -157,13 +160,13 @@ impl ser::Serializer for &mut ArchiveSerializer {
157 &mut self 160 &mut self
158 .settings 161 .settings
159 .variant_index_type 162 .variant_index_type
160 .cast(variant_index, &self.settings.byte_order)?, 163 .cast(variant_index, &self.settings.byte_order),
161 ); 164 );
162 value.serialize(self) 165 value.serialize(self)
163 } 166 }
164 167
165 fn serialize_seq(self, _len: Option<usize>) -> StructResult<Self::SerializeSeq> { 168 fn serialize_seq(self, _len: Option<usize>) -> StructResult<Self::SerializeSeq> {
166 Ok(self) 169 Err(StructError::SerializationNotSupported { type_name: "seq" }.into())
167 } 170 }
168 171
169 fn serialize_tuple(self, _len: usize) -> StructResult<Self::SerializeTuple> { 172 fn serialize_tuple(self, _len: usize) -> StructResult<Self::SerializeTuple> {
@@ -189,13 +192,13 @@ impl ser::Serializer for &mut ArchiveSerializer {
189 &mut self 192 &mut self
190 .settings 193 .settings
191 .variant_index_type 194 .variant_index_type
192 .cast(variant_index, &self.settings.byte_order)?, 195 .cast(variant_index, &self.settings.byte_order),
193 ); 196 );
194 Ok(self) 197 Ok(self)
195 } 198 }
196 199
197 fn serialize_map(self, _len: Option<usize>) -> StructResult<Self::SerializeMap> { 200 fn serialize_map(self, _len: Option<usize>) -> StructResult<Self::SerializeMap> {
198 Ok(self) 201 Err(StructError::SerializationNotSupported { type_name: "map" }.into())
199 } 202 }
200 203
201 fn serialize_struct( 204 fn serialize_struct(
@@ -217,7 +220,7 @@ impl ser::Serializer for &mut ArchiveSerializer {
217 &mut self 220 &mut self
218 .settings 221 .settings
219 .variant_index_type 222 .variant_index_type
220 .cast(variant_index, &self.settings.byte_order)?, 223 .cast(variant_index, &self.settings.byte_order),
221 ); 224 );
222 Ok(self) 225 Ok(self)
223 } 226 }
@@ -227,15 +230,15 @@ impl ser::SerializeSeq for &mut ArchiveSerializer {
227 type Ok = (); 230 type Ok = ();
228 type Error = ArchiveError<StructError>; 231 type Error = ArchiveError<StructError>;
229 232
230 fn serialize_element<T>(&mut self, value: &T) -> StructResult<()> 233 fn serialize_element<T>(&mut self, _value: &T) -> StructResult<()>
231 where 234 where
232 T: ?Sized + Serialize, 235 T: ?Sized + Serialize,
233 { 236 {
234 value.serialize(&mut **self) 237 Err(StructError::SerializationNotSupported { type_name: "seq" }.into())
235 } 238 }
236 239
237 fn end(self) -> StructResult<()> { 240 fn end(self) -> StructResult<()> {
238 Ok(()) 241 Err(StructError::SerializationNotSupported { type_name: "seq" }.into())
239 } 242 }
240} 243}
241 244
@@ -291,22 +294,22 @@ impl ser::SerializeMap for &mut ArchiveSerializer {
291 type Ok = (); 294 type Ok = ();
292 type Error = ArchiveError<StructError>; 295 type Error = ArchiveError<StructError>;
293 296
294 fn serialize_key<T>(&mut self, key: &T) -> StructResult<()> 297 fn serialize_key<T>(&mut self, _key: &T) -> StructResult<()>
295 where 298 where
296 T: ?Sized + Serialize, 299 T: ?Sized + Serialize,
297 { 300 {
298 key.serialize(&mut **self) 301 Err(StructError::SerializationNotSupported { type_name: "map" }.into())
299 } 302 }
300 303
301 fn serialize_value<T>(&mut self, value: &T) -> StructResult<()> 304 fn serialize_value<T>(&mut self, _value: &T) -> StructResult<()>
302 where 305 where
303 T: ?Sized + Serialize, 306 T: ?Sized + Serialize,
304 { 307 {
305 value.serialize(&mut **self) 308 Err(StructError::SerializationNotSupported { type_name: "map" }.into())
306 } 309 }
307 310
308 fn end(self) -> StructResult<()> { 311 fn end(self) -> StructResult<()> {
309 Ok(()) 312 Err(StructError::SerializationNotSupported { type_name: "map" }.into())
310 } 313 }
311} 314}
312 315
diff --git a/src/structs/settings.rs b/src/structs/settings.rs
index 63c4d3a..fce6d9e 100644
--- a/src/structs/settings.rs
+++ b/src/structs/settings.rs
@@ -1,5 +1,6 @@
1use crate::structs::{ArchiveSerializer, StructError, StructResult}; 1use crate::structs::{ArchiveDeserializer, ArchiveSerializer, StructResult};
2use serde::Serialize; 2use serde::{Deserialize, Serialize};
3use std::mem::size_of;
3 4
4pub enum ByteOrder { 5pub enum ByteOrder {
5 Le, 6 Le,
@@ -12,61 +13,53 @@ pub enum VariantIndexType {
12 U16, 13 U16,
13 U32, 14 U32,
14 U64, 15 U64,
15 I8,
16 I16,
17 I32,
18 I64,
19} 16}
20 17
21macro_rules! impl_byte_order { 18macro_rules! impl_byte_order {
22 ($($n:ident),+) => { 19 ($($to:ident $fr:ident $n:ident),+) => {
23 impl ByteOrder {$( 20 impl ByteOrder {$(
24 pub fn $n(&self, num: $n) -> Vec<u8> { 21 pub fn $fr(&self, num: $n) -> Vec<u8> {
25 match self { 22 match self {
26 ByteOrder::Le => num.to_le_bytes().to_vec(), 23 ByteOrder::Le => num.to_le_bytes().to_vec(),
27 ByteOrder::Be => num.to_be_bytes().to_vec(), 24 ByteOrder::Be => num.to_be_bytes().to_vec(),
28 ByteOrder::Ne => num.to_ne_bytes().to_vec(), 25 ByteOrder::Ne => num.to_ne_bytes().to_vec(),
29 } 26 }
30 } 27 }
28
29 pub fn $to(&self, bytes: [u8; size_of::<$n>()]) -> $n {
30 match self {
31 ByteOrder::Le => $n::from_le_bytes(bytes),
32 ByteOrder::Be => $n::from_be_bytes(bytes),
33 ByteOrder::Ne => $n::from_ne_bytes(bytes),
34 }
35 }
31 )+} 36 )+}
32 }; 37 };
33} 38}
34impl_byte_order!(u8, u16, u32, u64, i8, i16, i32, i64, f32, f64); 39
40impl_byte_order!(
41 to_u8 from_u8 u8,
42 to_u16 form_u16 u16,
43 to_u32 form_u32 u32,
44 to_u64 form_u64 u64,
45
46 to_i8 form_i8 i8,
47 to_i16 form_i16 i16,
48 to_i32 form_i32 i32,
49 to_i64 form_i64 i64,
50
51 to_f32 form_f32 f32,
52 to_f64 form_f64 f64
53);
35 54
36impl VariantIndexType { 55impl VariantIndexType {
37 pub fn cast(&self, num: u32, byte_order: &ByteOrder) -> StructResult<Vec<u8>> { 56 pub fn cast(&self, num: u32, byte_order: &ByteOrder) -> Vec<u8> {
38 Ok(match self { 57 match self {
39 VariantIndexType::U8 => byte_order.u8(num 58 VariantIndexType::U8 => byte_order.from_u8(num as u8),
40 .try_into() 59 VariantIndexType::U16 => byte_order.form_u16(num as u16),
41 .map_err(|_| StructError::IncorrectEnumVariant)?), 60 VariantIndexType::U32 => byte_order.form_u32(num as u32),
42 VariantIndexType::U16 => byte_order.u16( 61 VariantIndexType::U64 => byte_order.form_u64(num as u64),
43 num.try_into() 62 }
44 .map_err(|_| StructError::IncorrectEnumVariant)?,
45 ),
46 VariantIndexType::U32 => byte_order.u32(
47 num.try_into()
48 .map_err(|_| StructError::IncorrectEnumVariant)?,
49 ),
50 VariantIndexType::U64 => byte_order.u64(
51 num.try_into()
52 .map_err(|_| StructError::IncorrectEnumVariant)?,
53 ),
54 VariantIndexType::I8 => byte_order.i8(num
55 .try_into()
56 .map_err(|_| StructError::IncorrectEnumVariant)?),
57 VariantIndexType::I16 => byte_order.i16(
58 num.try_into()
59 .map_err(|_| StructError::IncorrectEnumVariant)?,
60 ),
61 VariantIndexType::I32 => byte_order.i32(
62 num.try_into()
63 .map_err(|_| StructError::IncorrectEnumVariant)?,
64 ),
65 VariantIndexType::I64 => byte_order.i64(
66 num.try_into()
67 .map_err(|_| StructError::IncorrectEnumVariant)?,
68 ),
69 })
70 } 63 }
71} 64}
72 65
@@ -98,6 +91,11 @@ impl Settings {
98 object.serialize(&mut serializer)?; 91 object.serialize(&mut serializer)?;
99 Ok(serializer.to_bytes()) 92 Ok(serializer.to_bytes())
100 } 93 }
94
95 pub fn deserialize<'de, T: Deserialize<'de>>(self, object: &'de [u8]) -> StructResult<T> {
96 let mut deserializer = ArchiveDeserializer::new(object, self);
97 Ok(T::deserialize(&mut deserializer)?)
98 }
101} 99}
102 100
103impl Default for Settings { 101impl Default for Settings {
diff --git a/src/structs/tests.rs b/src/structs/tests.rs
index 0fa5347..9ee7ce5 100644
--- a/src/structs/tests.rs
+++ b/src/structs/tests.rs
@@ -1,27 +1,26 @@
1use crate::structs::{ByteOrder, Settings, VariantIndexType}; 1use crate::structs::{ByteOrder, Settings, VariantIndexType};
2use serde::Serialize; 2use serde::{Deserialize, Serialize};
3 3
4#[derive(Serialize)] 4#[derive(Serialize, Deserialize, Debug, PartialEq)]
5struct Struct<'a> { 5struct Struct {
6 u8: u8, 6 u8: u8,
7 u16: u16, 7 u16: u16,
8 u32: u32, 8 u32: u32,
9 u64: u64, 9 u64: u64,
10 u8arr: [u8; 3], 10 u8arr: [u8; 3],
11 tuple: (u16, u8), 11 tuple: (u16, u8),
12 str: &'a str,
13} 12}
14 13
15#[derive(Serialize)] 14#[derive(Serialize, Deserialize, Debug, PartialEq)]
16enum Enum<'a> { 15enum Enum {
17 Unit, 16 Unit,
18 Type(u16), 17 Type(u16),
19 Tuple(u16, &'a str), 18 Tuple(u16, u8),
20 Struct { u32: u32, u64: u64 }, 19 Struct { u32: u32, u64: u64 },
21} 20}
22 21
23#[test] 22#[test]
24fn struct_serialize_test() { 23fn struct_serialize() {
25 let object = Struct { 24 let object = Struct {
26 u8: 42, 25 u8: 42,
27 u16: 26, 26 u16: 26,
@@ -29,7 +28,6 @@ fn struct_serialize_test() {
29 u64: 11, 28 u64: 11,
30 u8arr: [37, 74, 111], 29 u8arr: [37, 74, 111],
31 tuple: (24, 13), 30 tuple: (24, 13),
32 str: "yes",
33 }; 31 };
34 32
35 let bytes = Settings::default() 33 let bytes = Settings::default()
@@ -38,8 +36,7 @@ fn struct_serialize_test() {
38 .unwrap(); 36 .unwrap();
39 assert_eq!( 37 assert_eq!(
40 bytes, 38 bytes,
41 //u8|-u16--|----u32-----|----------u64-----------|[0]-[1]--[2]|.0 --.1---|-y----e----s| 39 [42, 26, 0, 69, 0, 0, 0, 11, 0, 0, 0, 0, 0, 0, 0, 37, 74, 111, 24, 0, 13]
42 [42, 26, 0, 69, 0, 0, 0, 11, 0, 0, 0, 0, 0, 0, 0, 37, 74, 111, 24, 0, 13, 121, 101, 115]
43 ); 40 );
44 41
45 let bytes = Settings::default() 42 let bytes = Settings::default()
@@ -48,13 +45,12 @@ fn struct_serialize_test() {
48 .unwrap(); 45 .unwrap();
49 assert_eq!( 46 assert_eq!(
50 bytes, 47 bytes,
51 //u8|-u16--|----u32-----|----------u64-----------|[0]-[1]--[2]|.0 --.1---|-y----e----s| 48 [42, 0, 26, 0, 0, 0, 69, 0, 0, 0, 0, 0, 0, 0, 11, 37, 74, 111, 0, 24, 13]
52 [42, 0, 26, 0, 0, 0, 69, 0, 0, 0, 0, 0, 0, 0, 11, 37, 74, 111, 0, 24, 13, 121, 101, 115]
53 ); 49 );
54} 50}
55 51
56#[test] 52#[test]
57fn enum_serialize_test() { 53fn enum_serialize() {
58 let bytes = Settings::default() 54 let bytes = Settings::default()
59 .byte_order(ByteOrder::Le) 55 .byte_order(ByteOrder::Le)
60 .variant_index_type(VariantIndexType::U8) 56 .variant_index_type(VariantIndexType::U8)
@@ -72,9 +68,9 @@ fn enum_serialize_test() {
72 let bytes = Settings::default() 68 let bytes = Settings::default()
73 .byte_order(ByteOrder::Le) 69 .byte_order(ByteOrder::Le)
74 .variant_index_type(VariantIndexType::U32) 70 .variant_index_type(VariantIndexType::U32)
75 .serialize(&Enum::Tuple(26, "yes")) 71 .serialize(&Enum::Tuple(26, 15))
76 .unwrap(); 72 .unwrap();
77 assert_eq!(bytes, [2, 0, 0, 0, 26, 0, 121, 101, 115]); 73 assert_eq!(bytes, [2, 0, 0, 0, 26, 0, 15]);
78 74
79 let bytes = Settings::default() 75 let bytes = Settings::default()
80 .byte_order(ByteOrder::Be) 76 .byte_order(ByteOrder::Be)
@@ -86,3 +82,70 @@ fn enum_serialize_test() {
86 [0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 69, 0, 0, 0, 0, 0, 0, 0, 37] 82 [0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 69, 0, 0, 0, 0, 0, 0, 0, 37]
87 ); 83 );
88} 84}
85
86#[test]
87fn struct_deserialize() {
88 let object = Struct {
89 u8: 42,
90 u16: 26,
91 u32: 69,
92 u64: 11,
93 u8arr: [37, 74, 111],
94 tuple: (24, 13),
95 };
96
97 assert_eq!(
98 Settings::default()
99 .byte_order(ByteOrder::Le)
100 .deserialize::<Struct>(&[
101 42, 26, 0, 69, 0, 0, 0, 11, 0, 0, 0, 0, 0, 0, 0, 37, 74, 111, 24, 0, 13,
102 ])
103 .unwrap(),
104 object
105 );
106 assert_eq!(
107 Settings::default()
108 .byte_order(ByteOrder::Be)
109 .deserialize::<Struct>(&[
110 42, 0, 26, 0, 0, 0, 69, 0, 0, 0, 0, 0, 0, 0, 11, 37, 74, 111, 0, 24, 13
111 ])
112 .unwrap(),
113 object
114 );
115}
116
117#[test]
118fn enum_deserialize() {
119 assert_eq!(
120 Settings::default()
121 .byte_order(ByteOrder::Le)
122 .variant_index_type(VariantIndexType::U8)
123 .deserialize::<Enum>(&[0])
124 .unwrap(),
125 Enum::Unit
126 );
127 assert_eq!(
128 Settings::default()
129 .byte_order(ByteOrder::Le)
130 .variant_index_type(VariantIndexType::U16)
131 .deserialize::<Enum>(&[1, 0, 42, 0])
132 .unwrap(),
133 Enum::Type(42)
134 );
135 assert_eq!(
136 Settings::default()
137 .byte_order(ByteOrder::Le)
138 .variant_index_type(VariantIndexType::U32)
139 .deserialize::<Enum>(&[2, 0, 0, 0, 26, 0, 15])
140 .unwrap(),
141 Enum::Tuple(26, 15)
142 );
143 assert_eq!(
144 Settings::default()
145 .byte_order(ByteOrder::Be)
146 .variant_index_type(VariantIndexType::U64)
147 .deserialize::<Enum>(&[0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 69, 0, 0, 0, 0, 0, 0, 0, 37])
148 .unwrap(),
149 Enum::Struct { u32: 69, u64: 37 }
150 );
151}
diff --git a/src/zip/driver.rs b/src/zip/driver.rs
index d575509..e5aa58d 100644
--- a/src/zip/driver.rs
+++ b/src/zip/driver.rs
@@ -1,6 +1,6 @@
1use crate::driver::{ArchiveRead, ArchiveWrite, Driver}; 1use crate::driver::{ArchiveRead, ArchiveWrite, Driver};
2use crate::zip::error::{ZipError, ZipResult}; 2use crate::zip::error::{ZipError, ZipResult};
3use crate::zip::structs::{EOCDR64Locator, CDR, EOCDR, EOCDR64}; 3use crate::zip::structs::{deserialize, EOCDR64Locator, CDR, EOCDR, EOCDR64};
4use crate::zip::ZipFile; 4use crate::zip::ZipFile;
5use std::collections::HashMap as Map; 5use std::collections::HashMap as Map;
6use std::fs::File; 6use std::fs::File;
@@ -41,7 +41,7 @@ impl<IO: Read + Seek> ArchiveRead for Zip<IO> {
41 io.read(&mut buf)?; 41 io.read(&mut buf)?;
42 buf 42 buf
43 }; 43 };
44 let eocdr: EOCDR = bincode::deserialize(&buf).map_err(|_| ZipError::InvalidEOCDR)?; 44 let eocdr: EOCDR = deserialize(&buf).map_err(|_| ZipError::InvalidEOCDR)?;
45 let comment = { 45 let comment = {
46 let mut buf: Vec<u8> = vec![0; eocdr.comment_len as usize]; 46 let mut buf: Vec<u8> = vec![0; eocdr.comment_len as usize];
47 io.read(&mut buf)?; 47 io.read(&mut buf)?;
@@ -55,31 +55,31 @@ impl<IO: Read + Seek> ArchiveRead for Zip<IO> {
55 io.read(&mut buf)?; 55 io.read(&mut buf)?;
56 buf 56 buf
57 }; 57 };
58 let (cd_pointer, cd_size, cd_records) = 58 let (cd_pointer, cd_size, cd_records) = if u32::from_le_bytes(buf[0..4].try_into().unwrap())
59 if u32::from_le_bytes(buf[0..4].try_into().unwrap()) == 0x07064b50 { 59 == 0x07064b50
60 let eocdr64locator: EOCDR64Locator = 60 {
61 bincode::deserialize(&buf[4..]).map_err(|_| ZipError::InvalidEOCDR64Locator)?; 61 let eocdr64locator: EOCDR64Locator =
62 62 deserialize(&buf[4..]).map_err(|_| ZipError::InvalidEOCDR64Locator)?;
63 io.seek(SeekFrom::Start(eocdr64locator.eocdr64_pointer))?; 63
64 let buf = { 64 io.seek(SeekFrom::Start(eocdr64locator.eocdr64_pointer))?;
65 let mut buf = [0; 56]; 65 let buf = {
66 io.read(&mut buf)?; 66 let mut buf = [0; 56];
67 buf 67 io.read(&mut buf)?;
68 }; 68 buf
69 if u32::from_le_bytes(buf[0..4].try_into().unwrap()) != 0x06064b50 {
70 return Err(ZipError::InvalidEOCDR64Signature.into());
71 }
72 let eocdr64: EOCDR64 =
73 bincode::deserialize(&buf[4..]).map_err(|_| ZipError::InvalidEOCDR64)?;
74
75 (eocdr64.cd_pointer, eocdr64.cd_size, eocdr64.cd_records)
76 } else {
77 (
78 eocdr.cd_pointer as u64,
79 eocdr.cd_size as u64,
80 eocdr.cd_records as u64,
81 )
82 }; 69 };
70 if u32::from_le_bytes(buf[0..4].try_into().unwrap()) != 0x06064b50 {
71 return Err(ZipError::InvalidEOCDR64Signature.into());
72 }
73 let eocdr64: EOCDR64 = deserialize(&buf[4..]).map_err(|_| ZipError::InvalidEOCDR64)?;
74
75 (eocdr64.cd_pointer, eocdr64.cd_size, eocdr64.cd_records)
76 } else {
77 (
78 eocdr.cd_pointer as u64,
79 eocdr.cd_size as u64,
80 eocdr.cd_records as u64,
81 )
82 };
83 83
84 // Read cd records 84 // Read cd records
85 let mut files = Map::with_capacity(cd_records as usize); 85 let mut files = Map::with_capacity(cd_records as usize);
@@ -96,8 +96,7 @@ impl<IO: Read + Seek> ArchiveRead for Zip<IO> {
96 return Err(ZipError::InvalidCDRSignature.into()); 96 return Err(ZipError::InvalidCDRSignature.into());
97 } 97 }
98 p += 4; 98 p += 4;
99 let cdr: CDR = 99 let cdr: CDR = deserialize(&buf[p..p + 42]).map_err(|_| ZipError::InvalidCDR)?;
100 bincode::deserialize(&buf[p..p + 42]).map_err(|_| ZipError::InvalidCDR)?;
101 p += 42; 100 p += 42;
102 let name = String::from_utf8(buf[p..p + cdr.name_len as usize].into()).unwrap(); 101 let name = String::from_utf8(buf[p..p + cdr.name_len as usize].into()).unwrap();
103 p += cdr.name_len as usize; 102 p += cdr.name_len as usize;
diff --git a/src/zip/structs.rs b/src/zip/structs.rs
index e38f9f0..0f9579e 100644
--- a/src/zip/structs.rs
+++ b/src/zip/structs.rs
@@ -1,3 +1,4 @@
1use crate::structs::{Settings, StructResult};
1use serde::{Deserialize, Serialize}; 2use serde::{Deserialize, Serialize};
2 3
3#[derive(Serialize, Deserialize)] 4#[derive(Serialize, Deserialize)]
@@ -50,3 +51,11 @@ pub struct CDR {
50 pub external_attributes: u32, 51 pub external_attributes: u32,
51 pub header_pointer: u32, 52 pub header_pointer: u32,
52} 53}
54
55pub fn serialize<T: Serialize>(object: &mut T) -> StructResult<Vec<u8>> {
56 Settings::default().serialize(object)
57}
58
59pub fn deserialize<'de, T: Deserialize<'de>>(object: &'de [u8]) -> StructResult<T> {
60 Settings::default().deserialize(object)
61}
diff --git a/tests/usage.rs b/tests/usage.rs
deleted file mode 100644
index 2faf517..0000000
--- a/tests/usage.rs
+++ /dev/null
@@ -1,19 +0,0 @@
1use archivator::{Archive, Zip};
2use std::fs::File;
3use std::time::{SystemTime, UNIX_EPOCH};
4
5fn time() -> f64 {
6 SystemTime::now()
7 .duration_since(UNIX_EPOCH)
8 .unwrap()
9 .as_secs_f64()
10}
11
12// #[test]
13fn time_test() {
14 let file = File::open("tests/files/1M.zip").unwrap();
15
16 let start = time();
17 let archive = Archive::<Zip>::new(file).unwrap();
18 println!("{}", time() - start);
19}