unityrs-core 1.0.0

Read and write Unity asset bundles, serialized files and typetrees.
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
//! The [`Meter`] of one open of an input, the memory account every open of
//! the input shares, what each lazy computation was granted on its own thread
//! ([`GrantScope`]), the [`Charge`] each grant is, and how many refusals of
//! the dependency pool each thread met ([`pool_refusals`]).

use std::cell::Cell;
use std::fmt;
use std::mem::size_of;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

use super::{ChargeError, Limits, heap_cost};
use crate::budget::{AllocError, BudgetExceeded, MemoryBudget, Permit, Reservation, Unbounded};
use crate::error::{LimitError, LimitKind};

/// The bytes an `Arc` of a `T` of `size` bytes asks for: the value and the
/// two reference counts.
const fn arc_bytes(size: usize) -> u64 {
    size as u64 + 2 * size_of::<usize>() as u64
}

/// What every open of one input holds: the memory account its meters share.
struct Account {
    used: AtomicU64,
    limit: u64,
    budget: Arc<dyn MemoryBudget>,
    what: Reservation,
}

/// An open's work past its allowance, as [`Meter::work_used_up`] reports
/// it: a status, not an error, so no refusal is made, or counted, until the
/// core refuses new work for it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct WorkPast {
    done: u64,
    allowance: u64,
}

const _: () = crate::send_sync::<WorkPast>();

impl WorkPast {
    /// The work counted.
    #[must_use]
    pub const fn done(&self) -> u64 {
        self.done
    }

    /// The allowance it passed.
    #[must_use]
    pub const fn allowance(&self) -> u64 {
        self.allowance
    }
}

/// One open of an input: what the input holds, against
/// [`Limits::max_input_memory`], and what this open has done, against
/// [`Limits::max_decode_work`] (module docs). Thread-safe: a lazily read
/// bundle's entries charge one meter from any thread. Shared as
/// `Arc<Meter>`; every [`Charge`] keeps it alive.
pub struct Meter {
    /// The input's memory, shared by every open of it ([`Self::reopen`]).
    account: Arc<Account>,
    /// Work done by this open ([`Limits::max_decode_work`]).
    work: AtomicU64,
    work_limit: u64,
    work_refusal: AtomicU64,
    /// Every byte this meter ever granted, never returned: what a lazy
    /// computation is measured by ([`crate::once::get_or_publish_result`]).
    granted: AtomicU64,
}

const _: () = crate::send_sync::<Meter>();

impl fmt::Debug for Meter {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Meter")
            .field("used", &self.used())
            .field("limit", &self.limit())
            .field("decoded", &self.decoded())
            .field("what", &self.reservation())
            .finish_non_exhaustive()
    }
}

impl Meter {
    /// Records one detected allocator refusal on this meter's budget and
    /// returns its provenance. Call only at detection, never in conversions.
    /// Arithmetic/count overflow must use the corresponding limit error.
    #[must_use]
    pub fn allocator_refused(&self, requested: u64) -> AllocError {
        let error = AllocError {
            requested,
            what: self.reservation(),
        };
        self.account.budget.allocator_refused(error);
        error
    }

    /// The heap an input's first meter takes itself, outside every charge,
    /// in glibc chunks ([`heap_cost`]): the meter and the memory account, each
    /// in its `Arc` (plan section 3.15's constant per input). Each
    /// [`Self::reopen`] adds [`Self::REOPEN_HEAP`].
    pub const OWN_HEAP: u64 = Self::REOPEN_HEAP + heap_cost(arc_bytes(size_of::<Account>()));

    /// The heap one more open's meter takes, in glibc chunks.
    pub const REOPEN_HEAP: u64 = heap_cost(arc_bytes(size_of::<Self>()));

    /// A meter of `limit` bytes whose charges are booked with `budget` as
    /// `what`, with no bound on decode work.
    #[must_use]
    pub fn new(limit: u64, budget: Arc<dyn MemoryBudget>, what: Reservation) -> Arc<Self> {
        Self::with_decode_work(limit, u64::MAX, budget, what)
    }

    /// A meter of `limit` bytes that also counts decode work up to
    /// `max_decode_work` bytes ([`Self::count_decode`]).
    #[must_use]
    pub fn with_decode_work(
        limit: u64,
        max_decode_work: u64,
        budget: Arc<dyn MemoryBudget>,
        what: Reservation,
    ) -> Arc<Self> {
        Arc::new(Self {
            account: Arc::new(Account {
                used: AtomicU64::new(0),
                limit,
                budget,
                what,
            }),
            work: AtomicU64::new(0),
            work_limit: max_decode_work,
            work_refusal: AtomicU64::new(0),
            granted: AtomicU64::new(0),
        })
    }

