allocative/impls/std/
cell.rs

1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under both the MIT license found in the
5 * LICENSE-MIT file in the root directory of this source tree and the Apache
6 * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
7 * of this source tree.
8 */
9
10use std::cell::OnceCell;
11use std::cell::RefCell;
12use std::sync::OnceLock;
13
14use crate::impls::common::DATA_NAME;
15use crate::Allocative;
16use crate::Visitor;
17
18impl<T: Allocative> Allocative for RefCell<T> {
19    fn visit<'a, 'b: 'a>(&self, visitor: &'a mut Visitor<'b>) {
20        let mut visitor = visitor.enter_self_sized::<Self>();
21        if let Ok(v) = self.try_borrow() {
22            visitor.visit_field(DATA_NAME, &*v);
23        }
24        visitor.exit();
25    }
26}
27
28impl<T: Allocative> Allocative for OnceCell<T> {
29    fn visit<'a, 'b: 'a>(&self, visitor: &'a mut Visitor<'b>) {
30        let mut visitor = visitor.enter_self_sized::<Self>();
31        if let Some(v) = self.get() {
32            visitor.visit_field::<T>(DATA_NAME, v);
33        }
34        visitor.exit();
35    }
36}
37
38impl<T: Allocative> Allocative for OnceLock<T> {
39    fn visit<'a, 'b: 'a>(&self, visitor: &'a mut Visitor<'b>) {
40        let mut visitor = visitor.enter_self_sized::<Self>();
41        if let Some(v) = self.get() {
42            visitor.visit_field::<T>(DATA_NAME, v);
43        }
44        visitor.exit();
45    }
46}
47
48#[cfg(test)]
49mod tests {
50    use std::cell::OnceCell;
51    use std::cell::RefCell;
52
53    use crate::golden::golden_test;
54
55    #[test]
56    fn test_default() {
57        golden_test!(&RefCell::new("abc".to_owned()))
58    }
59
60    #[test]
61    fn test_borrowed() {
62        let cell = RefCell::new("abc".to_owned());
63        let _lock = cell.borrow_mut();
64        golden_test!(&cell)
65    }
66
67    #[test]
68    fn test_once_cell() {
69        let cell = OnceCell::new();
70        cell.set("abc".to_owned()).unwrap();
71        golden_test!(&cell)
72    }
73}