embedder_traits/
user_content_manager.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;
6
7use malloc_size_of::MallocSizeOfOps;
8use malloc_size_of_derive::MallocSizeOf;
9use serde::{Deserialize, Serialize};
10
11#[derive(Clone, Debug, Default, Deserialize, MallocSizeOf, Serialize)]
12pub struct UserContentManager {
13    user_scripts: Vec<UserScript>,
14}
15
16impl UserContentManager {
17    pub fn new() -> Self {
18        UserContentManager::default()
19    }
20
21    pub fn add_script(&mut self, script: impl Into<UserScript>) {
22        self.user_scripts.push(script.into());
23    }
24
25    pub fn scripts(&self) -> &[UserScript] {
26        &self.user_scripts
27    }
28}
29
30#[derive(Clone, Debug, Deserialize, Serialize)]
31pub struct UserScript {
32    pub script: String,
33    pub source_file: Option<PathBuf>,
34}
35
36// Maybe we should implement `MallocSizeOf` for `PathBuf` in `malloc_size_of` crate?
37impl malloc_size_of::MallocSizeOf for UserScript {
38    fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
39        let mut sum = 0;
40        sum += self.script.size_of(ops);
41        if let Some(path) = &self.source_file {
42            sum += unsafe { ops.malloc_size_of(path.as_path()) };
43        }
44        sum
45    }
46}
47
48impl<T: Into<String>> From<T> for UserScript {
49    fn from(script: T) -> Self {
50        UserScript {
51            script: script.into(),
52            source_file: None,
53        }
54    }
55}