    /// The meter of one input loaded with `limits` and `budget`: its memory
    /// bound is [`Limits::max_input_memory`] and its decode-work bound
    /// [`Limits::max_decode_work`].
    #[must_use]
    pub fn for_input(
        limits: &Limits,
        budget: Arc<dyn MemoryBudget>,
        what: Reservation,
    ) -> Arc<Self> {
        Self::with_decode_work(
            limits.max_input_memory,
            limits.max_decode_work,
            budget,
            what,
        )
    }

    /// A meter for opening the same input again: it charges the same memory
    /// account, so everything every open holds counts against one
    /// [`Limits::max_input_memory`], and its work starts from zero with the
    /// same bound. The Environment opens an evicted dependency again on it
    /// (plan section 3.13). The old meter keeps its own count, so a handle
    /// of the old open that something still holds (a nested bundle a
    /// resource read kept) goes on counting against the old allowance, which
    /// nothing resets, and every open's work stays bounded.
    #[must_use]
    pub fn reopen(&self) -> Arc<Self> {
        Arc::new(Self {
            account: self.account.clone(),
            work: AtomicU64::new(0),
            work_limit: self.work_limit,
            work_refusal: AtomicU64::new(0),
            granted: AtomicU64::new(0),
        })
    }

    /// Separate work allowance on the same memory account, for caller-side export.
    #[must_use]
    pub fn work_scope(&self, limit: u64) -> Arc<Self> {
        Arc::new(Self {
            account: self.account.clone(),
            work: AtomicU64::new(0),
            work_limit: limit,
            work_refusal: AtomicU64::new(0),
            granted: AtomicU64::new(0),
        })
    }

    /// Work attempted by this scope, including its largest refused increment.
    #[must_use]
    pub fn attempted_work(&self) -> u64 {
        self.decoded()
            .max(self.work_refusal.load(Ordering::Acquire))
    }

