legit-hamming 0.1.1

Exact Hamming radius search over 64-bit and 256-bit hashes in memory: a scan or multi-index hashing, chosen per query, checked against one reference, and a search service over snapshots
Documentation
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
//! A request's `options`, read and checked against the limits before anything else happens.
//!
//! The JSON is read with a reader of this request's own, not into a whole tree: a key given twice
//! is noted, a key the request doesn't take is noted and its value skipped, the one list a request
//! carries (`values`, `records` or `ids`) is counted whole but held only up to its bound, and
//! every other value is held only when it is a plain value, a list or object in its place being
//! skipped and marked. A task of a million values is thus told it holds too many without a million
//! values being held, while every check below sees what it would have seen in the whole tree.

use std::collections::HashSet;
use std::fmt;

use serde::de::{self, DeserializeSeed, IgnoredAny, MapAccess, SeqAccess, Visitor};
use serde_json::{Map, Value as Json};

use super::FORMAT;
use super::error::{ErrorType, ServiceError};
use super::limits::{Lane, Limits};
use super::log::ChangeName;
use crate::value::Value;

/// The keys a search's `options` may hold.
const SEARCH_KEYS: [&str; 8] = [
    "format",
    "index",
    "width",
    "radius",
    "values",
    "subset",
    "limit",
    "exclude_zero",
];

/// The keys a `stats` request's `options` may hold.
const STATS_KEYS: [&str; 3] = ["format", "index", "subset"];

/// The keys an `append` or `replace` task's `options` may hold: `subset` only to be refused with
/// a message of its own.
const CHANGE_KEYS: [&str; 5] = ["format", "index", "width", "records", "subset"];

/// The keys a `remove` task's `options` may hold.
const REMOVE_KEYS: [&str; 5] = ["format", "index", "width", "ids", "subset"];

/// The most characters of a name a message quotes.
const QUOTED: usize = 64;

/// Whether `name` is a valid index or subset name: 1 to 32 of `a-z`, `0-9`, `_` and `-`.
///
/// ```
/// use legit_hamming::service::is_valid_name;
///
/// assert!(is_valid_name("images-pdq"));
/// assert!(!is_valid_name("Images") && !is_valid_name("") && !is_valid_name("a.b"));
/// ```
#[must_use]
pub fn is_valid_name(name: &str) -> bool {
    (1..=32).contains(&name.len())
        && name
            .bytes()
            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'_' | b'-'))
}

/// `text` cut to its first `chars` characters, for quoting a name a request gave.
///
/// ```
/// assert_eq!(legit_hamming::service::shorten("abcdef", 3), "abc");
/// ```
#[must_use]
pub fn shorten(text: &str, chars: usize) -> &str {
    text.char_indices().nth(chars).map_or(text, |(end, _)| &text[..end])
}

/// The query values of a search, at their width.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Values {
    W64(Vec<u64>),
    W256(Vec<[u64; 4]>),
}

impl Values {
    pub(crate) fn len(&self) -> usize {
        match self {
            Self::W64(values) => values.len(),
            Self::W256(values) => values.len(),
        }
    }
}

/// A search's options, checked.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct SearchRequest {
    pub(crate) index: String,
    pub(crate) subset: Option<String>,
    pub(crate) width: u32,
    pub(crate) radius: u32,
    pub(crate) values: Values,
    pub(crate) limit: Option<usize>,
    pub(crate) exclude_zero: bool,
}

/// A `stats` request's options, checked.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct StatsRequest {
    pub(crate) index: String,
    pub(crate) subset: Option<String>,
}

/// The records of a change task, at their width, or the ids of a `remove`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ChangeRecords {
    W64(Vec<(u64, u64)>),
    W256(Vec<(u64, [u64; 4])>),
    Remove(Vec<u64>),
}

/// A change task's options, checked.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ChangeRequest {
    pub(crate) index: String,
    pub(crate) width: u32,
    pub(crate) name: ChangeName,
    pub(crate) records: ChangeRecords,
}

