1use std::{
9 any::{Any, TypeId},
10 cell::RefCell,
11 fmt,
12 future::Future,
13 path::PathBuf,
14 pin::Pin,
15 rc::Rc,
16 sync::Arc,
17};
18
19use rustc_hash::FxHashMap;
20
21use super::{JsHost, Ret, Thrown, call::JsResult, module::ModuleFuture};
22use crate::{
23 JsonValue,
24 access::{Access, TrustedPaths},
25};
26
27#[derive(Clone, Default)]
33#[non_exhaustive]
34pub struct System {
35 pub access: Arc<Access>,
37 pub data_dir: Option<PathBuf>,
39 pub paths: TrustedPaths,
41 pub quotas: Quotas,
43 pub locals: Locals,
45 pub exit: Option<Rc<dyn Fn(i32)>>,
48 pub websocket: Option<Arc<dyn crate::websocket::WebSocketTransport>>,
50 pub filesystem: Option<Arc<dyn crate::filesystem::FileSystem>>,
52 pub os: crate::platform::Os,
54 pub refuse_connections: Option<RefuseConnections>,
59}
60
61pub type RefuseConnections = Arc<dyn Fn(&str) -> JsError + Send + Sync>;
66
67impl System {
68 pub fn new(
70 access: Arc<Access>,
71 data_dir: Option<PathBuf>,
72 paths: TrustedPaths,
73 quotas: Quotas,
74 ) -> Self {
75 Self {
76 access,
77 data_dir,
78 paths,
79 quotas,
80 locals: Locals::default(),
81 exit: None,
82 websocket: None,
83 filesystem: None,
84 os: crate::platform::Os::default(),
85 refuse_connections: None,
86 }
87 }
88
89 pub fn check_connection(&self, target: &str) -> Result<(), JsError> {
94 match &self.refuse_connections {
95 Some(refuse) => Err(refuse(target)),
96 None => Ok(()),
97 }
98 }
99
100 pub fn with_refuse_connections(mut self, refuse: Option<RefuseConnections>) -> Self {
103 self.refuse_connections = refuse;
104 self
105 }
106
107 pub fn with_websocket(
109 mut self,
110 websocket: Option<Arc<dyn crate::websocket::WebSocketTransport>>,
111 ) -> Self {
112 self.websocket = websocket;
113 self
114 }
115
116 pub fn with_filesystem(
118 mut self,
119 filesystem: Option<Arc<dyn crate::filesystem::FileSystem>>,
120 ) -> Self {
121 self.filesystem = filesystem;
122 self
123 }
124
125 pub fn with_os(mut self, os: crate::platform::Os) -> Self {
127 self.os = os;
128 self
129 }
130
131 pub fn with_locals(mut self, locals: Locals) -> Self {
133 self.locals = locals;
134 self
135 }
136
137 pub fn with_exit(mut self, exit: Option<Rc<dyn Fn(i32)>>) -> Self {
139 self.exit = exit;
140 self
141 }
142}
143
144pub trait Local: Default + 'static {
147 fn close(&self) {}
150}
151
152type Entry = (TypeId, Rc<dyn Any>, fn(&dyn Any));
153
154#[derive(Clone, Default)]
158pub struct Locals(Rc<RefCell<Vec<Entry>>>);
159
160impl Locals {
161 pub fn get<T: Local>(&self) -> Rc<T> {
163 let id = TypeId::of::<T>();
164 if let Some((_, local, _)) = self.0.borrow().iter().find(|(t, ..)| *t == id) {
165 return local
166 .clone()
167 .downcast()
168 .expect("the type it is filed under");
169 }
170 let local = Rc::new(T::default());
171 let close: fn(&dyn Any) = |local| {
172 if let Some(local) = local.downcast_ref::<T>() {
173 local.close();
174 }
175 };
176 self.0.borrow_mut().push((id, local.clone(), close));
177 local
178 }
179
180 pub fn close_all(&self) {
183 let locals = std::mem::take(&mut *self.0.borrow_mut());
184 for (_, local, close) in &locals {
185 close(&**local);
186 }
187 }
188}
189
190#[derive(Clone, Copy)]
194pub struct CallCx<'a> {
195 host: &'a dyn JsHost,
196}
197
198impl<'a> CallCx<'a> {
199 #[doc(hidden)]
200 pub fn new(host: &'a dyn JsHost) -> Self {
201 Self { host }
202 }
203
204 pub fn start(&self, work: impl Future<Output = ()> + 'static) {
207 self.host.start_task(Box::new(move || {
208 Box::pin(async move {
209 work.await;
210 Ok(Box::new(()) as Box<dyn super::ToJs>)
211 })
212 }));
213 }
214
215 pub fn on_cleanup(&self, f: impl FnOnce() + 'static) -> Cleanup {
221 Cleanup(Some(self.host.on_cleanup(Box::new(f))))
222 }
223}
224
225pub struct Cleanup(Option<Box<dyn FnOnce()>>);
228
229impl Cleanup {
230 pub fn release(mut self) {
232 if let Some(release) = self.0.take() {
233 release();
234 }
235 }
236}
237
238impl fmt::Debug for Cleanup {
239 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
240 f.write_str("Cleanup")
241 }
242}
243
244#[derive(Default)]
254#[non_exhaustive]
255pub struct Stop {
256 run: Rc<StopOnce>,
257}
258
259type StopOnce = RefCell<Option<Box<dyn FnOnce()>>>;
261
262impl Stop {
263 pub fn new(f: impl FnOnce() + 'static) -> Self {
265 Self {
266 run: Rc::new(RefCell::new(Some(Box::new(f)))),
267 }
268 }
269
270 fn run(run: &StopOnce) {
271 let f = run.borrow_mut().take();
273 if let Some(f) = f {
274 f();
275 }
276 }
277}
278
279impl fmt::Debug for Stop {
280 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
281 f.write_str("Stop")
282 }
283}
284
285impl Ret for Stop {
286 fn ts_type(_types: &mut super::TsTypes) -> String {
287 "() => void".into()
288 }
289
290 fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<super::JsOwned<'a>, super::PropError> {
291 let run = self.run;
292 let release = host.on_cleanup(Box::new({
293 let run = run.clone();
294 move || Self::run(&run)
295 }));
296 let release = RefCell::new(Some(release));
297 let stop = host.new_function(Box::new(move || {
298 let release = release.borrow_mut().take();
301 if let Some(release) = release {
302 release();
303 }
304 Self::run(&run);
305 }))?;
306 Ok(super::JsOwned::new(host, stop))
307 }
308}
309
310impl fmt::Debug for System {
311 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
312 f.debug_struct("System")
313 .field("data_dir", &self.data_dir)
314 .field("os", &self.os)
315 .finish_non_exhaustive()
316 }
317}
318
319#[derive(Clone, Default)]
323pub struct Quotas(Rc<RefCell<FxHashMap<&'static str, usize>>>);
324
325impl Quotas {
326 pub fn take(&self, kind: &'static str, max: usize) -> Option<Held> {
329 self.reserve(kind, 1, max)
330 }
331
332 pub fn reserve(&self, kind: &'static str, amount: usize, max: usize) -> Option<Held> {
335 let mut counts = self.0.borrow_mut();
336 let count = counts.entry(kind).or_default();
337 let total = count.checked_add(amount).filter(|&total| total <= max)?;
338 *count = total;
339 Some(Held {
340 quotas: self.clone(),
341 kind,
342 amount,
343 })
344 }
345
346 pub fn held(&self, kind: &'static str) -> usize {
348 self.0.borrow().get(kind).copied().unwrap_or(0)
349 }
350}
351
352pub struct Held {
355 quotas: Quotas,
356 kind: &'static str,
357 amount: usize,
358}
359
360impl Held {
361 pub fn amount(&self) -> usize {
363 self.amount
364 }
365}
366
367impl Drop for Held {
368 fn drop(&mut self) {
369 if let Some(count) = self.quotas.0.borrow_mut().get_mut(self.kind) {
370 *count -= self.amount;
371 }
372 }
373}
374
375impl fmt::Debug for Held {
376 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
377 write!(f, "Held({} {})", self.amount, self.kind)
378 }
379}
380
381#[must_use = "the work runs only when the call returns it"]
388pub struct Later<T>(Pin<Box<dyn Future<Output = Result<T, Thrown>>>>);
389
390impl<T: Ret + 'static> Later<T> {
391 pub fn new<E: IntoThrown>(work: impl Future<Output = Result<T, E>> + 'static) -> Self {
393 Self(Box::pin(async move {
394 work.await.map_err(IntoThrown::into_thrown)
395 }))
396 }
397
398 pub(crate) fn into_future(self) -> ModuleFuture {
399 Box::pin(async move {
400 let result: JsResult = match self.0.await {
401 Ok(v) => Ok(Box::new(v)),
402 Err(e) => Err(e),
403 };
404 result
405 })
406 }
407}
408
409impl<T> fmt::Debug for Later<T> {
410 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
411 f.write_str("Later")
412 }
413}
414
415#[derive(Debug, Clone, PartialEq, Eq)]
421pub enum JsError {
422 Type(String),
424 Range(String),
426 Error(String),
428 Fields(Box<ErrorFields>),
430}
431
432#[derive(Debug, Clone, Copy, PartialEq, Eq)]
434pub enum ErrorClass {
435 Type,
437 Range,
439 Error,
441}
442
443#[derive(Debug, Clone, PartialEq, Eq)]
446pub struct ErrorFields {
447 pub class: ErrorClass,
449 pub message: String,
451 pub fields: Vec<(&'static str, JsonValue)>,
453}
454
455impl ErrorFields {
456 fn of(class: ErrorClass, message: String) -> Self {
457 Self {
458 class,
459 message,
460 fields: Vec::new(),
461 }
462 }
463
464 pub fn field(&self, key: &str) -> Option<&JsonValue> {
466 self.fields.iter().find(|(k, _)| *k == key).map(|(_, v)| v)
467 }
468}
469
470impl JsError {
471 pub fn with(self, key: &'static str, value: impl Into<JsonValue>) -> Self {
474 let mut fields = match self {
475 JsError::Type(m) => ErrorFields::of(ErrorClass::Type, m),
476 JsError::Range(m) => ErrorFields::of(ErrorClass::Range, m),
477 JsError::Error(m) => ErrorFields::of(ErrorClass::Error, m),
478 JsError::Fields(f) => *f,
479 };
480 fields.fields.retain(|(k, _)| *k != key);
481 fields.fields.push((key, value.into()));
482 JsError::Fields(Box::new(fields))
483 }
484
485 pub fn with_code(self, code: &str) -> Self {
487 self.with("code", code)
488 }
489
490 pub fn access_denied(
496 message: impl Into<String>,
497 permission: &str,
498 resource: impl Into<String>,
499 ) -> Self {
500 JsError::Error(message.into())
501 .with_code(codes::ACCESS_DENIED)
502 .with("permission", permission)
503 .with("resource", resource.into())
504 }
505
506 pub fn message(&self) -> &str {
508 match self {
509 JsError::Type(m) | JsError::Range(m) | JsError::Error(m) => m,
510 JsError::Fields(f) => &f.message,
511 }
512 }
513
514 pub fn code(&self) -> Option<&str> {
516 match self {
517 JsError::Fields(f) => f.field("code").and_then(JsonValue::as_str),
518 _ => None,
519 }
520 }
521}
522
523pub mod codes {
527 pub const ACCESS_DENIED: &str = "ERR_ACCESS_DENIED";
530 pub const UNAVAILABLE: &str = "ERR_FEATURE_UNAVAILABLE_ON_PLATFORM";
532 pub const QUOTA_EXCEEDED: &str = "ERR_NSH_QUOTA_EXCEEDED";
535 pub const TIMED_OUT: &str = "ETIMEDOUT";
537 pub const HOST_ERROR: &str = "ERR_NSH_HOST_ERROR";
540}
541
542impl From<std::io::Error> for JsError {
546 fn from(error: std::io::Error) -> Self {
547 let message = error.to_string();
548 match io_code(&error) {
549 Some(code) => JsError::Error(message).with_code(code),
550 None => JsError::Error(message),
551 }
552 }
553}
554
555pub fn io_code(error: &std::io::Error) -> Option<&'static str> {
558 use std::io::ErrorKind as K;
559 #[cfg(unix)]
560 if let Some(code) = error.raw_os_error().and_then(errno_name) {
561 return Some(code);
562 }
563 Some(match error.kind() {
564 K::NotFound => "ENOENT",
565 K::PermissionDenied => "EACCES",
566 K::AlreadyExists => "EEXIST",
567 K::NotADirectory => "ENOTDIR",
568 K::IsADirectory => "EISDIR",
569 K::DirectoryNotEmpty => "ENOTEMPTY",
570 K::InvalidFilename => "ENAMETOOLONG",
571 K::ReadOnlyFilesystem => "EROFS",
572 K::CrossesDevices => "EXDEV",
573 K::StorageFull => "ENOSPC",
574 K::QuotaExceeded => "EDQUOT",
575 K::FileTooLarge => "EFBIG",
576 K::ResourceBusy => "EBUSY",
577 K::ExecutableFileBusy => "ETXTBSY",
578 K::Deadlock => "EDEADLK",
579 K::TooManyLinks => "EMLINK",
580 K::ArgumentListTooLong => "E2BIG",
581 K::Interrupted => "EINTR",
582 K::WouldBlock => "EAGAIN",
583 K::TimedOut => "ETIMEDOUT",
584 K::BrokenPipe => "EPIPE",
585 K::ConnectionRefused => "ECONNREFUSED",
586 K::ConnectionReset => "ECONNRESET",
587 K::ConnectionAborted => "ECONNABORTED",
588 K::NotConnected => "ENOTCONN",
589 K::AddrInUse => "EADDRINUSE",
590 K::AddrNotAvailable => "EADDRNOTAVAIL",
591 K::HostUnreachable => "EHOSTUNREACH",
592 K::NetworkUnreachable => "ENETUNREACH",
593 K::NetworkDown => "ENETDOWN",
594 K::InvalidInput => "EINVAL",
595 K::Unsupported => "ENOTSUP",
596 K::OutOfMemory => "ENOMEM",
597 _ => return None,
598 })
599}
600
601#[cfg(unix)]
604fn errno_name(errno: i32) -> Option<&'static str> {
605 let names: &[(i32, &str)] = &[
606 (libc::ENOENT, "ENOENT"),
607 (libc::EACCES, "EACCES"),
608 (libc::EPERM, "EPERM"),
609 (libc::EEXIST, "EEXIST"),
610 (libc::ENOTDIR, "ENOTDIR"),
611 (libc::EISDIR, "EISDIR"),
612 (libc::ENOTEMPTY, "ENOTEMPTY"),
613 (libc::ELOOP, "ELOOP"),
614 (libc::ENAMETOOLONG, "ENAMETOOLONG"),
615 (libc::EBADF, "EBADF"),
616 (libc::EBUSY, "EBUSY"),
617 (libc::EINVAL, "EINVAL"),
618 (libc::EMFILE, "EMFILE"),
619 (libc::ENFILE, "ENFILE"),
620 (libc::ENOSPC, "ENOSPC"),
621 (libc::EROFS, "EROFS"),
622 (libc::EXDEV, "EXDEV"),
623 (libc::EAGAIN, "EAGAIN"),
624 (libc::ENXIO, "ENXIO"),
625 (libc::ETXTBSY, "ETXTBSY"),
626 (libc::EFBIG, "EFBIG"),
627 (libc::EMLINK, "EMLINK"),
628 (libc::EPIPE, "EPIPE"),
629 (libc::ENOEXEC, "ENOEXEC"),
630 ];
631 names
632 .iter()
633 .find(|(n, _)| *n == errno)
634 .map(|(_, name)| *name)
635}
636
637pub trait IntoThrown {
640 fn into_thrown(self) -> Thrown;
642}
643
644impl<E: fmt::Display> IntoThrown for E {
645 fn into_thrown(self) -> Thrown {
646 Thrown::Error(self.to_string())
647 }
648}
649
650impl IntoThrown for JsError {
651 fn into_thrown(self) -> Thrown {
652 match self {
653 JsError::Type(m) => Thrown::Type(m),
654 JsError::Range(m) => Thrown::Range(m),
655 JsError::Error(m) => Thrown::Error(m),
656 JsError::Fields(f) => Thrown::Fields(f),
657 }
658 }
659}
660
661#[cfg(test)]
662mod tests {
663 use crate::{
664 JsonValue,
665 element::{JsValue, Registry, declarations, json_host},
666 prelude::*,
667 };
668
669 #[module]
670 struct Files;
671
672 #[module(flat)]
673 impl Files {
674 pub(crate) fn read(path: String, sys: System) -> Result<Later<Vec<u8>>, JsError> {
676 let _ = (path, sys);
677 Ok(Later::new(async { Ok::<_, String>(vec![1]) }))
678 }
679
680 pub(crate) fn write(sys: System, bytes: Vec<u8>) -> u32 {
682 let _ = sys;
683 bytes.len() as u32
684 }
685
686 pub(crate) fn watch(path: String, cx: CallCx<'_>) {
688 cx.on_cleanup(move || drop(path));
689 cx.start(async {});
690 }
691
692 pub(crate) fn listen() -> Stop {
694 Stop::new(|| {})
695 }
696
697 #[getter]
699 pub(crate) fn root(sys: System) -> Option<String> {
700 sys.data_dir.map(|d| d.display().to_string())
701 }
702 }
703
704 #[class]
705 struct Handle;
706
707 #[class]
708 impl Handle {
709 pub(crate) fn next(&self, sys: System, size: Option<u32>) -> Later<Option<Vec<u8>>> {
711 let _ = (sys, size);
712 Later::new(async { Ok::<_, String>(None) })
713 }
714
715 #[overload(fn(event: String, #[args(index, label)] f: Callback<(u32, String)>) -> Instance<Handle>)]
717 pub(crate) fn on(this: Instance<Self>, event: String, cx: CallCx<'_>) -> Instance<Self> {
718 let _ = (event, cx);
719 this
720 }
721 }
722
723 #[test]
724 fn bytes_are_uint8_arrays_tasks_promises_and_the_system_no_parameter() {
725 let mut registry = Registry::ui_set("test/system");
726 registry.module::<Files>().class::<Handle>();
727 let d = declarations(®istry, &[]);
728 assert!(
729 d.contains("function read(path: string): Promise<Uint8Array>;"),
730 "{d}"
731 );
732 assert!(
733 d.contains("function write(bytes: Uint8Array): number;"),
734 "{d}"
735 );
736 assert!(
737 d.contains("next(size?: number | null): Promise<Uint8Array | null>;"),
738 "{d}"
739 );
740 assert!(d.contains("function watch(path: string): void;"), "{d}");
741 assert!(d.contains("function listen(): () => void;"), "{d}");
742 assert!(
743 d.contains(" on(event: string, f: (index: number, label: string) => void): Handle;"),
744 "{d}"
745 );
746 assert!(!d.contains("function root"), "{d}");
748 }
749
750 #[test]
751 fn bytes_convert_from_and_to_js() {
752 let host = json_host::JsonHost::default();
753 let raw = host.value(serde_json::json!([0, 7, 255]));
754 let bytes = <Vec<u8>>::from_js(crate::element::JsIn::new(&host, raw)).unwrap();
755 assert_eq!(bytes, [0, 7, 255]);
756 let out = bytes.to_js(&host).unwrap();
757 assert_eq!(host.read(out), Some(serde_json::json!([0, 7, 255])));
758 let bad = host.value(JsonValue::from("x"));
759 assert!(<Vec<u8>>::from_js(crate::element::JsIn::new(&host, bad)).is_err());
760 }
761
762 #[test]
763 fn a_stop_is_a_function_that_runs_once() {
764 use crate::element::Ret;
765 let host = json_host::JsonHost::default();
766 let runs = std::rc::Rc::new(std::cell::Cell::new(0));
767 let stop = Stop::new({
768 let runs = runs.clone();
769 move || runs.set(runs.get() + 1)
770 });
771 let f = stop.into_js(&host).unwrap().into_raw();
772 assert_eq!(
773 crate::element::JsHost::kind(&host, f),
774 crate::element::JsKind::Function
775 );
776 assert_eq!(runs.get(), 0);
777 host.call(f);
778 host.call(f);
779 assert_eq!(runs.get(), 1);
780 }
781
782 #[derive(Debug, JsObject)]
783 #[prop(exact)]
784 struct Options {
785 recursive: Option<bool>,
786 #[prop(skip_none)]
787 note: Option<String>,
788 }
789
790 #[test]
791 fn times_are_dates_and_exact_objects_refuse_other_keys() {
792 let host = json_host::JsonHost::default();
793 let time = std::time::UNIX_EPOCH + std::time::Duration::from_millis(1500);
794 let out = time.to_js(&host).unwrap();
795 assert_eq!(host.read(out), Some(serde_json::json!({ "$date": 1500.0 })));
796 let date = host.value(serde_json::json!({ "$date": -250.0 }));
797 let back = std::time::SystemTime::from_js(crate::element::JsIn::new(&host, date)).unwrap();
798 assert_eq!(
799 std::time::UNIX_EPOCH
800 .duration_since(back)
801 .unwrap()
802 .as_millis(),
803 250
804 );
805 let options = host.value(serde_json::json!({ "recursive": true }));
806 let options = Options::from_js(crate::element::JsIn::new(&host, options)).unwrap();
807 assert_eq!(options.recursive, Some(true));
808 let shown = Options {
809 recursive: None,
810 note: None,
811 }
812 .to_js(&host)
813 .unwrap();
814 assert_eq!(
815 host.read(shown),
816 Some(serde_json::json!({ "recursive": null }))
817 );
818 let typo = host.value(serde_json::json!({ "recursive": true, "typo": 1 }));
819 let error = Options::from_js(crate::element::JsIn::new(&host, typo)).unwrap_err();
820 assert_eq!(error.0, "unknown field `typo`");
821 }
822
823 #[test]
824 fn errors_carry_node_s_codes_thrown_and_rejected() {
825 use super::{ErrorClass, JsError, io_code};
826 use crate::element::{IntoThrown, Thrown};
827 let missing = std::io::Error::from(std::io::ErrorKind::NotFound);
828 assert_eq!(io_code(&missing), Some("ENOENT"));
829 #[cfg(unix)]
830 assert_eq!(
831 io_code(&std::io::Error::from_raw_os_error(libc::ELOOP)),
832 Some("ELOOP")
833 );
834 assert_eq!(io_code(&std::io::Error::other("x")), None);
835 let error = JsError::Type("denied".into())
836 .with_code("EPERM")
837 .with_code("EACCES")
838 .with("path", "a.txt");
839 assert_eq!((error.message(), error.code()), ("denied", Some("EACCES")));
840 let Thrown::Fields(fields) = error.clone().into_thrown() else {
841 panic!("fields go with the error");
842 };
843 assert_eq!(fields.class, ErrorClass::Type);
844 assert_eq!(fields.fields.len(), 2);
845 assert_eq!(JsError::from(missing).code(), Some("ENOENT"));
846 let later = super::Later::<u32>::new(async { Err::<u32, _>(error) });
848 let runtime = tokio::runtime::Builder::new_current_thread()
849 .build()
850 .unwrap();
851 let Err(Thrown::Fields(rejected)) = runtime.block_on(later.into_future()) else {
852 panic!("a rejection with fields");
853 };
854 assert_eq!(rejected.field("path"), Some(&serde_json::json!("a.txt")));
855 let later = super::Later::<u32>::new(async { Err::<u32, _>("plain") });
857 assert!(matches!(
858 runtime.block_on(later.into_future()),
859 Err(Thrown::Error(m)) if m == "plain"
860 ));
861 }
862
863 #[test]
864 fn quotas_count_what_is_held() {
865 let quotas = super::Quotas::default();
866 let a = quotas.take("k", 2).unwrap();
867 let _b = quotas.take("k", 2).unwrap();
868 assert!(quotas.take("k", 2).is_none());
869 drop(a);
870 assert_eq!(quotas.held("k"), 1);
871 assert!(quotas.take("other", 1).is_some());
872 }
873
874 #[test]
875 fn quotas_reserve_amounts_up_to_their_limit() {
876 let quotas = super::Quotas::default();
877 let a = quotas.reserve("bytes", 40, 64).unwrap();
878 assert!(quotas.reserve("bytes", 25, 64).is_none());
879 let b = quotas.reserve("bytes", 24, 64).unwrap();
880 assert_eq!((quotas.held("bytes"), a.amount()), (64, 40));
881 assert!(quotas.reserve("bytes", usize::MAX, usize::MAX).is_none());
882 drop(a);
883 assert_eq!(quotas.held("bytes"), 24);
884 drop(b);
885 assert!(quotas.reserve("bytes", 64, 64).is_some());
886 }
887}