    /// Whether `other` charges the same input's memory (one of them is a
    /// [`Self::reopen`] of the other, or they are the same meter).
    #[must_use]
    pub fn same_input(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.account, &other.account)
    }

    pub(crate) fn input_address(&self) -> usize {
        Arc::as_ptr(&self.account).addr()
    }

    /// Counts `bytes` of this open's work, refused when it would pass the
    /// bound ([`LimitKind::DecodeWork`]): one atomic check-and-add, so work
    /// counted at once from several threads never passes the bound. Work is
    /// never returned while the open lives, whatever its charges do. A
    /// refused decode counts nothing, so a smaller one may still fit; once
    /// work has passed the bound (`add_work`, unchecked), every later decode on
    /// this meter is refused. A
    /// [`crate::budget::DecodeBuf`] counts every write of a block's segment:
    /// one that needs a growth after the meter and the budget granted its
    /// memory and before it allocates, so a refused growth counts nothing,
    /// and a growth the count refuses returns its charge and allocates
    /// nothing.
    pub fn count_decode(&self, bytes: u64) -> Result<(), ChargeError> {
        self.count_work(bytes).map_err(ChargeError::Limit)
    }

    /// [`Self::count_decode`]'s check-and-add, its refusal the bound's
    /// [`LimitKind::DecodeWork`] error itself: what a walk's read or write
    /// counts its work with as it goes (`walk::OpenWork`).
    pub(crate) fn count_work(&self, bytes: u64) -> Result<(), LimitError> {
        let limit = self.work_limit;
        self.work
            .try_update(Ordering::AcqRel, Ordering::Acquire, |done| {
                done.checked_add(bytes).filter(|t| *t <= limit)
            })
            .map(|_| ())
            .map_err(|done| self.decode_refused(done, bytes))
    }

    /// Counts `bytes` of work done if the bound holds them, in one atomic
    /// check-and-add as [`Self::count_decode`], and whether it did. A `false`
    /// counts nothing and records no refusal: a direct read
    /// ([`crate::ObjectRef::emit_typetree`]) then leaves the object to the
    /// full reader, which meets the refusal itself.
    #[must_use]
    pub fn try_count_work(&self, bytes: u64) -> bool {
        let limit = self.work_limit;
        self.work
            .try_update(Ordering::AcqRel, Ordering::Acquire, |done| {
                done.checked_add(bytes).filter(|t| *t <= limit)
            })
            .is_ok()
    }

    /// Takes back `bytes` counted by [`Self::count_decode`] for a growth
    /// the allocator then failed (nothing was allocated).
    pub(crate) fn uncount_decode(&self, bytes: u64) {
        let _ = self
            .work
            .try_update(Ordering::AcqRel, Ordering::Acquire, |done| {
                Some(done.saturating_sub(bytes))
            });
    }

    /// Counts `bytes` of work already done, unchecked: what a lazy
    /// computation that ended unkept was granted
    /// ([`crate::once::get_or_publish_result`]), or a bundle entry's parse
    /// that ended in a kept error (`files::bundle`). The work is done whatever
    /// the bound says; what follows is refused ([`Self::work_used_up`]).
    pub(crate) fn add_work(&self, bytes: u64) {
        let _ = self
            .work
            .try_update(Ordering::AcqRel, Ordering::Acquire, |done| {
                Some(done.saturating_add(bytes))
            });
    }

    /// Whether this open's work has passed its allowance: the work done and
    /// the allowance when it has, `None` while it has not. A status, not an
    /// error: the core turns it into its refusal of new work
    /// ([`LimitKind::DecodeWork`]) where it refuses that work, through
    /// [`LimitError::refused`], which counts under CR8's test feature (round
    /// 4: this query returned the `LimitError` itself, uncounted, so a
    /// caller's code could hand the core a refusal no counter saw). The
    /// allowance is inclusive, as [`Self::count_decode`] admits work: work
    /// that lands exactly on it is within it, and what follows is refused by
    /// `count_decode` itself. Only work counted past the bound (`add_work`,
    /// unchecked: a detection's refused chunk, what a refused computation was
    /// granted) passes it, so the refusal's work is always past the bound
    /// (`limit DecodeWork: <work> > <bound>`).
    #[must_use]
    pub fn work_used_up(&self) -> Option<WorkPast> {
        let done = self.decoded();
        (done > self.work_limit).then_some(WorkPast {
            done,
            allowance: self.work_limit,
        })
    }

    /// The refusal the core makes of new work once the open's work has
    /// passed its allowance ([`Self::work_used_up`]), built by
    /// [`LimitError::refused`], which counts: what a read, a parse or a lazy
    /// computation meets then.
    #[inline]
    pub(crate) fn work_refused(&self) -> Option<LimitError> {
        let done = self.decoded();
        if done > self.work_limit {
            Some(LimitError::refused(
                LimitKind::DecodeWork,
                done,
                self.work_limit,
            ))
        } else {
            None
        }
    }

    fn decode_refused(&self, done: u64, bytes: u64) -> LimitError {
        let attempted = done.saturating_add(bytes);
        self.work_refusal.fetch_max(attempted, Ordering::AcqRel);
        LimitError::refused(LimitKind::DecodeWork, attempted, self.work_limit)
    }

    /// The work this open's allowance still holds.
    #[must_use]
    pub fn work_left(&self) -> u64 {
        self.work_limit.saturating_sub(self.decoded())
    }

    /// Work counted so far by this open.
    #[must_use]
    pub fn decoded(&self) -> u64 {
        self.work.load(Ordering::Acquire)
    }

    /// Every byte this meter has granted since it was made, returned or not.
    #[must_use]
    pub fn granted(&self) -> u64 {
        self.granted.load(Ordering::Acquire)
    }

    /// A meter with no bound and no budget, for data that is not an input's:
    /// a TPK's trees, a caller's `nodes=` rows, tests.
    #[must_use]
    pub fn unlimited() -> Arc<Self> {
        Self::new(u64::MAX, Arc::new(Unbounded), Reservation::Input)
    }

    /// Bytes charged to the input and not yet returned, by every open of it.
    #[must_use]
    pub fn used(&self) -> u64 {
        self.account.used.load(Ordering::Acquire)
    }

    /// The bound.
    #[must_use]
    pub fn limit(&self) -> u64 {
        self.account.limit
    }

    /// How the budget books this meter's charges.
    #[must_use]
    pub fn reservation(&self) -> Reservation {
        self.account.what
    }

    /// Charges `bytes`: against the bound, then with the budget. A refusal
    /// charges nothing.
    pub fn charge(self: &Arc<Self>, bytes: u64) -> Result<Charge, ChargeError> {
        let permit = self.reserve(bytes)?;
        Ok(Charge {
            meter: self.clone(),
            permit,
            more: Vec::new(),
        })
    }

    fn reserve(&self, bytes: u64) -> Result<Permit, ChargeError> {
        let account = &self.account;
        let limit = account.limit;
        account
            .used
            .try_update(Ordering::AcqRel, Ordering::Acquire, |used| {
                used.checked_add(bytes).filter(|t| *t <= limit)
            })
            .map_err(|used| {
                LimitError::refused(LimitKind::InputMemory, used.saturating_add(bytes), limit)
            })?;
        let permit = account
            .budget
            .try_reserve(bytes, account.what)
            .map_err(|e| {
                self.refund(bytes);
                crate::counters::budget(e.what);
                ChargeError::Budget(counted(e))
            })?;
        let _ = self
            .granted
            .try_update(Ordering::AcqRel, Ordering::Acquire, |g| {
                Some(g.saturating_add(bytes))
            });
        GrantScope::credit(self, bytes);
        Ok(permit)
    }

    fn refund(&self, bytes: u64) {
        // Saturating: a refund never takes the count below zero.
        let _ = self
            .account
            .used
            .try_update(Ordering::AcqRel, Ordering::Acquire, |used| {
                Some(used.saturating_sub(bytes))
            });
    }
}