/// Read a change task's `options`: the byte bound, the JSON and its keys, then the width, the
/// number of records against its bound, and each record: an id and a value of the width for
/// `append` and `replace`, an id for `remove`, the ids rising. A message names a record by its
/// position, never its id or value.
pub(crate) fn change(text: &str, limits: &Limits, name: ChangeName) -> Result<ChangeRequest, ServiceError> {
    let keys: &[&str] = if name == ChangeName::Remove {
        &REMOVE_KEYS
    } else {
        &CHANGE_KEYS
    };
    let (key, most, what) = match name {
        ChangeName::Remove => ("ids", limits.max_remove_ids, "a list of ids"),
        _ => ("records", limits.max_change_records, "a list of `[id, hex]` pairs"),
    };
    let (object, listed) = object(text, limits, keys, Some((key, most)))?;
    let (index, subset) = names(&object)?;
    if subset.is_some() {
        return Err(ServiceError::invalid(
            "a change can't name a `subset`: subsets are snapshots only, replaced by the next export",
        ));
    }
    let width = match object.get("width") {
        Some(Json::Number(number)) if number.as_u64() == Some(64) => 64,
        Some(Json::Number(number)) if number.as_u64() == Some(256) => 256,
        Some(_) => return Err(ServiceError::invalid("`width` is 64 or 256")),
        None => return Err(ServiceError::invalid("`options` needs `width`, 64 or 256")),
    };
    let list = match object.get(key) {
        Some(Json::Array(list)) if !list.is_empty() => list,
        Some(Json::Array(_)) => return Err(ServiceError::invalid(format!("`{key}` is empty; give at least one"))),
        Some(_) => return Err(ServiceError::invalid(format!("`{key}` is {what}"))),
        None => return Err(ServiceError::invalid(format!("`options` needs `{key}`, {what}"))),
    };
    let count = listed.unwrap_or(list.len());
    if count > most {
        return Err(ServiceError::new(
            ErrorType::TooManyValues,
            format!(
                "the task holds {count} {key}; {} `{}` task takes at most {most}",
                if name.as_str().starts_with(['a', 'e', 'i', 'o', 'u']) {
                    "an"
                } else {
                    "a"
                },
                name.as_str()
            ),
        ));
    }
    let records = match (name, width) {
        (ChangeName::Remove, _) => {
            let ids = list
                .iter()
                .enumerate()
                .map(|(position, id)| {
                    id.as_u64().ok_or_else(|| {
                        ServiceError::invalid(format!(
                            "id {position} (from 0) isn't a whole number from 0 to 2^64 - 1"
                        ))
                    })
                })
                .collect::<Result<Vec<u64>, _>>()?;
            rising(ids.iter().copied())?;
            ChangeRecords::Remove(ids)
        }
        (_, 64) => ChangeRecords::W64(pairs(list)?),
        _ => ChangeRecords::W256(pairs(list)?),
    };
    Ok(ChangeRequest {
        index,
        width,
        name,
        records,
    })
}

/// Each record as an id and a value of `V`'s width, the ids rising.
fn pairs<V: Value>(list: &[Json]) -> Result<Vec<(u64, V)>, ServiceError> {
    let records = list
        .iter()
        .enumerate()
        .map(|(position, record)| match record.as_array().map(Vec::as_slice) {
            Some([id, Json::String(hex)]) => {
                let id = id.as_u64().ok_or_else(|| {
                    ServiceError::invalid(format!(
                        "record {position} (from 0): its id isn't a whole number from 0 to 2^64 - 1"
                    ))
                })?;
                let value = V::from_hex(hex).map_err(|_| {
                    ServiceError::invalid(format!(
                        "record {position} (from 0): its value isn't {} hex digits",
                        V::WORDS * 16
                    ))
                })?;
                Ok((id, value))
            }
            _ => Err(ServiceError::invalid(format!(
                "record {position} (from 0) isn't an `[id, hex]` pair"
            ))),
        })
        .collect::<Result<Vec<_>, _>>()?;
    rising(records.iter().map(|&(id, _)| id))?;
    Ok(records)
}

