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