thread_local! {
    /// How many refusals of [`Reservation::Dependency`] this thread met
    /// ([`pool_refusals`]).
    static POOL_REFUSALS: Cell<u64> = const { Cell::new(0) };
}

/// How many refusals of the dependency pool ([`Reservation::Dependency`])
/// this thread has met: the budget's, and an allocation refused on a
/// dependency's meter ([`refusal`]). The Environment's one retry of a pool
/// refusal tells by it whether the refusal it holds is one a retry already
/// met, or a later one (`env::registry::with_room`).
pub(crate) fn pool_refusals() -> u64 {
    POOL_REFUSALS.with(Cell::get)
}

/// `e`, counted in [`pool_refusals`] when it refuses the dependency pool.
fn counted(e: BudgetExceeded) -> BudgetExceeded {
    if e.what == Reservation::Dependency {
        POOL_REFUSALS.with(|n| n.set(n.get().wrapping_add(1)));
    }
    e
}

/// The refusal of `requested` bytes for `what` that the core makes itself
/// (an allocation the allocator refused after the budget granted it),
/// counted as a budget's is ([`pool_refusals`]).
pub(crate) fn refusal(requested: u64, what: Reservation) -> BudgetExceeded {
    counted(BudgetExceeded { requested, what })
}

/// How many lazy computations one thread tracks at once ([`GrantScope`]):
/// more than any nesting the core reaches (an entry parse inside a nested
/// bundle's, a compile inside a read, bounded by
/// [`Limits::max_container_depth`] and the walker's limits). A deeper scope
/// falls back to its meter's total grants, which errs towards stopping
/// early.
const GRANT_SCOPES: usize = 64;

/// The lazy computations running on this thread, innermost last: the
/// address of the meter each measures and what that meter granted on this
/// thread since the computation started. A fixed array, so tracking
/// allocates nothing (a counting-allocator test sees every heap byte).
struct GrantFrames {
    frames: [(usize, u64); GRANT_SCOPES],
    len: usize,
}

thread_local! {
    static GRANTS: std::cell::RefCell<GrantFrames> = const {
        std::cell::RefCell::new(GrantFrames {
            frames: [(0, 0); GRANT_SCOPES],
            len: 0,
        })
    };
}

/// What one lazy computation was granted by its meter on its own thread
/// while it ran ([`crate::once::get_or_publish_result`]): grants that other
/// threads made on the same meter meanwhile are theirs, not its (round 6:
/// the meter's total since the computation started was counted, so other
/// threads' successful work used up a failing computation's allowance).
/// Scopes nest; a grant counts for every open scope of its meter on the
/// thread, a nested computation's grants included.
pub(crate) struct GrantScope {
    /// The scope's frame index, or `None` past [`GRANT_SCOPES`] (then
    /// `fallback` holds the meter's total grants at the start).
    depth: Option<usize>,
    fallback: u64,
}

impl GrantScope {
    /// Opens a scope measuring `meter`'s grants on this thread.
    pub(crate) fn enter(meter: &Meter) -> Self {
        let addr = std::ptr::from_ref(meter).addr();
        let depth = GRANTS
            .try_with(|g| {
                let mut g = g.borrow_mut();
                let at = g.len;
                let frame = g.frames.get_mut(at)?;
                *frame = (addr, 0);
                g.len = at + 1;
                Some(at)
            })
            .ok()
            .flatten();
        Self {
            depth,
            fallback: meter.granted(),
        }
    }

    /// Closes the scope: what `meter` (the one it was opened on) granted on
    /// this thread while it was open.
    pub(crate) fn finish(self, meter: &Meter) -> u64 {
        match self.depth {
            Some(at) => GRANTS
                .try_with(|g| g.borrow().frames.get(at).map_or(0, |f| f.1))
                .unwrap_or(0),
            None => meter.granted().saturating_sub(self.fallback),
        }
        // `self` drops here and pops its frame.
    }