/// Whether `ids` rise strictly, as a task's must.
fn rising(ids: impl Iterator<Item = u64>) -> Result<(), ServiceError> {
    let mut previous = None;
    for (position, id) in ids.enumerate() {
        if previous.is_some_and(|previous| id <= previous) {
            return Err(ServiceError::invalid(format!(
                "id {position} (from 0) isn't above the id before it; a task's ids rise"
            )));
        }
        previous = Some(id);
    }
    Ok(())
}

/// Read a search's `options` on `lane`: the byte bound first, then the JSON, every key's type,
/// the number of values, the radius bound for the width, and each value's hex.
pub(crate) fn search(text: &str, limits: &Limits, lane: Lane) -> Result<SearchRequest, ServiceError> {
    let most = limits.max_values(lane);
    let (object, listed) = object(text, limits, &SEARCH_KEYS, Some(("values", most)))?;
    let (index, subset) = names(&object)?;
    let width = match object.get("width") {
        Some(Json::Number(number)) if number.as_u64() == Some(64) => 64,
        Some(Json::Number(number)) if number.as_u64() == Some(256) => 256,
        Some(_) => return Err(ServiceError::invalid("`width` is 64 or 256")),
        None => return Err(ServiceError::invalid("`options` needs `width`, 64 or 256")),
    };
    let radius = match object.get("radius") {
        Some(Json::Number(number)) => number
            .as_u64()
            .ok_or_else(|| ServiceError::invalid("`radius` is a whole number of at least 0"))?,
        Some(_) => return Err(ServiceError::invalid("`radius` is a whole number of at least 0")),
        None => return Err(ServiceError::invalid("`options` needs `radius`")),
    };
    // The optional keys' types, with the others', before the values are counted or decoded...
    let limit = match object.get("limit") {
        None | Some(Json::Null) => None,
        Some(Json::Number(number)) => match number.as_u64() {
            Some(limit) if limit > 0 => Some(usize::try_from(limit).unwrap_or(usize::MAX)),
            _ => return Err(ServiceError::invalid("`limit` is a whole number of at least 1")),
        },
        Some(_) => return Err(ServiceError::invalid("`limit` is a whole number of at least 1")),
    };
    let exclude_zero = match object.get("exclude_zero") {
        None | Some(Json::Null) => false,
        Some(Json::Bool(exclude)) => *exclude,
        Some(_) => return Err(ServiceError::invalid("`exclude_zero` is true or false")),
    };
    let values = match object.get("values") {
        Some(Json::Array(values)) if !values.is_empty() => values,
        Some(Json::Array(_)) => return Err(ServiceError::invalid("`values` holds no value; give at least one")),
        Some(_) => return Err(ServiceError::invalid("`values` is a list of hex strings")),
        None => return Err(ServiceError::invalid("`options` needs `values`, a list of hex strings")),
    };
    let count = listed.unwrap_or(values.len());
    if count > most {
        return Err(ServiceError::new(
            ErrorType::TooManyValues,
            format!(
                "the request holds {count} values; the {} lane takes at most {most}",
                lane.name()
            ),
        ));
    }
    let max_radius = limits.max_radius(width).unwrap_or(0);
    if radius > u64::from(max_radius) {
        let mut error = ServiceError::new(
            ErrorType::RadiusTooLarge,
            format!("radius {radius} is above {max_radius}, the largest this service searches at {width} bits"),
        );
        error.max_radius = Some(max_radius);
        return Err(error);
    }
    let values = if width == 64 {
        Values::W64(parse_values(values)?)
    } else {
        Values::W256(parse_values(values)?)
    };
    Ok(SearchRequest {
        index,
        subset,
        width,
        radius: u32::try_from(radius).unwrap_or(u32::MAX),
        values,
        limit,
        exclude_zero,
    })
}

