1use super::*;
5use hashbrown::HashTable;
6
7#[derive(Clone, Default)]
23pub struct MapData(Arc<MapInner>);
24
25impl std::fmt::Debug for MapData {
27 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
28 f.debug_list().entries(self.entries()).finish()
29 }
30}
31
32#[derive(Clone, Default)]
34pub(super) struct MapInner {
35 slots: Vec<Option<Slot>>,
38 index: HashTable<usize>,
40 live: usize,
42 bytes: usize,
45}
46
47#[derive(Clone)]
48struct Slot {
49 pair: (Value, Value),
50 hash: u64,
52}
53
54#[derive(Clone)]
57pub struct MapEntries<'a> {
58 slots: std::slice::Iter<'a, Option<Slot>>,
59 remaining: usize,
60}
61
62impl<'a> Iterator for MapEntries<'a> {
63 type Item = &'a (Value, Value);
64 fn next(&mut self) -> Option<Self::Item> {
65 let e = self.slots.by_ref().flatten().next()?;
66 self.remaining -= 1;
67 Some(&e.pair)
68 }
69 fn size_hint(&self) -> (usize, Option<usize>) {
70 (self.remaining, Some(self.remaining))
71 }
72}
73
74impl DoubleEndedIterator for MapEntries<'_> {
75 fn next_back(&mut self) -> Option<Self::Item> {
76 let e = self.slots.by_ref().rev().flatten().next()?;
77 self.remaining -= 1;
78 Some(&e.pair)
79 }
80}
81
82impl ExactSizeIterator for MapEntries<'_> {}
83
84impl std::iter::FusedIterator for MapEntries<'_> {}
85
86impl std::fmt::Debug for MapEntries<'_> {
88 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89 f.debug_list().entries(self.clone()).finish()
90 }
91}
92
93impl MapData {
94 pub fn new() -> Self {
96 Self::default()
97 }
98
99 pub fn from_pairs(pairs: Vec<(Value, Value)>) -> Self {
101 let mut inner = MapInner {
102 slots: Vec::with_capacity(pairs.len()),
103 index: HashTable::with_capacity(pairs.len()),
104 live: 0,
105 bytes: 0,
106 };
107 for (k, v) in pairs {
108 inner.upsert(k, v);
109 }
110 Self(Arc::new(inner))
111 }
112
113 pub fn entries(&self) -> MapEntries<'_> {
115 MapEntries {
116 slots: self.0.slots.iter(),
117 remaining: self.0.live,
118 }
119 }
120
121 pub fn iter(&self) -> MapEntries<'_> {
123 self.entries()
124 }
125
126 pub fn len(&self) -> usize {
128 self.0.live
129 }
130
131 pub fn is_empty(&self) -> bool {
133 self.0.live == 0
134 }
135
136 pub fn into_entries(self) -> Vec<(Value, Value)> {
138 match Arc::try_unwrap(self.0) {
139 Ok(inner) => inner.slots.into_iter().flatten().map(|s| s.pair).collect(),
140 Err(shared) => shared
141 .slots
142 .iter()
143 .flatten()
144 .map(|s| s.pair.clone())
145 .collect(),
146 }
147 }
148
149 pub fn contains_key(&self, key: &Value) -> bool {
151 self.slot(key).is_some()
152 }
153
154 pub fn get(&self, key: &Value) -> Option<&Value> {
156 self.slot(key).map(|i| &self.0.entry(i).1)
157 }
158
159 pub(crate) fn slot(&self, key: &Value) -> Option<usize> {
161 self.0.find(hash_of(key), key)
162 }
163
164 pub(crate) fn slot_or_hash(&self, key: &Value) -> Result<usize, u64> {
167 let hash = hash_of(key);
168 self.0.find(hash, key).ok_or(hash)
169 }
170
171 pub(crate) fn compact_for_iteration(&mut self) {
174 if self.0.live != self.0.slots.len() {
175 Arc::make_mut(&mut self.0).compact();
176 }
177 }
178
179 pub(crate) fn entry_at(&self, i: usize) -> Option<&(Value, Value)> {
181 self.0.slots.get(i)?.as_ref().map(|s| &s.pair)
182 }
183
184 pub(crate) fn push_hashed(&mut self, hash: u64, key: Value, value: Value) {
186 Arc::make_mut(&mut self.0).push_entry(hash, key, value);
187 }
188
189 pub(crate) fn value_mut(&mut self, i: usize) -> &mut Value {
191 &mut Arc::make_mut(&mut self.0).slots[i]
192 .as_mut()
193 .expect("組がある")
194 .pair
195 .1
196 }
197
198 pub(crate) fn push_new(&mut self, key: Value, value: Value) -> bool {
200 let hash = hash_of(&key);
201 if self.0.find(hash, &key).is_some() {
202 return false;
203 }
204 Arc::make_mut(&mut self.0).push_entry(hash, key, value);
205 true
206 }
207
208 pub(crate) fn content_bytes(&self) -> usize {
210 self.0.bytes
211 }
212
213 pub(crate) fn adjust_bytes(&mut self, shrink: usize, grow: usize) {
216 let inner = Arc::make_mut(&mut self.0);
217 inner.bytes = (inner.bytes + grow).saturating_sub(shrink);
218 }
219
220 pub(crate) fn remove_at(&mut self, i: usize) -> (Value, Value) {
222 let inner = Arc::make_mut(&mut self.0);
223 let Slot { pair: (k, v), hash } = inner.slots[i].take().expect("組がある");
224 inner.live -= 1;
225 inner.bytes = inner
226 .bytes
227 .saturating_sub(k.approx_bytes() + v.approx_bytes());
228 inner
229 .index
230 .find_entry(hash, |&j| j == i)
231 .expect("索引にある")
232 .remove();
233 while matches!(inner.slots.last(), Some(None)) {
234 inner.slots.pop();
235 }
236 if inner.slots.len() - inner.live > inner.live.max(COMPACT_MIN) {
237 inner.compact();
238 }
239 (k, v)
240 }
241
242 #[doc(hidden)]
244 pub fn shares_storage_with(&self, other: &Self) -> bool {
245 Arc::ptr_eq(&self.0, &other.0)
246 }
247
248 pub(crate) fn clear(&mut self) {
250 self.0 = Arc::new(MapInner::default());
251 }
252
253 #[doc(hidden)]
255 pub fn is_consistent(&self) -> bool {
256 let inner = &*self.0;
257 let holes = inner.slots.len() - inner.live;
258 inner.bytes
259 == self
260 .entries()
261 .map(|(k, v)| k.approx_bytes() + v.approx_bytes())
262 .sum::<usize>()
263 && inner.slots.iter().flatten().count() == inner.live
264 && inner.index.len() == inner.live
265 && !matches!(inner.slots.last(), Some(None))
266 && holes <= inner.live.max(COMPACT_MIN)
267 && inner.slots.iter().enumerate().all(|(i, e)| {
268 e.as_ref()
269 .is_none_or(|s| s.hash == hash_of(&s.pair.0) && self.slot(&s.pair.0) == Some(i))
270 })
271 }
272}
273
274const COMPACT_MIN: usize = 8;
276
277impl MapInner {
278 fn entry(&self, i: usize) -> &(Value, Value) {
279 &self.slots[i].as_ref().expect("組がある").pair
280 }
281
282 fn find(&self, hash: u64, key: &Value) -> Option<usize> {
283 let slots = &self.slots;
284 self.index
285 .find(hash, |&i| {
286 slots[i]
287 .as_ref()
288 .is_some_and(|s| s.hash == hash && key_eq(&s.pair.0, key))
289 })
290 .copied()
291 }
292
293 fn upsert(&mut self, key: Value, value: Value) {
295 let hash = hash_of(&key);
296 match self.find(hash, &key) {
297 Some(i) => {
298 let slot = &mut self.slots[i].as_mut().expect("組がある").pair.1;
299 self.bytes =
300 (self.bytes + value.approx_bytes()).saturating_sub(slot.approx_bytes());
301 *slot = value;
302 }
303 None => self.push_entry(hash, key, value),
304 }
305 }
306
307 fn push_entry(&mut self, hash: u64, key: Value, value: Value) {
309 self.bytes += key.approx_bytes() + value.approx_bytes();
310 let slots = &self.slots;
311 self.index.insert_unique(hash, slots.len(), |&i| {
312 slots[i].as_ref().expect("組がある").hash
313 });
314 self.slots.push(Some(Slot {
315 pair: (key, value),
316 hash,
317 }));
318 self.live += 1;
319 }
320
321 fn compact(&mut self) {
323 self.slots.retain(Option::is_some);
324 self.index.clear();
325 let slots = &self.slots;
326 for (i, s) in slots.iter().flatten().enumerate() {
327 self.index
328 .insert_unique(s.hash, i, |&j| slots[j].as_ref().expect("組がある").hash);
329 }
330 }
331}
332
333fn hash_of(key: &Value) -> u64 {
334 use std::hash::{BuildHasher, Hasher};
335 let mut h = rustc_hash::FxBuildHasher.build_hasher();
336 hash_key(key, &mut h);
337 h.finish()
338}
339
340fn hash_key<H: std::hash::Hasher>(v: &Value, h: &mut H) {
342 use std::hash::Hash;
343 match v {
344 Value::Int(n) => (0u8, n).hash(h),
345 Value::Bool(b) => (1u8, b).hash(h),
346 Value::Str(t) => (2u8, &**t).hash(h),
347 Value::Identity(i) => (3u8, &i.id, &i.name).hash(h),
348 Value::Struct(st) => {
349 (4u8, &*st.ty, st.fields.len()).hash(h);
350 for (_, f) in st.fields.iter() {
351 hash_key(f, h);
352 }
353 }
354 Value::Enum(e) => {
355 (5u8, &*e.ty, &*e.variant, e.args.len()).hash(h);
356 for a in e.args.iter() {
357 hash_key(a, h);
358 }
359 }
360 other => (6u8, other.key_repr()).hash(h),
362 }
363}
364
365fn key_eq(a: &Value, b: &Value) -> bool {
367 match (a, b) {
368 (Value::Int(x), Value::Int(y)) => x == y,
369 (Value::Bool(x), Value::Bool(y)) => x == y,
370 (Value::Str(x), Value::Str(y)) => x == y,
371 (Value::Identity(x), Value::Identity(y)) => x.id == y.id && x.name == y.name,
372 (Value::Struct(s1), Value::Struct(s2)) => {
373 s1.ty == s2.ty
374 && s1.fields.len() == s2.fields.len()
375 && s1
376 .fields
377 .iter()
378 .zip(s2.fields.iter())
379 .all(|((_, x), (_, y))| key_eq(x, y))
380 }
381 (Value::Enum(e1), Value::Enum(e2)) => {
382 e1.ty == e2.ty
383 && e1.variant == e2.variant
384 && e1.args.len() == e2.args.len()
385 && e1
386 .args
387 .iter()
388 .zip(e2.args.iter())
389 .all(|(x, y)| key_eq(x, y))
390 }
391 (
392 Value::Int(_)
393 | Value::Bool(_)
394 | Value::Str(_)
395 | Value::Identity(_)
396 | Value::Struct(_)
397 | Value::Enum(_),
398 _,
399 )
400 | (
401 _,
402 Value::Int(_)
403 | Value::Bool(_)
404 | Value::Str(_)
405 | Value::Identity(_)
406 | Value::Struct(_)
407 | Value::Enum(_),
408 ) => false,
409 _ => a.key_repr() == b.key_repr(),
410 }
411}
412
413impl<'a> IntoIterator for &'a MapData {
414 type Item = &'a (Value, Value);
415 type IntoIter = MapEntries<'a>;
416 fn into_iter(self) -> Self::IntoIter {
417 self.entries()
418 }
419}
420
421impl From<Vec<(Value, Value)>> for MapData {
422 fn from(pairs: Vec<(Value, Value)>) -> Self {
423 Self::from_pairs(pairs)
424 }
425}
426
427impl PartialEq for MapData {
428 fn eq(&self, other: &Self) -> bool {
429 if Arc::ptr_eq(&self.0, &other.0) {
430 return true;
431 }
432 self.len() == other.len()
434 && self
435 .iter()
436 .all(|(k, v)| other.get(k).is_some_and(|v2| v == v2))
437 }
438}
439
440impl Serialize for MapData {
441 fn serialize<S: serde::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
442 ser.collect_seq(self.entries())
443 }
444}
445
446impl<'de> Deserialize<'de> for MapData {
447 fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
448 Ok(Self::from_pairs(Vec::<(Value, Value)>::deserialize(de)?))
449 }
450}
451
452#[cfg(test)]
453mod tests {
454 use super::*;
455
456 fn keys(m: &MapData) -> Vec<Value> {
457 m.entries().map(|(k, _)| k.clone()).collect()
458 }
459
460 #[test]
461 fn iteration_and_lookup_work_in_insertion_order_after_removal() {
462 let mut m = MapData::new();
463 for i in 0..10 {
464 assert!(m.push_new(Value::Int(i), Value::Int(i * 10)));
465 }
466 for i in [0, 5, 9, 3] {
467 let p = m.slot(&Value::Int(i)).unwrap();
468 m.remove_at(p);
469 assert!(m.is_consistent());
470 }
471 assert_eq!(keys(&m), [1, 2, 4, 6, 7, 8].map(Value::Int).to_vec());
472 assert_eq!(m.len(), 6);
473 assert_eq!(m.entries().len(), 6);
474 assert_eq!(m.entries().next_back().map(|e| &e.0), Some(&Value::Int(8)));
475 assert_eq!(m.get(&Value::Int(7)), Some(&Value::Int(70)));
476 assert!(!m.contains_key(&Value::Int(5)));
477 m.push_new(Value::Int(5), Value::Int(0));
478 assert_eq!(keys(&m).last(), Some(&Value::Int(5)));
479 assert!(m.is_consistent());
480 }
481
482 #[test]
483 fn compacts_when_holes_grow() {
484 let mut m = MapData::new();
485 for i in 0..100 {
486 m.push_new(Value::Int(i), Value::Int(i));
487 }
488 for i in 0..90 {
489 let p = m.slot(&Value::Int(i)).unwrap();
490 m.remove_at(p);
491 assert!(m.is_consistent(), "{i}");
492 }
493 assert!(m.0.slots.len() <= 10 + COMPACT_MIN);
494 assert_eq!(keys(&m), (90..100).map(Value::Int).collect::<Vec<_>>());
495 for i in 90..100 {
496 let p = m.slot(&Value::Int(i)).unwrap();
497 m.remove_at(p);
498 }
499 assert!(m.is_empty() && m.0.slots.is_empty() && m.is_consistent());
500 }
501
502 #[test]
503 fn removing_from_shared_clone_does_not_affect_original() {
504 let mut a = MapData::from_pairs((0..20).map(|i| (Value::Int(i), Value::Int(i))).collect());
505 let b = a.clone();
506 let p = a.slot(&Value::Int(3)).unwrap();
507 a.remove_at(p);
508 assert_eq!(b.len(), 20);
509 assert!(b.contains_key(&Value::Int(3)) && !a.contains_key(&Value::Int(3)));
510 assert!(a.is_consistent() && b.is_consistent());
511 }
512
513 #[test]
514 fn key_equality_matches_string_representation() {
515 let s = |t: &str| Value::Str(t.into());
516 let st = |name: &str, v: i64| {
517 Value::Struct(std::sync::Arc::new(StructValue {
518 ty: "点".into(),
519 fields: vec![(name.into(), Value::Int(v))],
520 }))
521 };
522 let vals = [
523 Value::Int(1),
524 Value::Bool(true),
525 s("1"),
526 s("i1;"),
527 st("x", 1),
528 st("y", 1),
529 st("x", 2),
530 Value::Float(1.0),
531 ];
532 for a in &vals {
533 for b in &vals {
534 let same = a.key_repr() == b.key_repr();
535 assert_eq!(key_eq(a, b), same, "{a:?} と {b:?}");
536 if same {
537 assert_eq!(hash_of(a), hash_of(b), "{a:?} と {b:?}");
538 }
539 }
540 }
541 }
542}