Skip to main content

servo_base/
lib.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
5#![deny(unsafe_code)]
6
7//! A crate to hold very common types in Servo.
8//!
9//! You should almost never need to add a data type to this crate. Instead look for
10//! a more shared crate that has fewer dependents.
11
12pub mod cross_process_instant;
13pub mod generic_channel;
14pub mod id;
15// Bao addition (BCE-20260628-002): thread-local RouterProxy for per-instance
16// IPC routing. Upstream removed this module; Bao's servo_base consumers
17// (net-traits, constellation, script) still route through it.
18#[allow(unsafe_code)]
19pub mod ipc_router;
20pub mod print_tree;
21mod rope;
22pub mod text;
23pub mod threadboost;
24pub mod threadpool;
25mod unicode_block;
26
27use std::fs::File;
28use std::io::{BufWriter, Read};
29use std::path::Path;
30
31use ipc_channel::IpcError;
32use ipc_channel::ipc::IpcSender;
33use log::{trace, warn};
34use malloc_size_of_derive::MallocSizeOf;
35pub use rope::{Rope, RopeChars, RopeIndex, RopeMovement, RopeSlice};
36use serde::{Deserialize, Serialize};
37use webrender_api::Epoch as WebRenderEpoch;
38
39pub fn read_json_from_file<T>(data: &mut T, config_dir: &Path, filename: &str)
40where
41    T: for<'de> Deserialize<'de>,
42{
43    let path = config_dir.join(filename);
44    let display = path.display();
45
46    let mut file = match File::open(&path) {
47        Err(why) => {
48            warn!("couldn't open {}: {}", display, why);
49            return;
50        },
51        Ok(file) => file,
52    };
53
54    let mut string_buffer: String = String::new();
55    match file.read_to_string(&mut string_buffer) {
56        Err(why) => panic!("couldn't read from {}: {}", display, why),
57        Ok(_) => trace!("successfully read from {}", display),
58    }
59
60    match serde_json::from_str(&string_buffer) {
61        Ok(decoded_buffer) => *data = decoded_buffer,
62        Err(why) => warn!("Could not decode buffer{}", why),
63    }
64}
65
66pub fn write_json_to_file<T>(data: &T, config_dir: &Path, filename: &str)
67where
68    T: Serialize,
69{
70    let path = config_dir.join(filename);
71    let display = path.display();
72
73    let mut file = match File::create(&path) {
74        Err(why) => panic!("couldn't create {}: {}", display, why),
75        Ok(file) => file,
76    };
77    let mut writer = BufWriter::new(&mut file);
78    serde_json::to_writer_pretty(&mut writer, data).expect("Could not serialize to file");
79    trace!("successfully wrote to {display}");
80}
81
82/// A struct for denoting the age of messages; prevents race conditions.
83#[derive(
84    Clone,
85    Copy,
86    Debug,
87    Default,
88    Deserialize,
89    Eq,
90    Hash,
91    Ord,
92    PartialEq,
93    PartialOrd,
94    Serialize,
95    MallocSizeOf,
96)]
97pub struct Epoch(pub u32);
98
99impl Epoch {
100    pub fn next(&self) -> Self {
101        Self(self.0 + 1)
102    }
103}
104
105impl From<Epoch> for WebRenderEpoch {
106    fn from(val: Epoch) -> Self {
107        WebRenderEpoch(val.0)
108    }
109}
110
111pub trait WebRenderEpochToU16 {
112    fn as_u16(&self) -> u16;
113}
114
115impl WebRenderEpochToU16 for WebRenderEpoch {
116    /// The value of this [`Epoch`] as a u16 value. Note that if this Epoch's
117    /// value is more than u16::MAX, then the return value will be modulo
118    /// u16::MAX.
119    fn as_u16(&self) -> u16 {
120        (self.0 % u16::MAX as u32) as u16
121    }
122}
123
124pub type IpcSendResult = Result<(), IpcError>;
125
126/// Abstraction of the ability to send a particular type of message,
127/// used by net_traits::ResourceThreads to ease the use its IpcSender sub-fields
128/// XXX: If this trait will be used more in future, some auto derive might be appealing
129pub trait IpcSend<T>
130where
131    T: serde::Serialize + for<'de> serde::Deserialize<'de>,
132{
133    /// send message T
134    fn send(&self, _: T) -> IpcSendResult;
135    /// get underlying sender
136    fn sender(&self) -> IpcSender<T>;
137}