/// Read a `stats` request's `options`.
pub(crate) fn stats(text: &str, limits: &Limits) -> Result<StatsRequest, ServiceError> {
    let (object, _) = object(text, limits, &STATS_KEYS, None)?;
    let (index, subset) = names(&object)?;
    Ok(StatsRequest { index, subset })
}

/// The `options` as a JSON object of the `allowed` keys, each given once, naming this contract's
/// `format`; with `list`, a key and its bound, also how many elements that key's list holds, of
/// which the object keeps the first `bound`.
fn object(
    text: &str,
    limits: &Limits,
    allowed: &[&str],
    list: Option<(&str, usize)>,
) -> Result<(Map<String, Json>, Option<usize>), ServiceError> {
    // Measured before it's parsed...
    if text.len() > limits.max_options_bytes {
        return Err(ServiceError::invalid(format!(
            "`options` is {} bytes of JSON; it may be at most {}",
            text.len(),
            limits.max_options_bytes
        )));
    }
    if text.trim().is_empty() {
        return Err(ServiceError::invalid("the request has no `options`"));
    }
    let mut json = serde_json::Deserializer::from_str(text);
    // Anything but white space after the object is a syntax error, as a whole parse finds it...
    let seed = OptionsSeed { allowed, list };
    let read = match seed.deserialize(&mut json).and_then(|read| json.end().map(|()| read)) {
        Ok(read) => read,
        Err(error) => return Err(ServiceError::invalid(format!("`options` isn't JSON: {error}"))),
    };
    let Some(read) = read else {
        return Err(ServiceError::invalid("`options` is a JSON object"));
    };
    if let Some(key) = read.twice {
        return Err(ServiceError::invalid(format!(
            "`options` gives the key `{}` twice; each key is given once",
            shorten(&key, QUOTED)
        )));
    }
    if let Some(key) = read.unknown {
        return Err(ServiceError::invalid(format!(
            "`options` has a key `{}` this request doesn't take; it takes `{}`",
            shorten(&key, QUOTED),
            allowed.join("`, `")
        )));
    }
    let object = read.object;
    let listed = read.listed;
    match object.get("format") {
        Some(Json::Number(number)) if number.as_u64() == Some(u64::from(FORMAT)) => Ok((object, listed)),
        Some(_) => Err(ServiceError::invalid(format!(
            "`format` is {FORMAT}, the only version of the options this service reads"
        ))),
        None => Err(ServiceError::invalid(format!("`options` needs `format`: {FORMAT}"))),
    }
}

/// The `index` and optional `subset` names, as strings. Whether they are served is checked later.
fn names(object: &Map<String, Json>) -> Result<(String, Option<String>), ServiceError> {
    let index = match object.get("index") {
        Some(Json::String(index)) => index.clone(),
        Some(_) => return Err(ServiceError::invalid("`index` is a name")),
        None => return Err(ServiceError::invalid("`options` needs `index`, the index to search")),
    };
    let subset = match object.get("subset") {
        None | Some(Json::Null) => None,
        Some(Json::String(subset)) => Some(subset.clone()),
        Some(_) => return Err(ServiceError::invalid("`subset` is a name")),
    };
    Ok((index, subset))
}

/// Each value as hex of `V`'s width. A message names a value by its position, never its text.
fn parse_values<V: Value>(values: &[Json]) -> Result<Vec<V>, ServiceError> {
    values
        .iter()
        .enumerate()
        .map(|(position, value)| {
            let digits = V::WORDS * 16;
            let wrong = match value {
                Json::String(hex) => match V::from_hex(hex) {
                    Ok(value) => return Ok(value),
                    Err(_) if hex.chars().count() != digits => format!("is {} characters long", hex.chars().count()),
                    Err(_) => "holds a character that isn't a hex digit".to_owned(),
                },
                _ => "isn't a string".to_owned(),
            };
            Err(ServiceError::invalid(format!(
                "`values[{position}]` {wrong}; a value at this width is {digits} hex digits"
            )))
        })
        .collect()
}

