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
use std::{
collections::{
btree_map::{IntoIter, Iter, Keys},
BTreeMap,
},
fmt,
};
use bytes::Bytes;
use serde::{Serialize, Serializer};
#[cfg(feature = "dat2")]
use {crate::buf::BufExtra, crate::buf::ReadError, bytes::Buf, rs3cache_utils::adapters::Accumulator, std::iter::repeat_with, std::ops::Add};
#[cfg(feature = "sqlite")]
use {crate::buf::BufExtra, crate::buf::ReadError, bytes::Buf, rs3cache_utils::adapters::Accumulator, std::iter::repeat_with, std::ops::Add};
#[cfg(feature = "pyo3")]
use {
pyo3::class::basic::CompareOp,
pyo3::prelude::*,
std::collections::hash_map::DefaultHasher,
std::hash::{Hash, Hasher},
};
#[cfg_eval]
#[cfg_attr(feature = "pyo3", pyclass(frozen))]
#[serde_with::skip_serializing_none]
#[derive(Serialize, Clone, Debug, Default, Hash, Eq, PartialOrd, Ord, PartialEq)]
pub struct Metadata {
#[cfg_attr(feature = "pyo3", pyo3(get))]
pub index_id: u32,
#[cfg_attr(feature = "pyo3", pyo3(get))]
pub archive_id: u32,
#[cfg_attr(feature = "pyo3", pyo3(get))]
pub name: Option<i32>,
#[cfg_attr(feature = "pyo3", pyo3(get))]
pub crc: i32,
#[cfg_attr(feature = "pyo3", pyo3(get))]
pub version: i32,
#[cfg_attr(feature = "pyo3", pyo3(get))]
pub unknown: Option<i32>,
#[cfg_attr(feature = "pyo3", pyo3(get))]
pub compressed_size: Option<u32>,
#[cfg_attr(feature = "pyo3", pyo3(get))]
pub size: Option<u32>,
#[serde(serialize_with = "bytes_to_vec")]
pub digest: Option<Bytes>,
#[cfg_attr(feature = "pyo3", pyo3(get))]
pub child_count: u32,
#[cfg_attr(feature = "pyo3", pyo3(get))]
pub child_indices: Vec<u32>,
}
impl fmt::Display for Metadata {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Metadata({})", serde_json::to_string(self).unwrap())
}
}
#[cfg(feature = "pyo3")]
#[pyo3::pymethods]
impl Metadata {
#[getter(digest)]
fn py_digest(&self, py: Python) -> Py<PyAny> {
match self.digest {
Some(ref b) => pyo3::types::PyBytes::new(py, b).into(),
None => py.None(),
}
}
fn __repr__(&self) -> PyResult<String> {
Ok(format!("Metadata({})", serde_json::to_string(self).unwrap()))
}
fn __str__(&self) -> PyResult<String> {
Ok(format!("Metadata({})", serde_json::to_string(self).unwrap()))
}
fn __hash__(&self) -> PyResult<u64> {
let mut hasher = DefaultHasher::new();
self.hash(&mut hasher);
Ok(hasher.finish())
}
fn __richcmp__(&self, other: &Metadata, op: CompareOp) -> PyResult<bool> {
match op {
CompareOp::Lt => Ok(self < other),
CompareOp::Le => Ok(self <= other),
CompareOp::Eq => Ok(self == other),
CompareOp::Ne => Ok(self != other),
CompareOp::Gt => Ok(self > other),
CompareOp::Ge => Ok(self >= other),
}
}
}
pub fn bytes_to_vec<S>(bytes: &Option<Bytes>, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match *bytes {
Some(ref value) => s.serialize_some(&**value),
None => s.serialize_none(),
}
}
impl Metadata {
#[inline(always)]
pub const fn index_id(&self) -> u32 {
self.index_id
}
#[inline(always)]
pub const fn archive_id(&self) -> u32 {
self.archive_id
}
#[inline(always)]
pub const fn name(&self) -> Option<i32> {
self.name
}
#[inline(always)]
pub const fn crc(&self) -> i32 {
self.crc
}
#[inline(always)]
pub const fn version(&self) -> i32 {
self.version
}
#[inline(always)]
pub const fn unknown(&self) -> Option<i32> {
self.unknown
}
#[inline(always)]
pub const fn compressed_size(&self) -> Option<u32> {
self.compressed_size
}
#[inline(always)]
pub const fn size(&self) -> Option<u32> {
self.size
}
#[inline(always)]
pub fn digest(&self) -> Option<&[u8]> {
self.digest.as_deref()
}
#[inline(always)]
pub const fn child_count(&self) -> u32 {
self.child_count
}
#[inline(always)]
pub fn child_indices(&self) -> &[u32] {
&self.child_indices
}
}
#[derive(Serialize, Clone, Debug, Default, Hash, Eq, Ord, PartialOrd, PartialEq)]
pub struct IndexMetadata {
metadatas: BTreeMap<u32, Metadata>,
}
impl IndexMetadata {
#[cfg(any(feature = "dat2", feature = "dat"))]
pub(crate) fn empty() -> Self {
Self {
metadatas: BTreeMap::default(),
}
}
#[inline(always)]
pub fn keys(&self) -> Keys<'_, u32, Metadata> {
self.metadatas.keys()
}
#[cfg(any(feature = "sqlite", feature = "dat2"))]
pub(crate) fn deserialize(index_id: u32, mut buffer: Bytes) -> Result<Self, ReadError> {
let format = buffer.try_get_i8()?;
let _index_utc_stamp = if format > 5 { Some(buffer.try_get_i32()?) } else { None };
let [named, hashed, unk4, ..] = buffer.get_bitflags();
let entry_count = if format >= 7 {
buffer.try_get_smart32()?.unwrap() as usize
} else {
buffer.try_get_u16()? as usize
};
let archive_ids = repeat_with(|| try {
if format >= 7 {
buffer.try_get_smart32()?.unwrap()
} else {
buffer.try_get_u16()? as u32
}
})
.take(entry_count)
.collect::<Result<Vec<u32>, ReadError>>()?
.into_iter()
.accumulate(Add::add)
.collect::<Vec<u32>>();
let names = if named {
repeat_with(|| try { Some(buffer.try_get_i32()?) })
.take(entry_count)
.collect::<Result<Vec<Option<i32>>, ReadError>>()?
} else {
vec![None; entry_count]
};
let crcs = repeat_with(|| buffer.try_get_i32())
.take(entry_count)
.collect::<Result<Vec<i32>, ReadError>>()?;
let unknowns = if unk4 {
repeat_with(|| try { Some(buffer.try_get_i32()?) })
.take(entry_count)
.collect::<Result<Vec<Option<i32>>, ReadError>>()?
} else {
vec![None; entry_count]
};
let digests = if hashed {
repeat_with(|| Some(buffer.copy_to_bytes(64))).take(entry_count).collect()
} else {
vec![None; entry_count]
};
let (compressed_sizes, sizes): (Vec<_>, Vec<_>) = if unk4 {
repeat_with(|| (Some(buffer.get_u32()), Some(buffer.get_u32()))).take(entry_count).unzip()
} else {
(vec![None; entry_count], vec![None; entry_count])
};
let versions = repeat_with(|| buffer.get_i32()).take(entry_count).collect::<Vec<i32>>();
let child_counts = repeat_with(|| {
if format >= 7 {
buffer.get_smart32().unwrap()
} else {
buffer.get_u16() as u32
}
})
.take(entry_count)
.collect::<Vec<u32>>();
let child_indices = child_counts
.iter()
.map(|count| {
repeat_with(|| {
if format >= 7 {
buffer.get_smart32().unwrap()
} else {
buffer.get_u16() as u32
}
})
.take(*count as usize)
.accumulate(Add::add)
.collect::<Vec<u32>>()
})
.collect::<Vec<Vec<u32>>>();
let metadatas = itertools::izip!(
archive_ids,
names,
crcs,
unknowns,
digests,
compressed_sizes,
sizes,
versions,
child_counts,
child_indices
)
.map(
|(archive_id, name, crc, unknown, digest, compressed_size, size, version, child_count, child_indices)| {
(
archive_id,
Metadata {
index_id,
archive_id,
name,
crc,
version,
unknown,
compressed_size,
size,
digest,
child_count,
child_indices,
},
)
},
)
.collect();
Ok(Self { metadatas })
}
#[inline(always)]
pub fn get(&self, archive_id: &u32) -> Option<&Metadata> {
self.metadatas.get(archive_id)
}
#[inline(always)]
pub fn iter(&self) -> Iter<'_, u32, Metadata> {
self.metadatas.iter()
}
pub fn metadatas(&self) -> &BTreeMap<u32, Metadata> {
&self.metadatas
}
}
impl IntoIterator for IndexMetadata {
type Item = (u32, Metadata);
type IntoIter = IntoIter<u32, Metadata>;
fn into_iter(self) -> Self::IntoIter {
self.metadatas.into_iter()
}
}