    /// Adds `bytes` granted by `meter` to every open scope of it on this
    /// thread.
    fn credit(meter: &Meter, bytes: u64) {
        let addr = std::ptr::from_ref(meter).addr();
        let _ = GRANTS.try_with(|g| {
            let mut g = g.borrow_mut();
            let len = g.len;
            for frame in g.frames.iter_mut().take(len) {
                if frame.0 == addr {
                    frame.1 = frame.1.saturating_add(bytes);
                }
            }
        });
    }
}

impl Drop for GrantScope {
    fn drop(&mut self) {
        if let Some(at) = self.depth {
            // Scopes close in reverse order of opening (a stack frame each),
            // so this is the innermost one.
            let _ = GRANTS.try_with(|g| g.borrow_mut().len = at);
        }
    }
}

/// Bytes charged to a [`Meter`] (and booked with its budget), returned when
/// the charge drops. It rides inside whatever it paid for.
///
/// **Bookkeeping.** A charge holds one [`Permit`] for its own meter, and
/// every charge it absorbs from that meter merges into it (bytes added,
/// permits merged by home), so a value built from any number of charged
/// tables keeps one record, however its budget books it. A charge absorbed
/// from *another* meter is kept as one record per distinct meter. Neither
/// grows with the input: one meter and one budget home (every budget of the
/// core: [`Unbounded`], [`crate::budget::Counting`]) allocate no record at
/// all (`tests/memory_model.rs` checks this under `Counting`).
#[must_use = "a charge returns its bytes when dropped"]
pub struct Charge {
    meter: Arc<Meter>,
    // The permit holds this meter's byte count as well as its homes. Keeping
    // one count leaves room for the inline phase home without growing Charge.
    permit: Permit,
    /// Absorbed charges of other meters, one per meter.
    more: Vec<Charge>,
}

const _: () = crate::send_sync::<Charge>();

impl fmt::Debug for Charge {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Charge")
            .field("bytes", &self.bytes())
            .field("more", &self.more.len())
            .finish_non_exhaustive()
    }
}

impl Charge {
    /// A charge of nothing on `meter`, to grow.
    pub fn zero(meter: &Arc<Meter>) -> Self {
        Self {
            meter: meter.clone(),
            permit: Permit::detached(0),
            more: Vec::new(),
        }
    }

    /// The bytes held, absorbed charges included.
    #[must_use]
    pub fn bytes(&self) -> u64 {
        self.more
            .iter()
            .fold(self.permit.bytes(), |n, c| n.saturating_add(c.bytes()))
    }

    /// The meter this charge is on.
    #[must_use]
    pub fn meter(&self) -> &Arc<Meter> {
        &self.meter
    }

    /// Charges `bytes` more to the same meter. A refusal changes nothing.
    pub fn grow(&mut self, bytes: u64) -> Result<(), ChargeError> {
        let permit = self.meter.reserve(bytes)?;
        self.permit.absorb(permit);
        Ok(())
    }

    /// Returns up to `bytes` of this meter's part now (what a buffer no
    /// longer holds).
    pub fn release(&mut self, bytes: u64) {
        let held = self.permit.bytes();
        let n = bytes.min(held);
        self.meter.refund(n);
        self.permit.shrink_to(held - n);
    }

    /// Takes `other` in: its bytes are returned when this charge drops. A
    /// charge of this meter merges into this one; a charge of another meter
    /// merges into the record this charge keeps for that meter (type docs).
    pub fn absorb(&mut self, mut other: Charge) {
        for c in std::mem::take(&mut other.more) {
            self.absorb(c);
        }
        if Arc::ptr_eq(&self.meter, &other.meter) {
            self.permit
                .absorb(std::mem::replace(&mut other.permit, Permit::detached(0)));
        } else if other.permit.bytes() > 0 {
            match self
                .more
                .iter_mut()
                .find(|c| Arc::ptr_eq(&c.meter, &other.meter))
            {
                Some(kept) => kept.absorb(other),
                None => self.more.push(other),
            }
        }
    }

    /// How many records this charge keeps besides its own: one per other
    /// meter it absorbed, plus its permit's ([`Permit::records`]).
    #[must_use]
    pub fn records(&self) -> usize {
        self.more
            .iter()
            .fold(self.permit.records(), |n, c| n + 1 + c.records())
    }
}

impl Drop for Charge {
    fn drop(&mut self) {
        // The permit drops after this, returning the budget's side.
        self.meter.refund(self.permit.bytes());
    }
}