/// What reading `options` found: its keys, each value as the checks read it, the first key given
/// twice, the first key the request doesn't take, and how many elements the request's list holds.
struct Read {
    object: Map<String, Json>,
    twice: Option<String>,
    unknown: Option<String>,
    listed: Option<usize>,
}

/// The elements of a list's element that are held: enough to tell an `[id, hex]` pair from a
/// longer list.
const ELEMENT_KEEP: usize = 3;

/// Reads `options` as [`Read`], or `None` when it isn't a JSON object. Only the keys `allowed` are
/// held, and of them only the plain values; `list`, a key and its bound, is the list held to that
/// bound and counted whole.
struct OptionsSeed<'a> {
    allowed: &'a [&'a str],
    list: Option<(&'a str, usize)>,
}

impl<'de> DeserializeSeed<'de> for OptionsSeed<'_> {
    type Value = Option<Read>;

    fn deserialize<D: de::Deserializer<'de>>(self, deserializer: D) -> Result<Self::Value, D::Error> {
        deserializer.deserialize_any(self)
    }
}

impl<'de> Visitor<'de> for OptionsSeed<'_> {
    type Value = Option<Read>;

    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("a JSON object")
    }

    fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
        let mut read = Read {
            object: Map::new(),
            twice: None,
            unknown: None,
            listed: None,
        };
        // Only the keys the request takes are remembered, so a run of other keys costs nothing...
        let mut seen: HashSet<String> = HashSet::new();
        while let Some(key) = map.next_key::<String>()? {
            if !self.allowed.contains(&key.as_str()) {
                read.unknown.get_or_insert(key);
                map.next_value::<IgnoredAny>()?;
            } else if seen.contains(&key) {
                read.twice.get_or_insert(key);
                map.next_value::<IgnoredAny>()?;
            } else {
                let shape = match self.list {
                    Some((list, bound)) if list == key => Shallow { levels: 2, keep: bound },
                    _ => Shallow { levels: 0, keep: 0 },
                };
                let (value, count) = map.next_value_seed(shape)?;
                if self.list.is_some_and(|(list, _)| list == key) {
                    read.listed = count;
                }
                seen.insert(key.clone());
                read.object.insert(key, value);
            }
        }
        Ok(Some(read))
    }

    fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
        while seq.next_element::<IgnoredAny>()?.is_some() {}
        Ok(None)
    }

    fn visit_bool<E: de::Error>(self, _: bool) -> Result<Self::Value, E> {
        Ok(None)
    }

    fn visit_i64<E: de::Error>(self, _: i64) -> Result<Self::Value, E> {
        Ok(None)
    }

    fn visit_u64<E: de::Error>(self, _: u64) -> Result<Self::Value, E> {
        Ok(None)
    }

    fn visit_f64<E: de::Error>(self, _: f64) -> Result<Self::Value, E> {
        Ok(None)
    }

    fn visit_str<E: de::Error>(self, _: &str) -> Result<Self::Value, E> {
        Ok(None)
    }

    fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
        Ok(None)
    }
}

/// Reads a value as the checks need it: a plain value as it is; a list, `levels` deep, as its
/// first `keep` elements, each read one level less deep, and how many it holds; and anything
/// deeper, or an object, skipped and given as an empty list or object of the same kind, which no
/// check takes for a value of its key.
#[derive(Clone, Copy)]
struct Shallow {
    levels: u8,
    keep: usize,
}

impl<'de> DeserializeSeed<'de> for Shallow {
    type Value = (Json, Option<usize>);

    fn deserialize<D: de::Deserializer<'de>>(self, deserializer: D) -> Result<Self::Value, D::Error> {
        deserializer.deserialize_any(self)
    }
}

