embedder_traits/
user_contents.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::path::PathBuf;
6use std::sync::atomic::{AtomicU32, Ordering};
7
8use malloc_size_of::MallocSizeOfOps;
9use malloc_size_of_derive::MallocSizeOf;
10use serde::{Deserialize, Serialize};
11
12static USER_CONTENT_MANAGER_ID: AtomicU32 = AtomicU32::new(1);
13
14#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
15pub struct UserContentManagerId(u32);
16
17impl UserContentManagerId {
18    pub fn next() -> Self {
19        Self(USER_CONTENT_MANAGER_ID.fetch_add(1, Ordering::Relaxed))
20    }
21}
22
23#[derive(Clone, Debug, Default, Deserialize, MallocSizeOf, Serialize)]
24pub struct UserContents {
25    pub scripts: Vec<UserScript>,
26}
27
28impl UserContents {
29    pub fn new() -> Self {
30        UserContents::default()
31    }
32}
33
34#[derive(Clone, Debug, Deserialize, Serialize)]
35pub struct UserScript {
36    pub script: String,
37    pub source_file: Option<PathBuf>,
38}
39
40// Maybe we should implement `MallocSizeOf` for `PathBuf` in `malloc_size_of` crate?
41impl malloc_size_of::MallocSizeOf for UserScript {
42    fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
43        let mut sum = 0;
44        sum += self.script.size_of(ops);
45        if let Some(path) = &self.source_file {
46            sum += unsafe { ops.malloc_size_of(path.as_path()) };
47        }
48        sum
49    }
50}
51
52impl<T: Into<String>> From<T> for UserScript {
53    fn from(script: T) -> Self {
54        UserScript {
55            script: script.into(),
56            source_file: None,
57        }
58    }
59}