1use crate::{
3 property_set::{
4 DynProperty, Property, PropertyDepsQueue, PropertySet, PropertySetDependency,
5 PropertySetId, StringDepsQueue, cmp_dyn_properties,
6 },
7 static_string_ref::{BlockStringRef, StaticStringRef},
8};
9use micromegas_transit::{
10 HeterogeneousQueue, StaticStringDependency, read_any, string_codec::StringCodec,
11};
12use rustc_hash::{FxHashMap, FxHashSet};
13use smallvec::SmallVec;
14use std::{borrow::Cow, collections::hash_map::Entry, fmt};
15use xxhash_rust::xxh3::{xxh3_64, xxh3_64_with_seed};
16
17pub const DYN_ID_TAG: u64 = 1 << 63;
20
21const FIRST_INSERT_CAPACITY: usize = 64 * 1024;
22
23const RECORD_HEADER: usize = 1 + std::mem::size_of::<u32>();
25const STRING_HEADER: usize = std::mem::size_of::<u64>() + 1 + std::mem::size_of::<u32>();
27const SET_HEADER: usize = std::mem::size_of::<u64>() + std::mem::size_of::<u32>();
29
30fn dyn_string_id(offset: u32) -> u64 {
31 DYN_ID_TAG | (u64::from(offset) << 1)
32}
33
34fn dyn_set_id(offset: u32) -> u64 {
35 DYN_ID_TAG | (u64::from(offset) << 1) | 1
36}
37
38fn dyn_offset(id: u64) -> u32 {
39 ((id & !DYN_ID_TAG) >> 1) as u32
40}
41
42const INLINE_PROPERTIES: usize = 8;
44
45pub struct MergedProperties<'a> {
47 properties: SmallVec<[DynProperty<'a>; INLINE_PROPERTIES]>,
48 static_values: u64,
50 static_names: u64,
52}
53
54impl<'a> MergedProperties<'a> {
55 pub fn properties(&self) -> &[DynProperty<'a>] {
56 &self.properties
57 }
58
59 #[doc(hidden)]
60 pub fn is_static_value(&self, index: usize) -> bool {
61 is_static_bit(self.static_values, index)
62 }
63
64 #[doc(hidden)]
65 pub fn is_static_name(&self, index: usize) -> bool {
66 is_static_bit(self.static_names, index)
67 }
68}
69
70fn is_static_bit(mask: u64, index: usize) -> bool {
71 index < 64 && (mask >> index) & 1 != 0
72}
73
74#[inline]
79pub fn merge_properties<'a>(
80 static_set: &'static PropertySet,
81 dyn_properties: &[DynProperty<'a>],
82) -> MergedProperties<'a> {
83 let mut properties: SmallVec<[DynProperty<'a>; INLINE_PROPERTIES]> = SmallVec::new();
84 for dyn_prop in dyn_properties {
85 properties.retain(|p| !p.name().eq_ignore_ascii_case(dyn_prop.name()));
86 properties.push(*dyn_prop);
87 }
88 properties.sort_by(cmp_dyn_properties);
89
90 let statics = static_set.dyn_properties();
91 if statics.is_empty() {
92 let static_names = properties
95 .iter()
96 .take(64)
97 .enumerate()
98 .fold(0u64, |names, (i, p)| {
99 names | (u64::from(p.is_static_name()) << i)
100 });
101 return MergedProperties {
102 properties,
103 static_values: 0,
104 static_names,
105 };
106 }
107 let deduped = std::mem::take(&mut properties);
108 let mut static_values = 0u64;
111 let mut static_names = 0u64;
112 let mut dynamic = deduped.iter().peekable();
113 let mut statics = statics
114 .iter()
115 .filter(|s| {
116 !deduped
117 .iter()
118 .any(|d| d.name().eq_ignore_ascii_case(s.name()))
119 })
120 .peekable();
121 loop {
122 let from_static = match (statics.peek(), dynamic.peek()) {
123 (None, None) => break,
124 (Some(_), None) => true,
125 (None, Some(_)) => false,
126 (Some(s), Some(d)) => cmp_dyn_properties(s, d).is_le(),
128 };
129 let prop = if from_static {
130 *statics.next().unwrap()
131 } else {
132 *dynamic.next().unwrap()
133 };
134 let i = properties.len();
135 if i < 64 {
136 static_values |= u64::from(from_static) << i;
137 static_names |= u64::from(prop.is_static_name()) << i;
138 }
139 properties.push(prop);
140 }
141 MergedProperties {
142 properties,
143 static_values,
144 static_names,
145 }
146}
147
148#[doc(hidden)]
149pub fn content_hash<'a>(properties: impl Iterator<Item = (&'a str, &'a str)>) -> u64 {
150 properties.fold(0, |h, (name, value)| {
151 xxh3_64_with_seed(value.as_bytes(), xxh3_64_with_seed(name.as_bytes(), h))
152 })
153}
154
155#[inline]
156fn read_u32(bytes: &[u8], at: usize) -> u32 {
157 u32::from_ne_bytes(bytes[at..at + 4].try_into().unwrap())
158}
159
160#[inline]
161fn string_at(bytes: &[u8], offset: u32) -> &str {
162 let payload = offset as usize + RECORD_HEADER;
163 let len = read_u32(bytes, payload + std::mem::size_of::<u64>() + 1) as usize;
164 let begin = payload + STRING_HEADER;
165 unsafe { std::str::from_utf8_unchecked(&bytes[begin..begin + len]) }
167}
168
169#[inline]
170fn set_len(bytes: &[u8], offset: u32) -> usize {
171 read_u32(
172 bytes,
173 offset as usize + RECORD_HEADER + std::mem::size_of::<u64>(),
174 ) as usize
175}
176
177#[inline]
178fn set_property(bytes: &[u8], offset: u32, index: usize) -> Property {
179 let size = std::mem::size_of::<Property>();
180 let begin = offset as usize + RECORD_HEADER + SET_HEADER + index * size;
181 let window = &bytes[begin..begin + size];
182 unsafe { read_any::<Property>(window.as_ptr()) }
184}
185
186pub(crate) unsafe fn static_ref_str(r: &StaticStringRef) -> &'static str {
191 unsafe {
192 let slice = std::slice::from_raw_parts(r.ptr as *const u8, r.len as usize);
193 std::str::from_utf8_unchecked(slice)
194 }
195}
196
197struct HashIndex<T> {
200 first: FxHashMap<u64, T>,
201 collisions: FxHashMap<u64, Vec<T>>,
202}
203
204impl<T> HashIndex<T> {
205 fn new() -> Self {
206 Self {
207 first: FxHashMap::default(),
208 collisions: FxHashMap::default(),
209 }
210 }
211
212 fn candidates(&self, hash: u64) -> impl Iterator<Item = &T> {
213 let extra = if self.collisions.is_empty() {
214 None
215 } else {
216 self.collisions.get(&hash)
217 };
218 self.first
219 .get(&hash)
220 .into_iter()
221 .chain(extra.into_iter().flatten())
222 }
223
224 fn insert(&mut self, hash: u64, record: T) {
225 match self.first.entry(hash) {
226 Entry::Vacant(slot) => {
227 slot.insert(record);
228 }
229 Entry::Occupied(_) => self.collisions.entry(hash).or_default().push(record),
230 }
231 }
232
233 fn iter(&self) -> impl Iterator<Item = &T> {
234 self.first
235 .values()
236 .chain(self.collisions.values().flatten())
237 }
238}
239
240#[derive(Debug)]
241struct DynSet {
242 offset: u32,
243 static_values: u64,
245 static_names: u64,
246}
247
248pub struct DynDeps<D> {
254 queue: D,
255 strings: HashIndex<u32>,
257 sets: HashIndex<DynSet>,
258}
259
260impl<D> fmt::Debug for DynDeps<D> {
261 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
262 f.debug_struct("DynDeps").finish_non_exhaustive()
263 }
264}
265
266impl<D: HeterogeneousQueue> Default for DynDeps<D> {
267 fn default() -> Self {
268 Self::new()
269 }
270}
271
272impl<D: HeterogeneousQueue> DynDeps<D> {
273 pub fn new() -> Self {
275 Self {
276 queue: D::new(0),
277 strings: HashIndex::new(),
278 sets: HashIndex::new(),
279 }
280 }
281
282 pub fn len_bytes(&self) -> usize {
284 self.queue.len_bytes()
285 }
286
287 pub fn queue(&self) -> &D {
288 &self.queue
289 }
290
291 fn reserve_on_first_insert(&mut self) {
292 if self.queue.capacity_bytes() == 0 {
293 self.queue = D::new(FIRST_INSERT_CAPACITY);
294 }
295 }
296
297 pub fn set_properties(&self, id: PropertySetId) -> Vec<(&str, &str)> {
299 if let Some(set) = id.as_interned() {
300 return set
301 .get_properties()
302 .iter()
303 .map(|p| (p.name.as_str(), p.value.as_str()))
304 .collect();
305 }
306 let offset = dyn_offset(id.0);
307 let bytes = self.queue.as_bytes();
308 let set = self
309 .sets
310 .iter()
311 .find(|s| s.offset == offset)
312 .expect("unknown dynamic set id");
313 (0..set_len(bytes, offset))
314 .map(|i| {
315 let prop = set_property(bytes, offset, i);
316 (
317 ref_str(bytes, &prop.name, set.static_names, i),
318 ref_str(bytes, &prop.value, set.static_values, i),
319 )
320 })
321 .collect()
322 }
323
324 pub fn str(&self, id: u64) -> &str {
326 string_at(self.queue.as_bytes(), dyn_offset(id))
327 }
328}
329
330#[inline]
333fn ref_str<'b>(bytes: &'b [u8], r: &StaticStringRef, mask: u64, index: usize) -> &'b str {
334 if is_static_bit(mask, index) {
335 unsafe { static_ref_str(r) }
337 } else {
338 string_at(bytes, dyn_offset(r.ptr))
339 }
340}
341
342impl<D: StringDepsQueue> DynDeps<D> {
343 pub fn intern_str(&mut self, value: &str) -> u64 {
345 self.reserve_on_first_insert();
346 let hash = xxh3_64(value.as_bytes());
347 let bytes = self.queue.as_bytes();
348 for &offset in self.strings.candidates(hash) {
349 if string_at(bytes, offset) == value {
350 return dyn_string_id(offset);
351 }
352 }
353 let offset = u32::try_from(self.queue.len_bytes()).expect("dynamic queue exceeds 4 GiB");
354 let id = dyn_string_id(offset);
355 self.queue.push_string(StaticStringDependency {
356 id,
357 codec: StringCodec::Utf8,
358 len: value.len() as u32,
359 ptr: value.as_ptr(),
360 });
361 self.strings.insert(hash, offset);
362 id
363 }
364
365 pub fn intern_str_ref(&mut self, value: &str) -> BlockStringRef {
367 BlockStringRef {
368 id: self.intern_str(value),
369 len: value.len() as u32,
370 codec: StringCodec::Utf8,
371 }
372 }
373}
374
375impl<D: PropertyDepsQueue> DynDeps<D> {
376 #[inline]
379 pub fn intern_set(&mut self, merged: &MergedProperties<'_>) -> PropertySetId {
380 self.reserve_on_first_insert();
381 let hash = content_hash(merged.properties.iter().map(|p| (p.name(), p.value())));
382 let bytes = self.queue.as_bytes();
383 for candidate in self.sets.candidates(hash) {
384 if Self::same_content(bytes, candidate, merged) {
385 return PropertySetId(dyn_set_id(candidate.offset));
386 }
387 }
388 let mut properties = Vec::with_capacity(merged.properties.len());
389 for (i, prop) in merged.properties.iter().enumerate() {
390 let name = if merged.is_static_name(i) {
392 unsafe { StaticStringRef::from_str_unchecked(prop.name()) }
394 } else {
395 StaticStringRef {
396 ptr: self.intern_str(prop.name()),
397 len: prop.name().len() as u32,
398 codec: StringCodec::Utf8,
399 }
400 };
401 let value = if merged.is_static_value(i) {
402 unsafe { StaticStringRef::from_str_unchecked(prop.value()) }
404 } else {
405 StaticStringRef {
406 ptr: self.intern_str(prop.value()),
407 len: prop.value().len() as u32,
408 codec: StringCodec::Utf8,
409 }
410 };
411 properties.push(Property { name, value });
412 }
413 let offset = u32::try_from(self.queue.len_bytes()).expect("dynamic queue exceeds 4 GiB");
414 let id = dyn_set_id(offset);
415 self.queue.push_set(PropertySetDependency {
416 id,
417 properties: Cow::Owned(properties),
418 });
419 self.sets.insert(
420 hash,
421 DynSet {
422 offset,
423 static_values: merged.static_values,
424 static_names: merged.static_names,
425 },
426 );
427 PropertySetId(id)
428 }
429
430 #[inline]
431 fn same_content(bytes: &[u8], candidate: &DynSet, merged: &MergedProperties<'_>) -> bool {
432 if set_len(bytes, candidate.offset) != merged.properties.len() {
433 return false;
434 }
435 merged.properties.iter().enumerate().all(|(i, wanted)| {
436 let prop = set_property(bytes, candidate.offset, i);
437 ref_str(bytes, &prop.name, candidate.static_names, i) == wanted.name()
438 && ref_str(bytes, &prop.value, candidate.static_values, i) == wanted.value()
439 })
440 }
441
442 pub(crate) fn record_static_refs(&self, recorded_deps: &mut FxHashSet<u64>, deps: &mut D) {
445 let bytes = self.queue.as_bytes();
446 for set in self.sets.iter() {
447 for i in 0..set_len(bytes, set.offset) {
448 let prop = set_property(bytes, set.offset, i);
449 if is_static_bit(set.static_names, i) && recorded_deps.insert(prop.name.id()) {
450 deps.push_string(prop.name.into_dependency());
451 }
452 if is_static_bit(set.static_values, i) && recorded_deps.insert(prop.value.id()) {
453 deps.push_string(prop.value.into_dependency());
454 }
455 }
456 }
457 }
458}