impl<'de> Visitor<'de> for Shallow {
    type Value = (Json, Option<usize>);

    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("a JSON value")
    }

    fn visit_bool<E: de::Error>(self, value: bool) -> Result<Self::Value, E> {
        Ok((Json::Bool(value), None))
    }

    fn visit_i64<E: de::Error>(self, value: i64) -> Result<Self::Value, E> {
        Ok((Json::from(value), None))
    }

    fn visit_u64<E: de::Error>(self, value: u64) -> Result<Self::Value, E> {
        Ok((Json::from(value), None))
    }

    fn visit_f64<E: de::Error>(self, value: f64) -> Result<Self::Value, E> {
        Ok((Json::from(value), None))
    }

    fn visit_str<E: de::Error>(self, value: &str) -> Result<Self::Value, E> {
        Ok((Json::String(value.to_owned()), None))
    }

    fn visit_string<E: de::Error>(self, value: String) -> Result<Self::Value, E> {
        Ok((Json::String(value), None))
    }

    fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
        Ok((Json::Null, None))
    }

    fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
        let mut held = Vec::new();
        let mut count = 0usize;
        loop {
            if self.levels > 0 && count < self.keep {
                let element = Self {
                    levels: self.levels - 1,
                    keep: ELEMENT_KEEP,
                };
                match seq.next_element_seed(element)? {
                    Some((value, _)) => held.push(value),
                    None => break,
                }
            } else if seq.next_element::<IgnoredAny>()?.is_none() {
                break;
            }
            count = count.saturating_add(1);
        }
        Ok((Json::Array(held), Some(count)))
    }

    fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
        while map.next_entry::<IgnoredAny, IgnoredAny>()?.is_some() {}
        Ok((Json::Object(Map::new()), None))
    }
}

/// The `unknown_index` or `unknown_subset` error for a name: quoted, shortened to 64 characters.
pub(crate) fn unknown(error_type: ErrorType, what: &str, name: &str) -> ServiceError {
    ServiceError::new(
        error_type,
        format!("this service serves no {what} `{}`", shorten(name, QUOTED)),
    )
}

#[cfg(test)]
mod tests {
    use std::alloc::{GlobalAlloc, Layout, System};
    use std::cell::Cell;

    use super::*;

    /// The system allocator, counting the bytes each thread asks of it.
    struct Counting;

    thread_local! {
        static ALLOCATED: Cell<usize> = const { Cell::new(0) };
    }

    #[expect(
        unsafe_code,
        reason = "a global allocator, which passes each call on to the system's"
    )]
    // SAFETY: every call is passed on to `System` unchanged; counting touches only a thread-local
    // `Cell`, which neither allocates nor runs a destructor.
    unsafe impl GlobalAlloc for Counting {
        unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
            ALLOCATED.with(|allocated| allocated.set(allocated.get().saturating_add(layout.size())));
            // SAFETY: the caller's contract, passed on...
            unsafe { System.alloc(layout) }
        }

        unsafe fn dealloc(&self, pointer: *mut u8, layout: Layout) {
            // SAFETY: the caller's contract, passed on...
            unsafe { System.dealloc(pointer, layout) }
        }

        unsafe fn realloc(&self, pointer: *mut u8, layout: Layout, size: usize) -> *mut u8 {
            ALLOCATED.with(|allocated| allocated.set(allocated.get().saturating_add(size)));
            // SAFETY: the caller's contract, passed on...
            unsafe { System.realloc(pointer, layout, size) }
        }
    }

    #[global_allocator]
    static ALLOCATOR: Counting = Counting;

    /// The bytes `work` asks the allocator for on this thread.
    fn allocated(work: impl FnOnce()) -> usize {
        let before = ALLOCATED.with(Cell::get);
        work();
        ALLOCATED.with(Cell::get) - before
    }

    #[test]
    fn a_task_of_a_million_values_is_refused_without_holding_them() {
        let limits = Limits::new();
        // Just under the 1 MiB bound: about half a million values on a lane that takes one...
        let values = vec!["0"; (limits.max_options_bytes - 100) / 2].join(",");
        let text = format!(r#"{{"format":1,"index":"images","width":64,"radius":2,"values":[{values}]}}"#);
        assert!(text.len() <= limits.max_options_bytes);
        let mut refused = None;
        let bytes = allocated(|| refused = Some(search(&text, &limits, Lane::Fast)));
        let error = refused.expect("ran").expect_err("refused");
        assert_eq!(error.error_type, ErrorType::TooManyValues);
        assert!(
            error
                .message
                .contains(&format!("{}", (limits.max_options_bytes - 100) / 2))
        );
        // A whole tree of it takes hundreds of times more...
        let tree = allocated(|| drop(serde_json::from_str::<Json>(&text)));
        assert!(bytes < 64 << 10, "{bytes} bytes held to refuse it; a tree takes {tree}");
        assert!(tree > 100 * bytes);
        // The same for a change task's records, and for a key the request doesn't take...
        let records = vec![r#"[1,"0000000000000000"]"#; 40_000].join(",");
        let text = format!(r#"{{"format":1,"index":"images","width":64,"records":[{records}]}}"#);
        let bytes = allocated(|| {
            let error = change(&text, &limits, ChangeName::Append).expect_err("refused");
            assert_eq!(error.error_type, ErrorType::TooManyValues);
        });
        // The first 1,000 pairs, the most a task takes, are held; not the other 39,000...
        let tree = allocated(|| drop(serde_json::from_str::<Json>(&text)));
        assert!(
            bytes < 512 << 10 && tree > 20 * bytes,
            "{bytes} bytes held to refuse it; a tree takes {tree}"
        );
        let text = format!(r#"{{"format":1,"index":"images","width":64,"radius":2,"values":[],"other":[{values}]}}"#);
        let bytes = allocated(|| {
            let error = search(&text, &limits, Lane::Bulk).expect_err("refused");
            assert!(error.message.contains("`other`"));
        });
        assert!(bytes < 64 << 10, "{bytes} bytes held to refuse it");
    }

    #[test]
    fn a_value_out_of_its_place_is_read_as_the_wrong_type_it_is() {
        let limits = Limits::new();
        let cases = [
            (r#""width":[64]"#, "`width` is 64 or 256"),
            (r#""width":{"a":64}"#, "`width` is 64 or 256"),
            (r#""radius":[1]"#, "`radius` is a whole number"),
            (r#""limit":[[2]]"#, "`limit` is a whole number"),
            (r#""limit":1.5"#, "`limit` is a whole number"),
            (r#""exclude_zero":[]"#, "`exclude_zero` is true or false"),
            (r#""subset":["a"]"#, "`subset` is a name"),
        ];
        for (field, message) in cases {
            let mut object: Map<String, Json> =
                serde_json::from_str(r#"{"format":1,"index":"images","width":64,"radius":2,"values":["0"]}"#)
                    .expect("JSON");
            let (key, value) = field.split_once(':').expect("a field");
            object.insert(
                serde_json::from_str(key).expect("a key"),
                serde_json::from_str(value).expect("a value"),
            );
            let text = Json::Object(object).to_string();
            let error = search(&text, &limits, Lane::Bulk).expect_err("refused");
            assert!(error.message.contains(message), "{field}: {}", error.message);
        }
        // A pair that holds more than an id and a value, or a value that isn't text...
        for records in [
            r#"[[1,"0000000000000000",3]]"#,
            r#"[[1,["0000000000000000"]]]"#,
            r#"[{"id":1}]"#,
        ] {
            let text = format!(r#"{{"format":1,"index":"images","width":64,"records":{records}}}"#);
            let error = change(&text, &limits, ChangeName::Replace).expect_err("refused");
            assert!(
                error.message.contains("isn't an `[id, hex]` pair"),
                "{records}: {}",
                error.message
            );
        }
        let error = change(
            r#"{"format":1,"index":"images","width":64,"ids":[[1]]}"#,
            &limits,
            ChangeName::Remove,
        )
        .expect_err("refused");
        assert!(error.message.contains("isn't a whole number"), "{}", error.message);
    }
}