script: Limit public exports. (#34915)

* script: Restrict reexport visibility of DOM types.

Signed-off-by: Josh Matthews <josh@joshmatthews.net>

* script: Mass pub->pub(crate) conversion.

Signed-off-by: Josh Matthews <josh@joshmatthews.net>

* script: Hide existing dead code warnings.

Signed-off-by: Josh Matthews <josh@joshmatthews.net>

* Formatting.

Signed-off-by: Josh Matthews <josh@joshmatthews.net>

* Fix clippy warnings.

Signed-off-by: Josh Matthews <josh@joshmatthews.net>

* Formatting.

Signed-off-by: Josh Matthews <josh@joshmatthews.net>

* Fix unit tests.

Signed-off-by: Josh Matthews <josh@joshmatthews.net>

* Fix clippy.

Signed-off-by: Josh Matthews <josh@joshmatthews.net>

* More formatting.

Signed-off-by: Josh Matthews <josh@joshmatthews.net>

---------

Signed-off-by: Josh Matthews <josh@joshmatthews.net>
This commit is contained in:
Josh Matthews 2025-01-10 03:19:19 -05:00 committed by GitHub
parent f220d6d3a5
commit c94d909a86
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
585 changed files with 5411 additions and 5013 deletions

View file

@ -21,7 +21,7 @@ pub(crate) struct AnimationTimeline {
impl AnimationTimeline {
/// Creates a new "normal" timeline, i.e., a "Current" mode timer.
#[inline]
pub fn new() -> Self {
pub(crate) fn new() -> Self {
Self {
current_value: SystemTime::now()
.duration_since(UNIX_EPOCH)
@ -32,17 +32,17 @@ impl AnimationTimeline {
/// Creates a new "test mode" timeline, with initial time 0.
#[inline]
pub fn new_for_testing() -> Self {
pub(crate) fn new_for_testing() -> Self {
Self { current_value: 0. }
}
/// Returns the current value of the timeline in seconds.
pub fn current_value(&self) -> f64 {
pub(crate) fn current_value(&self) -> f64 {
self.current_value
}
/// Updates the value of the `AnimationTimeline` to the current clock time.
pub fn update(&mut self) {
pub(crate) fn update(&mut self) {
self.current_value = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
@ -51,7 +51,7 @@ impl AnimationTimeline {
/// Increments the current value of the timeline by a specific number of seconds.
/// This is used for testing.
pub fn advance_specific(&mut self, by: f64) {
pub(crate) fn advance_specific(&mut self, by: f64) {
self.current_value += by;
}
}

View file

@ -41,7 +41,7 @@ use crate::script_runtime::CanGc;
pub(crate) struct Animations {
/// The map of nodes to their animation states.
#[no_trace]
pub sets: DocumentAnimationSet,
pub(crate) sets: DocumentAnimationSet,
/// Whether or not we have animations that are running.
has_running_animations: Cell<bool>,
@ -550,7 +550,7 @@ impl Animations {
/// The type of transition event to trigger. These are defined by
/// CSS Transitions § 6.1 and CSS Animations § 4.2
#[derive(Clone, Debug, Deserialize, JSTraceable, MallocSizeOf, Serialize)]
pub enum TransitionOrAnimationEventType {
pub(crate) enum TransitionOrAnimationEventType {
/// "The transitionrun event occurs when a transition is created (i.e., when it
/// is added to the set of running transitions)."
TransitionRun,
@ -577,7 +577,7 @@ pub enum TransitionOrAnimationEventType {
impl TransitionOrAnimationEventType {
/// Whether or not this event is a transition-related event.
pub fn is_transition_event(&self) -> bool {
pub(crate) fn is_transition_event(&self) -> bool {
match *self {
Self::TransitionRun |
Self::TransitionEnd |
@ -593,21 +593,21 @@ impl TransitionOrAnimationEventType {
#[derive(Deserialize, JSTraceable, MallocSizeOf, Serialize)]
/// A transition or animation event.
pub struct TransitionOrAnimationEvent {
pub(crate) struct TransitionOrAnimationEvent {
/// The pipeline id of the layout task that sent this message.
#[no_trace]
pub pipeline_id: PipelineId,
pub(crate) pipeline_id: PipelineId,
/// The type of transition event this should trigger.
pub event_type: TransitionOrAnimationEventType,
pub(crate) event_type: TransitionOrAnimationEventType,
/// The address of the node which owns this transition.
#[no_trace]
pub node: OpaqueNode,
pub(crate) node: OpaqueNode,
/// The pseudo element for this transition or animation, if applicable.
#[no_trace]
pub pseudo_element: Option<PseudoElement>,
pub(crate) pseudo_element: Option<PseudoElement>,
/// The name of the property that is transitioning (in the case of a transition)
/// or the name of the animation (in the case of an animation).
pub property_or_animation_name: String,
pub(crate) property_or_animation_name: String,
/// The elapsed time property to send with this transition event.
pub elapsed_time: f64,
pub(crate) elapsed_time: f64,
}

View file

@ -45,7 +45,7 @@ use crate::task_source::SendableTaskSource;
/// The Dom object, or ReadableStream, that is the source of a body.
/// <https://fetch.spec.whatwg.org/#concept-body-source>
#[derive(Clone, PartialEq)]
pub enum BodySource {
pub(crate) enum BodySource {
/// A ReadableStream comes with a null-source.
Null,
/// Another Dom object as source,
@ -79,7 +79,7 @@ struct TransmitBodyConnectHandler {
}
impl TransmitBodyConnectHandler {
pub fn new(
pub(crate) fn new(
stream: Trusted<ReadableStream>,
task_source: SendableTaskSource,
control_sender: IpcSender<BodyChunkRequest>,
@ -99,7 +99,7 @@ impl TransmitBodyConnectHandler {
/// Reset `in_memory_done`, called when a stream is
/// re-extracted from the source to support a re-direct.
pub fn reset_in_memory_done(&mut self) {
pub(crate) fn reset_in_memory_done(&mut self) {
self.in_memory_done = false;
}
@ -337,11 +337,11 @@ impl Callback for TransmitBodyPromiseRejectionHandler {
}
/// The result of <https://fetch.spec.whatwg.org/#concept-bodyinit-extract>
pub struct ExtractedBody {
pub stream: DomRoot<ReadableStream>,
pub source: BodySource,
pub total_bytes: Option<usize>,
pub content_type: Option<DOMString>,
pub(crate) struct ExtractedBody {
pub(crate) stream: DomRoot<ReadableStream>,
pub(crate) source: BodySource,
pub(crate) total_bytes: Option<usize>,
pub(crate) content_type: Option<DOMString>,
}
impl ExtractedBody {
@ -356,7 +356,7 @@ impl ExtractedBody {
///
/// Transmitting a body over fetch, and consuming it in script,
/// are mutually exclusive operations, since each will lock the stream to a reader.
pub fn into_net_request_body(self) -> (RequestBody, DomRoot<ReadableStream>) {
pub(crate) fn into_net_request_body(self) -> (RequestBody, DomRoot<ReadableStream>) {
let ExtractedBody {
stream,
total_bytes,
@ -423,13 +423,13 @@ impl ExtractedBody {
}
/// Is the data of the stream of this extracted body available in memory?
pub fn in_memory(&self) -> bool {
pub(crate) fn in_memory(&self) -> bool {
self.stream.in_memory()
}
}
/// <https://fetch.spec.whatwg.org/#concept-bodyinit-extract>
pub trait Extractable {
pub(crate) trait Extractable {
fn extract(&self, global: &GlobalScope, can_gc: CanGc) -> Fallible<ExtractedBody>;
}
@ -570,7 +570,7 @@ impl Extractable for URLSearchParams {
}
#[derive(Clone, Copy, JSTraceable, MallocSizeOf)]
pub enum BodyType {
pub(crate) enum BodyType {
Blob,
FormData,
Json,
@ -578,7 +578,7 @@ pub enum BodyType {
ArrayBuffer,
}
pub enum FetchedData {
pub(crate) enum FetchedData {
Text(String),
Json(RootedTraceableBox<Heap<JSValue>>),
BlobData(DomRoot<Blob>),
@ -712,7 +712,7 @@ impl Callback for ConsumeBodyPromiseHandler {
// https://fetch.spec.whatwg.org/#concept-body-consume-body
#[allow(crown::unrooted_must_root)]
pub fn consume_body<T: BodyMixin + DomObject>(
pub(crate) fn consume_body<T: BodyMixin + DomObject>(
object: &T,
body_type: BodyType,
can_gc: CanGc,
@ -889,7 +889,10 @@ fn run_form_data_algorithm(
}
#[allow(unsafe_code)]
pub fn run_array_buffer_data_algorithm(cx: JSContext, bytes: Vec<u8>) -> Fallible<FetchedData> {
pub(crate) fn run_array_buffer_data_algorithm(
cx: JSContext,
bytes: Vec<u8>,
) -> Fallible<FetchedData> {
rooted!(in(*cx) let mut array_buffer_ptr = ptr::null_mut::<JSObject>());
let arraybuffer = unsafe {
ArrayBuffer::create(
@ -906,7 +909,7 @@ pub fn run_array_buffer_data_algorithm(cx: JSContext, bytes: Vec<u8>) -> Fallibl
}
/// <https://fetch.spec.whatwg.org/#body>
pub trait BodyMixin {
pub(crate) trait BodyMixin {
/// <https://fetch.spec.whatwg.org/#concept-body-disturbed>
fn is_disturbed(&self) -> bool;
/// <https://fetch.spec.whatwg.org/#dom-body-body>

View file

@ -47,7 +47,7 @@ fn main() {
let mut phf = File::create(phf).unwrap();
writeln!(
&mut phf,
"pub static MAP: phf::Map<&'static [u8], fn(JSContext, HandleObject)> = {};",
"pub(crate) static MAP: phf::Map<&'static [u8], fn(JSContext, HandleObject)> = {};",
map.build(),
)
.unwrap();

View file

@ -196,40 +196,40 @@ impl CanvasState {
}
}
pub fn get_ipc_renderer(&self) -> &IpcSender<CanvasMsg> {
pub(crate) fn get_ipc_renderer(&self) -> &IpcSender<CanvasMsg> {
&self.ipc_renderer
}
pub fn get_missing_image_urls(&self) -> &DomRefCell<Vec<ServoUrl>> {
pub(crate) fn get_missing_image_urls(&self) -> &DomRefCell<Vec<ServoUrl>> {
&self.missing_image_urls
}
pub fn get_canvas_id(&self) -> CanvasId {
pub(crate) fn get_canvas_id(&self) -> CanvasId {
self.canvas_id
}
pub fn send_canvas_2d_msg(&self, msg: Canvas2dMsg) {
pub(crate) fn send_canvas_2d_msg(&self, msg: Canvas2dMsg) {
self.ipc_renderer
.send(CanvasMsg::Canvas2d(msg, self.get_canvas_id()))
.unwrap()
}
// https://html.spec.whatwg.org/multipage/#concept-canvas-set-bitmap-dimensions
pub fn set_bitmap_dimensions(&self, size: Size2D<u64>) {
pub(crate) fn set_bitmap_dimensions(&self, size: Size2D<u64>) {
self.reset_to_initial_state();
self.ipc_renderer
.send(CanvasMsg::Recreate(Some(size), self.get_canvas_id()))
.unwrap();
}
pub fn reset(&self) {
pub(crate) fn reset(&self) {
self.reset_to_initial_state();
self.ipc_renderer
.send(CanvasMsg::Recreate(None, self.get_canvas_id()))
.unwrap();
}
pub fn reset_to_initial_state(&self) {
pub(crate) fn reset_to_initial_state(&self) {
self.saved_states.borrow_mut().clear();
*self.state.borrow_mut() = CanvasContextState::new();
}
@ -249,7 +249,7 @@ impl CanvasState {
))
}
pub fn origin_is_clean(&self) -> bool {
pub(crate) fn origin_is_clean(&self) -> bool {
self.origin_clean.get()
}
@ -311,7 +311,7 @@ impl CanvasState {
}
}
pub fn get_rect(&self, canvas_size: Size2D<u64>, rect: Rect<u64>) -> Vec<u8> {
pub(crate) fn get_rect(&self, canvas_size: Size2D<u64>, rect: Rect<u64>) -> Vec<u8> {
assert!(self.origin_is_clean());
assert!(Rect::from_size(canvas_size).contains_rect(&rect));
@ -589,7 +589,7 @@ impl CanvasState {
Ok(())
}
pub fn mark_as_dirty(&self, canvas: Option<&HTMLCanvasElement>) {
pub(crate) fn mark_as_dirty(&self, canvas: Option<&HTMLCanvasElement>) {
if let Some(canvas) = canvas {
canvas.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);
}
@ -665,7 +665,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-fillrect
pub fn fill_rect(&self, x: f64, y: f64, width: f64, height: f64) {
pub(crate) fn fill_rect(&self, x: f64, y: f64, width: f64, height: f64) {
if let Some(rect) = self.create_drawable_rect(x, y, width, height) {
let style = self.state.borrow().fill_style.to_fill_or_stroke_style();
self.send_canvas_2d_msg(Canvas2dMsg::FillRect(rect, style));
@ -673,14 +673,14 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-clearrect
pub fn clear_rect(&self, x: f64, y: f64, width: f64, height: f64) {
pub(crate) fn clear_rect(&self, x: f64, y: f64, width: f64, height: f64) {
if let Some(rect) = self.create_drawable_rect(x, y, width, height) {
self.send_canvas_2d_msg(Canvas2dMsg::ClearRect(rect));
}
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-strokerect
pub fn stroke_rect(&self, x: f64, y: f64, width: f64, height: f64) {
pub(crate) fn stroke_rect(&self, x: f64, y: f64, width: f64, height: f64) {
if let Some(rect) = self.create_drawable_rect(x, y, width, height) {
let style = self.state.borrow().stroke_style.to_fill_or_stroke_style();
self.send_canvas_2d_msg(Canvas2dMsg::StrokeRect(rect, style));
@ -688,12 +688,12 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowoffsetx
pub fn shadow_offset_x(&self) -> f64 {
pub(crate) fn shadow_offset_x(&self) -> f64 {
self.state.borrow().shadow_offset_x
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowoffsetx
pub fn set_shadow_offset_x(&self, value: f64) {
pub(crate) fn set_shadow_offset_x(&self, value: f64) {
if !value.is_finite() || value == self.state.borrow().shadow_offset_x {
return;
}
@ -702,12 +702,12 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowoffsety
pub fn shadow_offset_y(&self) -> f64 {
pub(crate) fn shadow_offset_y(&self) -> f64 {
self.state.borrow().shadow_offset_y
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowoffsety
pub fn set_shadow_offset_y(&self, value: f64) {
pub(crate) fn set_shadow_offset_y(&self, value: f64) {
if !value.is_finite() || value == self.state.borrow().shadow_offset_y {
return;
}
@ -716,12 +716,12 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowblur
pub fn shadow_blur(&self) -> f64 {
pub(crate) fn shadow_blur(&self) -> f64 {
self.state.borrow().shadow_blur
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowblur
pub fn set_shadow_blur(&self, value: f64) {
pub(crate) fn set_shadow_blur(&self, value: f64) {
if !value.is_finite() || value < 0f64 || value == self.state.borrow().shadow_blur {
return;
}
@ -730,14 +730,14 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowcolor
pub fn shadow_color(&self) -> DOMString {
pub(crate) fn shadow_color(&self) -> DOMString {
let mut result = String::new();
serialize(&self.state.borrow().shadow_color, &mut result).unwrap();
DOMString::from(result)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowcolor
pub fn set_shadow_color(
pub(crate) fn set_shadow_color(
&self,
canvas: Option<&HTMLCanvasElement>,
value: DOMString,
@ -750,7 +750,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-strokestyle
pub fn stroke_style(&self) -> StringOrCanvasGradientOrCanvasPattern {
pub(crate) fn stroke_style(&self) -> StringOrCanvasGradientOrCanvasPattern {
match self.state.borrow().stroke_style {
CanvasFillOrStrokeStyle::Color(ref rgba) => {
let mut result = String::new();
@ -767,7 +767,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-strokestyle
pub fn set_stroke_style(
pub(crate) fn set_stroke_style(
&self,
canvas: Option<&HTMLCanvasElement>,
value: StringOrCanvasGradientOrCanvasPattern,
@ -794,7 +794,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-strokestyle
pub fn fill_style(&self) -> StringOrCanvasGradientOrCanvasPattern {
pub(crate) fn fill_style(&self) -> StringOrCanvasGradientOrCanvasPattern {
match self.state.borrow().fill_style {
CanvasFillOrStrokeStyle::Color(ref rgba) => {
let mut result = String::new();
@ -811,7 +811,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-strokestyle
pub fn set_fill_style(
pub(crate) fn set_fill_style(
&self,
canvas: Option<&HTMLCanvasElement>,
value: StringOrCanvasGradientOrCanvasPattern,
@ -838,7 +838,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-createlineargradient
pub fn create_linear_gradient(
pub(crate) fn create_linear_gradient(
&self,
global: &GlobalScope,
x0: Finite<f64>,
@ -854,7 +854,7 @@ impl CanvasState {
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-createradialgradient>
#[allow(clippy::too_many_arguments)]
pub fn create_radial_gradient(
pub(crate) fn create_radial_gradient(
&self,
global: &GlobalScope,
x0: Finite<f64>,
@ -883,7 +883,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-createpattern
pub fn create_pattern(
pub(crate) fn create_pattern(
&self,
global: &GlobalScope,
image: CanvasImageSource,
@ -943,7 +943,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-save
pub fn save(&self) {
pub(crate) fn save(&self) {
self.saved_states
.borrow_mut()
.push(self.state.borrow().clone());
@ -952,7 +952,7 @@ impl CanvasState {
#[allow(crown::unrooted_must_root)]
// https://html.spec.whatwg.org/multipage/#dom-context-2d-restore
pub fn restore(&self) {
pub(crate) fn restore(&self) {
let mut saved_states = self.saved_states.borrow_mut();
if let Some(state) = saved_states.pop() {
self.state.borrow_mut().clone_from(&state);
@ -961,12 +961,12 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-globalalpha
pub fn global_alpha(&self) -> f64 {
pub(crate) fn global_alpha(&self) -> f64 {
self.state.borrow().global_alpha
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-globalalpha
pub fn set_global_alpha(&self, alpha: f64) {
pub(crate) fn set_global_alpha(&self, alpha: f64) {
if !alpha.is_finite() || !(0.0..=1.0).contains(&alpha) {
return;
}
@ -976,7 +976,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-globalcompositeoperation
pub fn global_composite_operation(&self) -> DOMString {
pub(crate) fn global_composite_operation(&self) -> DOMString {
match self.state.borrow().global_composition {
CompositionOrBlending::Composition(op) => DOMString::from(op.to_str()),
CompositionOrBlending::Blending(op) => DOMString::from(op.to_str()),
@ -984,7 +984,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-globalcompositeoperation
pub fn set_global_composite_operation(&self, op_str: DOMString) {
pub(crate) fn set_global_composite_operation(&self, op_str: DOMString) {
if let Ok(op) = CompositionOrBlending::from_str(&op_str) {
self.state.borrow_mut().global_composition = op;
self.send_canvas_2d_msg(Canvas2dMsg::SetGlobalComposition(op))
@ -992,17 +992,17 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-imagesmoothingenabled
pub fn image_smoothing_enabled(&self) -> bool {
pub(crate) fn image_smoothing_enabled(&self) -> bool {
self.state.borrow().image_smoothing_enabled
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-imagesmoothingenabled
pub fn set_image_smoothing_enabled(&self, value: bool) {
pub(crate) fn set_image_smoothing_enabled(&self, value: bool) {
self.state.borrow_mut().image_smoothing_enabled = value;
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-filltext
pub fn fill_text(
pub(crate) fn fill_text(
&self,
canvas: Option<&HTMLCanvasElement>,
text: DOMString,
@ -1043,7 +1043,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#textmetrics
pub fn measure_text(
pub(crate) fn measure_text(
&self,
global: &GlobalScope,
canvas: Option<&HTMLCanvasElement>,
@ -1080,7 +1080,12 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-font
pub fn set_font(&self, canvas: Option<&HTMLCanvasElement>, value: DOMString, can_gc: CanGc) {
pub(crate) fn set_font(
&self,
canvas: Option<&HTMLCanvasElement>,
value: DOMString,
can_gc: CanGc,
) {
let canvas = match canvas {
Some(element) => element,
None => return, // offscreen canvas doesn't have a placeholder canvas
@ -1097,7 +1102,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-font
pub fn font(&self) -> DOMString {
pub(crate) fn font(&self) -> DOMString {
self.state.borrow().font_style.as_ref().map_or_else(
|| CanvasContextState::DEFAULT_FONT_STYLE.into(),
|style| {
@ -1109,7 +1114,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-textalign
pub fn text_align(&self) -> CanvasTextAlign {
pub(crate) fn text_align(&self) -> CanvasTextAlign {
match self.state.borrow().text_align {
TextAlign::Start => CanvasTextAlign::Start,
TextAlign::End => CanvasTextAlign::End,
@ -1120,7 +1125,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-textalign
pub fn set_text_align(&self, value: CanvasTextAlign) {
pub(crate) fn set_text_align(&self, value: CanvasTextAlign) {
let text_align = match value {
CanvasTextAlign::Start => TextAlign::Start,
CanvasTextAlign::End => TextAlign::End,
@ -1132,7 +1137,7 @@ impl CanvasState {
self.send_canvas_2d_msg(Canvas2dMsg::SetTextAlign(text_align));
}
pub fn text_baseline(&self) -> CanvasTextBaseline {
pub(crate) fn text_baseline(&self) -> CanvasTextBaseline {
match self.state.borrow().text_baseline {
TextBaseline::Top => CanvasTextBaseline::Top,
TextBaseline::Hanging => CanvasTextBaseline::Hanging,
@ -1143,7 +1148,7 @@ impl CanvasState {
}
}
pub fn set_text_baseline(&self, value: CanvasTextBaseline) {
pub(crate) fn set_text_baseline(&self, value: CanvasTextBaseline) {
let text_baseline = match value {
CanvasTextBaseline::Top => TextBaseline::Top,
CanvasTextBaseline::Hanging => TextBaseline::Hanging,
@ -1157,7 +1162,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-direction
pub fn direction(&self) -> CanvasDirection {
pub(crate) fn direction(&self) -> CanvasDirection {
match self.state.borrow().direction {
Direction::Ltr => CanvasDirection::Ltr,
Direction::Rtl => CanvasDirection::Rtl,
@ -1166,7 +1171,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-direction
pub fn set_direction(&self, value: CanvasDirection) {
pub(crate) fn set_direction(&self, value: CanvasDirection) {
let direction = match value {
CanvasDirection::Ltr => Direction::Ltr,
CanvasDirection::Rtl => Direction::Rtl,
@ -1176,12 +1181,12 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-linewidth
pub fn line_width(&self) -> f64 {
pub(crate) fn line_width(&self) -> f64 {
self.state.borrow().line_width
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-linewidth
pub fn set_line_width(&self, width: f64) {
pub(crate) fn set_line_width(&self, width: f64) {
if !width.is_finite() || width <= 0.0 {
return;
}
@ -1191,7 +1196,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-linecap
pub fn line_cap(&self) -> CanvasLineCap {
pub(crate) fn line_cap(&self) -> CanvasLineCap {
match self.state.borrow().line_cap {
LineCapStyle::Butt => CanvasLineCap::Butt,
LineCapStyle::Round => CanvasLineCap::Round,
@ -1200,7 +1205,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-linecap
pub fn set_line_cap(&self, cap: CanvasLineCap) {
pub(crate) fn set_line_cap(&self, cap: CanvasLineCap) {
let line_cap = match cap {
CanvasLineCap::Butt => LineCapStyle::Butt,
CanvasLineCap::Round => LineCapStyle::Round,
@ -1211,7 +1216,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-linejoin
pub fn line_join(&self) -> CanvasLineJoin {
pub(crate) fn line_join(&self) -> CanvasLineJoin {
match self.state.borrow().line_join {
LineJoinStyle::Round => CanvasLineJoin::Round,
LineJoinStyle::Bevel => CanvasLineJoin::Bevel,
@ -1220,7 +1225,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-linejoin
pub fn set_line_join(&self, join: CanvasLineJoin) {
pub(crate) fn set_line_join(&self, join: CanvasLineJoin) {
let line_join = match join {
CanvasLineJoin::Round => LineJoinStyle::Round,
CanvasLineJoin::Bevel => LineJoinStyle::Bevel,
@ -1231,12 +1236,12 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-miterlimit
pub fn miter_limit(&self) -> f64 {
pub(crate) fn miter_limit(&self) -> f64 {
self.state.borrow().miter_limit
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-miterlimit
pub fn set_miter_limit(&self, limit: f64) {
pub(crate) fn set_miter_limit(&self, limit: f64) {
if !limit.is_finite() || limit <= 0.0 {
return;
}
@ -1246,7 +1251,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-createimagedata
pub fn create_image_data(
pub(crate) fn create_image_data(
&self,
global: &GlobalScope,
sw: i32,
@ -1260,7 +1265,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-createimagedata
pub fn create_image_data_(
pub(crate) fn create_image_data_(
&self,
global: &GlobalScope,
imagedata: &ImageData,
@ -1271,7 +1276,7 @@ impl CanvasState {
// https://html.spec.whatwg.org/multipage/#dom-context-2d-getimagedata
#[allow(clippy::too_many_arguments)]
pub fn get_image_data(
pub(crate) fn get_image_data(
&self,
canvas_size: Size2D<u64>,
global: &GlobalScope,
@ -1311,7 +1316,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-putimagedata
pub fn put_image_data(
pub(crate) fn put_image_data(
&self,
canvas_size: Size2D<u64>,
imagedata: &ImageData,
@ -1332,7 +1337,7 @@ impl CanvasState {
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-putimagedata>
#[allow(unsafe_code, clippy::too_many_arguments)]
pub fn put_image_data_(
pub(crate) fn put_image_data_(
&self,
canvas_size: Size2D<u64>,
imagedata: &ImageData,
@ -1385,7 +1390,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-drawimage
pub fn draw_image(
pub(crate) fn draw_image(
&self,
canvas: Option<&HTMLCanvasElement>,
image: CanvasImageSource,
@ -1400,7 +1405,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-drawimage
pub fn draw_image_(
pub(crate) fn draw_image_(
&self,
canvas: Option<&HTMLCanvasElement>,
image: CanvasImageSource,
@ -1429,7 +1434,7 @@ impl CanvasState {
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-drawimage>
#[allow(clippy::too_many_arguments)]
pub fn draw_image__(
pub(crate) fn draw_image__(
&self,
canvas: Option<&HTMLCanvasElement>,
image: CanvasImageSource,
@ -1469,31 +1474,31 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-beginpath
pub fn begin_path(&self) {
pub(crate) fn begin_path(&self) {
self.send_canvas_2d_msg(Canvas2dMsg::BeginPath);
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-fill
pub fn fill(&self, _fill_rule: CanvasFillRule) {
pub(crate) fn fill(&self, _fill_rule: CanvasFillRule) {
// TODO: Process fill rule
let style = self.state.borrow().fill_style.to_fill_or_stroke_style();
self.send_canvas_2d_msg(Canvas2dMsg::Fill(style));
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-stroke
pub fn stroke(&self) {
pub(crate) fn stroke(&self) {
let style = self.state.borrow().stroke_style.to_fill_or_stroke_style();
self.send_canvas_2d_msg(Canvas2dMsg::Stroke(style));
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-clip
pub fn clip(&self, _fill_rule: CanvasFillRule) {
pub(crate) fn clip(&self, _fill_rule: CanvasFillRule) {
// TODO: Process fill rule
self.send_canvas_2d_msg(Canvas2dMsg::Clip);
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-ispointinpath
pub fn is_point_in_path(
pub(crate) fn is_point_in_path(
&self,
global: &GlobalScope,
x: f64,
@ -1515,7 +1520,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-scale
pub fn scale(&self, x: f64, y: f64) {
pub(crate) fn scale(&self, x: f64, y: f64) {
if !(x.is_finite() && y.is_finite()) {
return;
}
@ -1526,7 +1531,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-rotate
pub fn rotate(&self, angle: f64) {
pub(crate) fn rotate(&self, angle: f64) {
if angle == 0.0 || !angle.is_finite() {
return;
}
@ -1540,7 +1545,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-translate
pub fn translate(&self, x: f64, y: f64) {
pub(crate) fn translate(&self, x: f64, y: f64) {
if !(x.is_finite() && y.is_finite()) {
return;
}
@ -1551,7 +1556,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-transform
pub fn transform(&self, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) {
pub(crate) fn transform(&self, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) {
if !(a.is_finite() &&
b.is_finite() &&
c.is_finite() &&
@ -1570,7 +1575,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-gettransform
pub fn get_transform(&self, global: &GlobalScope, can_gc: CanGc) -> DomRoot<DOMMatrix> {
pub(crate) fn get_transform(&self, global: &GlobalScope, can_gc: CanGc) -> DomRoot<DOMMatrix> {
let (sender, receiver) = ipc::channel::<Transform2D<f32>>().unwrap();
self.send_canvas_2d_msg(Canvas2dMsg::GetTransform(sender));
let transform = receiver.recv().unwrap();
@ -1579,7 +1584,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-settransform
pub fn set_transform(&self, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) {
pub(crate) fn set_transform(&self, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) {
if !(a.is_finite() &&
b.is_finite() &&
c.is_finite() &&
@ -1596,18 +1601,18 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-resettransform
pub fn reset_transform(&self) {
pub(crate) fn reset_transform(&self) {
self.state.borrow_mut().transform = Transform2D::identity();
self.update_transform()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-closepath
pub fn close_path(&self) {
pub(crate) fn close_path(&self) {
self.send_canvas_2d_msg(Canvas2dMsg::ClosePath);
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-moveto
pub fn move_to(&self, x: f64, y: f64) {
pub(crate) fn move_to(&self, x: f64, y: f64) {
if !(x.is_finite() && y.is_finite()) {
return;
}
@ -1615,7 +1620,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-lineto
pub fn line_to(&self, x: f64, y: f64) {
pub(crate) fn line_to(&self, x: f64, y: f64) {
if !(x.is_finite() && y.is_finite()) {
return;
}
@ -1623,7 +1628,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-rect
pub fn rect(&self, x: f64, y: f64, width: f64, height: f64) {
pub(crate) fn rect(&self, x: f64, y: f64, width: f64, height: f64) {
if [x, y, width, height].iter().all(|val| val.is_finite()) {
let rect = Rect::new(
Point2D::new(x as f32, y as f32),
@ -1634,7 +1639,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-quadraticcurveto
pub fn quadratic_curve_to(&self, cpx: f64, cpy: f64, x: f64, y: f64) {
pub(crate) fn quadratic_curve_to(&self, cpx: f64, cpy: f64, x: f64, y: f64) {
if !(cpx.is_finite() && cpy.is_finite() && x.is_finite() && y.is_finite()) {
return;
}
@ -1645,7 +1650,15 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-beziercurveto
pub fn bezier_curve_to(&self, cp1x: f64, cp1y: f64, cp2x: f64, cp2y: f64, x: f64, y: f64) {
pub(crate) fn bezier_curve_to(
&self,
cp1x: f64,
cp1y: f64,
cp2x: f64,
cp2y: f64,
x: f64,
y: f64,
) {
if !(cp1x.is_finite() &&
cp1y.is_finite() &&
cp2x.is_finite() &&
@ -1663,7 +1676,15 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-arc
pub fn arc(&self, x: f64, y: f64, r: f64, start: f64, end: f64, ccw: bool) -> ErrorResult {
pub(crate) fn arc(
&self,
x: f64,
y: f64,
r: f64,
start: f64,
end: f64,
ccw: bool,
) -> ErrorResult {
if !([x, y, r, start, end].iter().all(|x| x.is_finite())) {
return Ok(());
}
@ -1683,7 +1704,7 @@ impl CanvasState {
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-arcto
pub fn arc_to(&self, cp1x: f64, cp1y: f64, cp2x: f64, cp2y: f64, r: f64) -> ErrorResult {
pub(crate) fn arc_to(&self, cp1x: f64, cp1y: f64, cp2x: f64, cp2y: f64, r: f64) -> ErrorResult {
if !([cp1x, cp1y, cp2x, cp2y, r].iter().all(|x| x.is_finite())) {
return Ok(());
}
@ -1701,7 +1722,7 @@ impl CanvasState {
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-ellipse>
#[allow(clippy::too_many_arguments)]
pub fn ellipse(
pub(crate) fn ellipse(
&self,
x: f64,
y: f64,
@ -1735,7 +1756,7 @@ impl CanvasState {
}
}
pub fn parse_color(
pub(crate) fn parse_color(
canvas: Option<&HTMLCanvasElement>,
string: &str,
can_gc: CanGc,
@ -1784,12 +1805,12 @@ pub fn parse_color(
// Used by drawImage to determine if a source or destination rectangle is valid
// Origin coordinates and size cannot be negative. Size has to be greater than zero
pub fn is_rect_valid(rect: Rect<f64>) -> bool {
pub(crate) fn is_rect_valid(rect: Rect<f64>) -> bool {
rect.size.width > 0.0 && rect.size.height > 0.0
}
// https://html.spec.whatwg.org/multipage/#serialisation-of-a-color
pub fn serialize<W>(color: &AbsoluteColor, dest: &mut W) -> fmt::Result
pub(crate) fn serialize<W>(color: &AbsoluteColor, dest: &mut W) -> fmt::Result
where
W: fmt::Write,
{
@ -1819,7 +1840,7 @@ where
}
}
pub fn adjust_size_sign(
pub(crate) fn adjust_size_sign(
mut origin: Point2D<i32>,
mut size: Size2D<i32>,
) -> (Point2D<i32>, Size2D<u32>) {

View file

@ -6,7 +6,7 @@
/// to convert between two types that are not defined in the script crate.
/// This is intended to be used on dict/enum types generated from WebIDL once
/// those types are moved out of the script crate.
pub trait Convert<T> {
pub(crate) trait Convert<T> {
fn convert(self) -> T;
}
@ -14,7 +14,7 @@ pub trait Convert<T> {
/// to convert between two types that are not defined in the script crate.
/// This is intended to be used on dict/enum types generated from WebIDL once
/// those types are moved out of the script crate.
pub trait TryConvert<T> {
pub(crate) trait TryConvert<T> {
type Error;
fn try_convert(self) -> Result<T, Self::Error>;

View file

@ -44,7 +44,7 @@ use crate::script_module::ScriptFetchOptions;
use crate::script_runtime::CanGc;
#[allow(unsafe_code)]
pub fn handle_evaluate_js(
pub(crate) fn handle_evaluate_js(
global: &GlobalScope,
eval: String,
reply: IpcSender<EvaluateJSReply>,
@ -97,7 +97,7 @@ pub fn handle_evaluate_js(
reply.send(result).unwrap();
}
pub fn handle_get_root_node(
pub(crate) fn handle_get_root_node(
documents: &DocumentCollection,
pipeline: PipelineId,
reply: IpcSender<Option<NodeInfo>>,
@ -108,7 +108,7 @@ pub fn handle_get_root_node(
reply.send(info).unwrap();
}
pub fn handle_get_document_element(
pub(crate) fn handle_get_document_element(
documents: &DocumentCollection,
pipeline: PipelineId,
reply: IpcSender<Option<NodeInfo>>,
@ -133,7 +133,7 @@ fn find_node_by_unique_id(
})
}
pub fn handle_get_children(
pub(crate) fn handle_get_children(
documents: &DocumentCollection,
pipeline: PipelineId,
node_id: String,
@ -185,7 +185,7 @@ pub fn handle_get_children(
};
}
pub fn handle_get_attribute_style(
pub(crate) fn handle_get_attribute_style(
documents: &DocumentCollection,
pipeline: PipelineId,
node_id: String,
@ -217,7 +217,7 @@ pub fn handle_get_attribute_style(
}
#[allow(crown::unrooted_must_root)]
pub fn handle_get_stylesheet_style(
pub(crate) fn handle_get_stylesheet_style(
documents: &DocumentCollection,
pipeline: PipelineId,
node_id: String,
@ -264,7 +264,7 @@ pub fn handle_get_stylesheet_style(
}
#[allow(crown::unrooted_must_root)]
pub fn handle_get_selectors(
pub(crate) fn handle_get_selectors(
documents: &DocumentCollection,
pipeline: PipelineId,
node_id: String,
@ -300,7 +300,7 @@ pub fn handle_get_selectors(
reply.send(msg).unwrap();
}
pub fn handle_get_computed_style(
pub(crate) fn handle_get_computed_style(
documents: &DocumentCollection,
pipeline: PipelineId,
node_id: String,
@ -334,7 +334,7 @@ pub fn handle_get_computed_style(
reply.send(Some(msg)).unwrap();
}
pub fn handle_get_layout(
pub(crate) fn handle_get_layout(
documents: &DocumentCollection,
pipeline: PipelineId,
node_id: String,
@ -395,7 +395,7 @@ fn determine_auto_margins(node: &Node, can_gc: CanGc) -> AutoMargins {
}
}
pub fn handle_modify_attribute(
pub(crate) fn handle_modify_attribute(
documents: &DocumentCollection,
pipeline: PipelineId,
node_id: String,
@ -435,7 +435,7 @@ pub fn handle_modify_attribute(
}
}
pub fn handle_modify_rule(
pub(crate) fn handle_modify_rule(
documents: &DocumentCollection,
pipeline: PipelineId,
node_id: String,
@ -469,11 +469,11 @@ pub fn handle_modify_rule(
}
}
pub fn handle_wants_live_notifications(global: &GlobalScope, send_notifications: bool) {
pub(crate) fn handle_wants_live_notifications(global: &GlobalScope, send_notifications: bool) {
global.set_devtools_wants_updates(send_notifications);
}
pub fn handle_set_timeline_markers(
pub(crate) fn handle_set_timeline_markers(
documents: &DocumentCollection,
pipeline: PipelineId,
marker_types: Vec<TimelineMarkerType>,
@ -485,7 +485,7 @@ pub fn handle_set_timeline_markers(
}
}
pub fn handle_drop_timeline_markers(
pub(crate) fn handle_drop_timeline_markers(
documents: &DocumentCollection,
pipeline: PipelineId,
marker_types: Vec<TimelineMarkerType>,
@ -495,7 +495,7 @@ pub fn handle_drop_timeline_markers(
}
}
pub fn handle_request_animation_frame(
pub(crate) fn handle_request_animation_frame(
documents: &DocumentCollection,
id: PipelineId,
actor_name: String,
@ -505,13 +505,13 @@ pub fn handle_request_animation_frame(
}
}
pub fn handle_reload(documents: &DocumentCollection, id: PipelineId, can_gc: CanGc) {
pub(crate) fn handle_reload(documents: &DocumentCollection, id: PipelineId, can_gc: CanGc) {
if let Some(win) = documents.find_window(id) {
win.Location().reload_without_origin_check(can_gc);
}
}
pub fn handle_get_css_database(reply: IpcSender<HashMap<String, CssDatabaseProperty>>) {
pub(crate) fn handle_get_css_database(reply: IpcSender<HashMap<String, CssDatabaseProperty>>) {
let database: HashMap<_, _> = ENABLED_LONGHAND_PROPERTIES
.iter()
.map(|l| {

View file

@ -24,33 +24,33 @@ pub(crate) struct DocumentCollection {
}
impl DocumentCollection {
pub fn insert(&mut self, pipeline_id: PipelineId, doc: &Document) {
pub(crate) fn insert(&mut self, pipeline_id: PipelineId, doc: &Document) {
self.map.insert(pipeline_id, Dom::from_ref(doc));
}
pub fn remove(&mut self, pipeline_id: PipelineId) -> Option<DomRoot<Document>> {
pub(crate) fn remove(&mut self, pipeline_id: PipelineId) -> Option<DomRoot<Document>> {
self.map
.remove(&pipeline_id)
.map(|ref doc| DomRoot::from_ref(&**doc))
}
pub fn find_document(&self, pipeline_id: PipelineId) -> Option<DomRoot<Document>> {
pub(crate) fn find_document(&self, pipeline_id: PipelineId) -> Option<DomRoot<Document>> {
self.map
.get(&pipeline_id)
.map(|doc| DomRoot::from_ref(&**doc))
}
pub fn find_window(&self, pipeline_id: PipelineId) -> Option<DomRoot<Window>> {
pub(crate) fn find_window(&self, pipeline_id: PipelineId) -> Option<DomRoot<Window>> {
self.find_document(pipeline_id)
.map(|doc| DomRoot::from_ref(doc.window()))
}
pub fn find_global(&self, pipeline_id: PipelineId) -> Option<DomRoot<GlobalScope>> {
pub(crate) fn find_global(&self, pipeline_id: PipelineId) -> Option<DomRoot<GlobalScope>> {
self.find_window(pipeline_id)
.map(|window| DomRoot::from_ref(window.upcast()))
}
pub fn find_iframe(
pub(crate) fn find_iframe(
&self,
pipeline_id: PipelineId,
browsing_context_id: BrowsingContextId,
@ -63,7 +63,7 @@ impl DocumentCollection {
})
}
pub fn iter(&self) -> DocumentsIter<'_> {
pub(crate) fn iter(&self) -> DocumentsIter<'_> {
DocumentsIter {
iter: self.map.iter(),
}
@ -101,7 +101,7 @@ impl Default for DocumentCollection {
}
#[allow(crown::unrooted_must_root)]
pub struct DocumentsIter<'a> {
pub(crate) struct DocumentsIter<'a> {
iter: hash_map::Iter<'a, PipelineId, Dom<Document>>,
}

View file

@ -18,7 +18,7 @@ use crate::fetch::FetchCanceller;
use crate::script_runtime::CanGc;
#[derive(Clone, Debug, JSTraceable, MallocSizeOf, PartialEq)]
pub enum LoadType {
pub(crate) enum LoadType {
Image(#[no_trace] ServoUrl),
Script(#[no_trace] ServoUrl),
Subframe(#[no_trace] ServoUrl),
@ -32,7 +32,7 @@ pub enum LoadType {
/// that the owner is destroyed.
#[derive(JSTraceable, MallocSizeOf)]
#[crown::unrooted_must_root_lint::must_root]
pub struct LoadBlocker {
pub(crate) struct LoadBlocker {
/// The document whose load event is blocked by this object existing.
doc: Dom<Document>,
/// The load that is blocking the document's load event.
@ -41,7 +41,7 @@ pub struct LoadBlocker {
impl LoadBlocker {
/// Mark the document's load event as blocked on this new load.
pub fn new(doc: &Document, load: LoadType) -> LoadBlocker {
pub(crate) fn new(doc: &Document, load: LoadType) -> LoadBlocker {
doc.loader_mut().add_blocking_load(load.clone());
LoadBlocker {
doc: Dom::from_ref(doc),
@ -50,7 +50,7 @@ impl LoadBlocker {
}
/// Remove this load from the associated document's list of blocking loads.
pub fn terminate(blocker: &DomRefCell<Option<LoadBlocker>>, can_gc: CanGc) {
pub(crate) fn terminate(blocker: &DomRefCell<Option<LoadBlocker>>, can_gc: CanGc) {
if let Some(this) = blocker.borrow().as_ref() {
let load_data = this.load.clone().unwrap();
this.doc.finish_load(load_data, can_gc);
@ -68,7 +68,7 @@ impl Drop for LoadBlocker {
}
#[derive(JSTraceable, MallocSizeOf)]
pub struct DocumentLoader {
pub(crate) struct DocumentLoader {
#[no_trace]
resource_threads: ResourceThreads,
blocking_loads: Vec<LoadType>,
@ -77,11 +77,11 @@ pub struct DocumentLoader {
}
impl DocumentLoader {
pub fn new(existing: &DocumentLoader) -> DocumentLoader {
pub(crate) fn new(existing: &DocumentLoader) -> DocumentLoader {
DocumentLoader::new_with_threads(existing.resource_threads.clone(), None)
}
pub fn new_with_threads(
pub(crate) fn new_with_threads(
resource_threads: ResourceThreads,
initial_load: Option<ServoUrl>,
) -> DocumentLoader {
@ -96,7 +96,7 @@ impl DocumentLoader {
}
}
pub fn cancel_all_loads(&mut self) -> bool {
pub(crate) fn cancel_all_loads(&mut self) -> bool {
let canceled_any = !self.cancellers.is_empty();
// Associated fetches will be canceled when dropping the canceller.
self.cancellers.clear();
@ -114,7 +114,7 @@ impl DocumentLoader {
}
/// Initiate a new fetch given a response callback.
pub fn fetch_async_with_callback(
pub(crate) fn fetch_async_with_callback(
&mut self,
load: LoadType,
request: RequestBuilder,
@ -125,7 +125,7 @@ impl DocumentLoader {
}
/// Initiate a new fetch that does not block the document load event.
pub fn fetch_async_background(
pub(crate) fn fetch_async_background(
&mut self,
request: RequestBuilder,
callback: BoxedFetchCallback,
@ -147,7 +147,7 @@ impl DocumentLoader {
}
/// Mark an in-progress network request complete.
pub fn finish_load(&mut self, load: &LoadType) {
pub(crate) fn finish_load(&mut self, load: &LoadType) {
debug!(
"Removing blocking load {:?} ({}).",
load,
@ -165,26 +165,26 @@ impl DocumentLoader {
}
}
pub fn is_blocked(&self) -> bool {
pub(crate) fn is_blocked(&self) -> bool {
// TODO: Ensure that we report blocked if parsing is still ongoing.
!self.blocking_loads.is_empty()
}
pub fn is_only_blocked_by_iframes(&self) -> bool {
pub(crate) fn is_only_blocked_by_iframes(&self) -> bool {
self.blocking_loads
.iter()
.all(|load| matches!(*load, LoadType::Subframe(_)))
}
pub fn inhibit_events(&mut self) {
pub(crate) fn inhibit_events(&mut self) {
self.events_inhibited = true;
}
pub fn events_inhibited(&self) -> bool {
pub(crate) fn events_inhibited(&self) -> bool {
self.events_inhibited
}
pub fn resource_threads(&self) -> &ResourceThreads {
pub(crate) fn resource_threads(&self) -> &ResourceThreads {
&self.resource_threads
}
}

View file

@ -13,7 +13,7 @@ use crate::dom::globalscope::GlobalScope;
use crate::script_runtime::{CanGc, JSContext};
#[dom_struct]
pub struct AbortController {
pub(crate) struct AbortController {
reflector_: Reflector,
}

View file

@ -17,14 +17,14 @@ use crate::dom::node::{Node, ShadowIncluding};
use crate::script_runtime::CanGc;
#[dom_struct]
pub struct AbstractRange {
pub(crate) struct AbstractRange {
reflector_: Reflector,
start: BoundaryPoint,
end: BoundaryPoint,
}
impl AbstractRange {
pub fn new_inherited(
pub(crate) fn new_inherited(
start_container: &Node,
start_offset: u32,
end_container: &Node,
@ -37,7 +37,7 @@ impl AbstractRange {
}
}
pub fn new(
pub(crate) fn new(
document: &Document,
start_container: &Node,
start_offset: u32,
@ -57,11 +57,11 @@ impl AbstractRange {
abstractrange
}
pub fn start(&self) -> &BoundaryPoint {
pub(crate) fn start(&self) -> &BoundaryPoint {
&self.start
}
pub fn end(&self) -> &BoundaryPoint {
pub(crate) fn end(&self) -> &BoundaryPoint {
&self.end
}
}
@ -95,7 +95,7 @@ impl AbstractRangeMethods<crate::DomTypeHolder> for AbstractRange {
#[derive(DenyPublicFields, JSTraceable, MallocSizeOf)]
#[crown::unrooted_must_root_lint::must_root]
pub struct BoundaryPoint {
pub(crate) struct BoundaryPoint {
node: MutDom<Node>,
offset: Cell<u32>,
}
@ -109,16 +109,16 @@ impl BoundaryPoint {
}
}
pub fn set(&self, node: &Node, offset: u32) {
pub(crate) fn set(&self, node: &Node, offset: u32) {
self.node.set(node);
self.set_offset(offset);
}
pub fn set_offset(&self, offset: u32) {
pub(crate) fn set_offset(&self, offset: u32) {
self.offset.set(offset);
}
pub fn node(&self) -> &MutDom<Node> {
pub(crate) fn node(&self) -> &MutDom<Node> {
&self.node
}
}
@ -143,7 +143,12 @@ impl PartialEq for BoundaryPoint {
}
/// <https://dom.spec.whatwg.org/#concept-range-bp-position>
pub fn bp_position(a_node: &Node, a_offset: u32, b_node: &Node, b_offset: u32) -> Option<Ordering> {
pub(crate) fn bp_position(
a_node: &Node,
a_offset: u32,
b_node: &Node,
b_offset: u32,
) -> Option<Ordering> {
if std::ptr::eq(a_node, b_node) {
// Step 1.
return Some(a_offset.cmp(&b_offset));

View file

@ -10,7 +10,7 @@ use crate::dom::bindings::reflector::DomObject;
use crate::messaging::CommonScriptMsg;
/// Messages used to control the worker event loops
pub enum WorkerScriptMsg {
pub(crate) enum WorkerScriptMsg {
/// Common variants associated with the script messages
Common(CommonScriptMsg),
/// Message sent through Worker.postMessage
@ -20,12 +20,12 @@ pub enum WorkerScriptMsg {
},
}
pub struct SimpleWorkerErrorHandler<T: DomObject> {
pub addr: Trusted<T>,
pub(crate) struct SimpleWorkerErrorHandler<T: DomObject> {
pub(crate) addr: Trusted<T>,
}
impl<T: DomObject> SimpleWorkerErrorHandler<T> {
pub fn new(addr: Trusted<T>) -> SimpleWorkerErrorHandler<T> {
pub(crate) fn new(addr: Trusted<T>) -> SimpleWorkerErrorHandler<T> {
SimpleWorkerErrorHandler { addr }
}
}

View file

@ -15,7 +15,7 @@ use crate::realms::enter_realm;
use crate::script_runtime::CanGc;
use crate::task_queue::{QueuedTaskConversion, TaskQueue};
pub trait WorkerEventLoopMethods {
pub(crate) trait WorkerEventLoopMethods {
type WorkerMsg: QueuedTaskConversion + Send;
type ControlMsg;
type Event;
@ -30,7 +30,7 @@ pub trait WorkerEventLoopMethods {
}
// https://html.spec.whatwg.org/multipage/#worker-event-loop
pub fn run_worker_event_loop<T, WorkerMsg, Event>(
pub(crate) fn run_worker_event_loop<T, WorkerMsg, Event>(
worker_scope: &T,
worker: Option<&TrustedWorkerAddress>,
can_gc: CanGc,

View file

@ -9,7 +9,7 @@ use crate::dom::htmlinputelement::InputActivationState;
use crate::script_runtime::CanGc;
/// Trait for elements with defined activation behavior
pub trait Activatable {
pub(crate) trait Activatable {
fn as_element(&self) -> &Element;
// Is this particular instance of the element activatable?

View file

@ -29,7 +29,7 @@ use crate::dom::window::Window;
use crate::script_runtime::CanGc;
#[dom_struct]
pub struct AnalyserNode {
pub(crate) struct AnalyserNode {
node: AudioNode,
#[ignore_malloc_size_of = "Defined in servo-media"]
#[no_trace]
@ -38,7 +38,7 @@ pub struct AnalyserNode {
impl AnalyserNode {
#[allow(crown::unrooted_must_root)]
pub fn new_inherited(
pub(crate) fn new_inherited(
_: &Window,
context: &BaseAudioContext,
options: &AnalyserOptions,
@ -91,7 +91,7 @@ impl AnalyserNode {
))
}
pub fn new(
pub(crate) fn new(
window: &Window,
context: &BaseAudioContext,
options: &AnalyserOptions,
@ -101,7 +101,7 @@ impl AnalyserNode {
}
#[allow(crown::unrooted_must_root)]
pub fn new_with_proto(
pub(crate) fn new_with_proto(
window: &Window,
proto: Option<HandleObject>,
context: &BaseAudioContext,
@ -130,7 +130,7 @@ impl AnalyserNode {
Ok(object)
}
pub fn push_block(&self, block: Block) {
pub(crate) fn push_block(&self, block: Block) {
self.engine.borrow_mut().push(block)
}
}

View file

@ -20,7 +20,7 @@ use crate::dom::window::Window;
use crate::script_runtime::CanGc;
#[dom_struct]
pub struct AnimationEvent {
pub(crate) struct AnimationEvent {
event: Event,
#[no_trace]
animation_name: Atom,
@ -38,7 +38,7 @@ impl AnimationEvent {
}
}
pub fn new(
pub(crate) fn new(
window: &Window,
type_: Atom,
init: &AnimationEventInit,

View file

@ -28,7 +28,7 @@ use crate::script_thread::ScriptThread;
// https://dom.spec.whatwg.org/#interface-attr
#[dom_struct]
pub struct Attr {
pub(crate) struct Attr {
node_: Node,
#[no_trace]
identifier: AttrIdentifier,
@ -62,7 +62,7 @@ impl Attr {
}
}
#[allow(clippy::too_many_arguments)]
pub fn new(
pub(crate) fn new(
document: &Document,
local_name: LocalName,
value: AttrValue,
@ -82,17 +82,17 @@ impl Attr {
}
#[inline]
pub fn name(&self) -> &LocalName {
pub(crate) fn name(&self) -> &LocalName {
&self.identifier.name.0
}
#[inline]
pub fn namespace(&self) -> &Namespace {
pub(crate) fn namespace(&self) -> &Namespace {
&self.identifier.namespace.0
}
#[inline]
pub fn prefix(&self) -> Option<&Prefix> {
pub(crate) fn prefix(&self) -> Option<&Prefix> {
Some(&self.identifier.prefix.as_ref()?.0)
}
}
@ -152,7 +152,7 @@ impl AttrMethods<crate::DomTypeHolder> for Attr {
}
impl Attr {
pub fn set_value(&self, mut value: AttrValue, owner: &Element) {
pub(crate) fn set_value(&self, mut value: AttrValue, owner: &Element) {
let name = self.local_name().clone();
let namespace = self.namespace().clone();
let old_value = DOMString::from(&**self.value());
@ -185,25 +185,25 @@ impl Attr {
}
/// Used to swap the attribute's value without triggering mutation events
pub fn swap_value(&self, value: &mut AttrValue) {
pub(crate) fn swap_value(&self, value: &mut AttrValue) {
mem::swap(&mut *self.value.borrow_mut(), value);
}
pub fn identifier(&self) -> &AttrIdentifier {
pub(crate) fn identifier(&self) -> &AttrIdentifier {
&self.identifier
}
pub fn value(&self) -> Ref<AttrValue> {
pub(crate) fn value(&self) -> Ref<AttrValue> {
self.value.borrow()
}
pub fn local_name(&self) -> &LocalName {
pub(crate) fn local_name(&self) -> &LocalName {
&self.identifier.local_name
}
/// Sets the owner element. Should be called after the attribute is added
/// or removed from its older parent.
pub fn set_owner(&self, owner: Option<&Element>) {
pub(crate) fn set_owner(&self, owner: Option<&Element>) {
let ns = self.namespace();
match (self.owner(), owner) {
(Some(old), None) => {
@ -220,11 +220,11 @@ impl Attr {
self.owner.set(owner);
}
pub fn owner(&self) -> Option<DomRoot<Element>> {
pub(crate) fn owner(&self) -> Option<DomRoot<Element>> {
self.owner.get()
}
pub fn summarize(&self) -> AttrInfo {
pub(crate) fn summarize(&self) -> AttrInfo {
AttrInfo {
namespace: (**self.namespace()).to_owned(),
name: String::from(self.Name()),
@ -232,7 +232,7 @@ impl Attr {
}
}
pub fn qualified_name(&self) -> DOMString {
pub(crate) fn qualified_name(&self) -> DOMString {
match self.prefix() {
Some(ref prefix) => DOMString::from(format!("{}:{}", prefix, &**self.local_name())),
None => DOMString::from(&**self.local_name()),
@ -241,7 +241,7 @@ impl Attr {
}
#[allow(unsafe_code)]
pub trait AttrHelpersForLayout<'dom> {
pub(crate) trait AttrHelpersForLayout<'dom> {
fn value(self) -> &'dom AttrValue;
fn as_str(&self) -> &'dom str;
fn to_tokens(self) -> Option<&'dom [Atom]>;

View file

@ -26,8 +26,8 @@ use crate::script_runtime::{CanGc, JSContext};
// Spec mandates at least [8000, 96000], we use [8000, 192000] to match Firefox
// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createbuffer
pub const MIN_SAMPLE_RATE: f32 = 8000.;
pub const MAX_SAMPLE_RATE: f32 = 192000.;
pub(crate) const MIN_SAMPLE_RATE: f32 = 8000.;
pub(crate) const MAX_SAMPLE_RATE: f32 = 192000.;
/// The AudioBuffer keeps its data either in js_channels
/// or in shared_channels if js_channels buffers are detached.
@ -38,7 +38,7 @@ pub const MAX_SAMPLE_RATE: f32 = 192000.;
/// to know in which situations js_channels buffers must be detached.
///
#[dom_struct]
pub struct AudioBuffer {
pub(crate) struct AudioBuffer {
reflector_: Reflector,
/// Float32Arrays returned by calls to GetChannelData.
#[ignore_malloc_size_of = "mozjs"]
@ -60,7 +60,11 @@ pub struct AudioBuffer {
impl AudioBuffer {
#[allow(crown::unrooted_must_root)]
pub fn new_inherited(number_of_channels: u32, length: u32, sample_rate: f32) -> AudioBuffer {
pub(crate) fn new_inherited(
number_of_channels: u32,
length: u32,
sample_rate: f32,
) -> AudioBuffer {
let vec = (0..number_of_channels)
.map(|_| HeapBufferSource::default())
.collect();
@ -75,7 +79,7 @@ impl AudioBuffer {
}
}
pub fn new(
pub(crate) fn new(
global: &Window,
number_of_channels: u32,
length: u32,
@ -172,7 +176,7 @@ impl AudioBuffer {
Some(result)
}
pub fn get_channels(&self) -> Ref<Option<ServoMediaAudioBuffer>> {
pub(crate) fn get_channels(&self) -> Ref<Option<ServoMediaAudioBuffer>> {
if self.shared_channels.borrow().is_none() {
let channels = self.acquire_contents();
if channels.is_some() {

View file

@ -31,7 +31,7 @@ use crate::dom::window::Window;
use crate::script_runtime::CanGc;
#[dom_struct]
pub struct AudioBufferSourceNode {
pub(crate) struct AudioBufferSourceNode {
source_node: AudioScheduledSourceNode,
buffer: MutNullableDom<AudioBuffer>,
buffer_set: Cell<bool>,
@ -96,7 +96,7 @@ impl AudioBufferSourceNode {
Ok(node)
}
pub fn new(
pub(crate) fn new(
window: &Window,
context: &BaseAudioContext,
options: &AudioBufferSourceOptions,

View file

@ -37,7 +37,7 @@ use crate::realms::InRealm;
use crate::script_runtime::CanGc;
#[dom_struct]
pub struct AudioContext {
pub(crate) struct AudioContext {
context: BaseAudioContext,
latency_hint: AudioContextLatencyCategory,
/// <https://webaudio.github.io/web-audio-api/#dom-audiocontext-baselatency>
@ -104,7 +104,7 @@ impl AudioContext {
}
}
pub fn base(&self) -> DomRoot<BaseAudioContext> {
pub(crate) fn base(&self) -> DomRoot<BaseAudioContext> {
DomRoot::from_ref(&self.context)
}
}

View file

@ -16,7 +16,7 @@ use crate::dom::globalscope::GlobalScope;
use crate::script_runtime::CanGc;
#[dom_struct]
pub struct AudioDestinationNode {
pub(crate) struct AudioDestinationNode {
node: AudioNode,
}
@ -39,7 +39,7 @@ impl AudioDestinationNode {
}
#[allow(crown::unrooted_must_root)]
pub fn new(
pub(crate) fn new(
global: &GlobalScope,
context: &BaseAudioContext,
options: &AudioNodeOptions,

View file

@ -22,7 +22,7 @@ use crate::dom::window::Window;
use crate::script_runtime::CanGc;
#[dom_struct]
pub struct AudioListener {
pub(crate) struct AudioListener {
reflector_: Reflector,
position_x: Dom<AudioParam>,
position_y: Dom<AudioParam>,
@ -154,7 +154,7 @@ impl AudioListener {
}
#[allow(crown::unrooted_must_root)]
pub fn new(
pub(crate) fn new(
window: &Window,
context: &BaseAudioContext,
can_gc: CanGc,

View file

@ -28,10 +28,10 @@ use crate::dom::eventtarget::EventTarget;
// 32 is the minimum required by the spec for createBuffer() and the deprecated
// createScriptProcessor() and matches what is used by Blink and Gecko.
// The limit protects against large memory allocations.
pub const MAX_CHANNEL_COUNT: u32 = 32;
pub(crate) const MAX_CHANNEL_COUNT: u32 = 32;
#[dom_struct]
pub struct AudioNode {
pub(crate) struct AudioNode {
eventtarget: EventTarget,
#[ignore_malloc_size_of = "servo_media"]
#[no_trace]
@ -45,7 +45,7 @@ pub struct AudioNode {
}
impl AudioNode {
pub fn new_inherited(
pub(crate) fn new_inherited(
node_type: AudioNodeInit,
context: &BaseAudioContext,
options: UnwrappedAudioNodeOptions,
@ -75,7 +75,7 @@ impl AudioNode {
))
}
pub fn new_inherited_for_id(
pub(crate) fn new_inherited_for_id(
node_id: NodeId,
context: &BaseAudioContext,
options: UnwrappedAudioNodeOptions,
@ -94,7 +94,7 @@ impl AudioNode {
}
}
pub fn message(&self, message: AudioNodeMessage) {
pub(crate) fn message(&self, message: AudioNodeMessage) {
self.context
.audio_context_impl()
.lock()
@ -102,7 +102,7 @@ impl AudioNode {
.message_node(self.node_id, message);
}
pub fn node_id(&self) -> NodeId {
pub(crate) fn node_id(&self) -> NodeId {
self.node_id
}
}
@ -388,7 +388,7 @@ impl Convert<ServoMediaChannelInterpretation> for ChannelInterpretation {
}
impl AudioNodeOptions {
pub fn unwrap_or(
pub(crate) fn unwrap_or(
&self,
count: u32,
mode: ChannelCountMode,
@ -404,10 +404,10 @@ impl AudioNodeOptions {
/// Each node has a set of defaults, so this lets us work with them
/// easily without having to deal with the Options
pub struct UnwrappedAudioNodeOptions {
pub count: u32,
pub mode: ChannelCountMode,
pub interpretation: ChannelInterpretation,
pub(crate) struct UnwrappedAudioNodeOptions {
pub(crate) count: u32,
pub(crate) mode: ChannelCountMode,
pub(crate) interpretation: ChannelInterpretation,
}
impl Default for UnwrappedAudioNodeOptions {

View file

@ -23,7 +23,7 @@ use crate::dom::window::Window;
use crate::script_runtime::CanGc;
#[dom_struct]
pub struct AudioParam {
pub(crate) struct AudioParam {
reflector_: Reflector,
context: Dom<BaseAudioContext>,
#[ignore_malloc_size_of = "servo_media"]
@ -43,7 +43,7 @@ pub struct AudioParam {
impl AudioParam {
#[allow(clippy::too_many_arguments)]
pub fn new_inherited(
pub(crate) fn new_inherited(
context: &BaseAudioContext,
node: NodeId,
node_type: AudioNodeType,
@ -67,7 +67,7 @@ impl AudioParam {
}
#[allow(crown::unrooted_must_root, clippy::too_many_arguments)]
pub fn new(
pub(crate) fn new(
window: &Window,
context: &BaseAudioContext,
node: NodeId,
@ -99,15 +99,15 @@ impl AudioParam {
.message_node(self.node, message);
}
pub fn context(&self) -> &BaseAudioContext {
pub(crate) fn context(&self) -> &BaseAudioContext {
&self.context
}
pub fn node_id(&self) -> NodeId {
pub(crate) fn node_id(&self) -> NodeId {
self.node
}
pub fn param_type(&self) -> ParamType {
pub(crate) fn param_type(&self) -> ParamType {
self.param
}
}

View file

@ -19,7 +19,7 @@ use crate::dom::bindings::refcounted::Trusted;
use crate::dom::bindings::reflector::DomObject;
#[dom_struct]
pub struct AudioScheduledSourceNode {
pub(crate) struct AudioScheduledSourceNode {
node: AudioNode,
has_start: Cell<bool>,
has_stop: Cell<bool>,
@ -27,7 +27,7 @@ pub struct AudioScheduledSourceNode {
impl AudioScheduledSourceNode {
#[allow(crown::unrooted_must_root)]
pub fn new_inherited(
pub(crate) fn new_inherited(
node_type: AudioNodeInit,
context: &BaseAudioContext,
options: UnwrappedAudioNodeOptions,
@ -47,11 +47,11 @@ impl AudioScheduledSourceNode {
})
}
pub fn node(&self) -> &AudioNode {
pub(crate) fn node(&self) -> &AudioNode {
&self.node
}
pub fn has_start(&self) -> bool {
pub(crate) fn has_start(&self) -> bool {
self.has_start.get()
}
}

View file

@ -16,7 +16,7 @@ use crate::dom::window::Window;
use crate::script_runtime::CanGc;
#[dom_struct]
pub struct AudioTrack {
pub(crate) struct AudioTrack {
reflector_: Reflector,
id: DOMString,
kind: DOMString,
@ -27,7 +27,7 @@ pub struct AudioTrack {
}
impl AudioTrack {
pub fn new_inherited(
pub(crate) fn new_inherited(
id: DOMString,
kind: DOMString,
label: DOMString,
@ -45,7 +45,7 @@ impl AudioTrack {
}
}
pub fn new(
pub(crate) fn new(
window: &Window,
id: DOMString,
kind: DOMString,
@ -62,27 +62,27 @@ impl AudioTrack {
)
}
pub fn id(&self) -> DOMString {
pub(crate) fn id(&self) -> DOMString {
self.id.clone()
}
pub fn kind(&self) -> DOMString {
pub(crate) fn kind(&self) -> DOMString {
self.kind.clone()
}
pub fn enabled(&self) -> bool {
pub(crate) fn enabled(&self) -> bool {
self.enabled.get()
}
pub fn set_enabled(&self, value: bool) {
pub(crate) fn set_enabled(&self, value: bool) {
self.enabled.set(value);
}
pub fn add_track_list(&self, track_list: &AudioTrackList) {
pub(crate) fn add_track_list(&self, track_list: &AudioTrackList) {
*self.track_list.borrow_mut() = Some(Dom::from_ref(track_list));
}
pub fn remove_track_list(&self) {
pub(crate) fn remove_track_list(&self) {
*self.track_list.borrow_mut() = None;
}
}

View file

@ -18,14 +18,14 @@ use crate::dom::window::Window;
use crate::script_runtime::CanGc;
#[dom_struct]
pub struct AudioTrackList {
pub(crate) struct AudioTrackList {
eventtarget: EventTarget,
tracks: DomRefCell<Vec<Dom<AudioTrack>>>,
media_element: Option<Dom<HTMLMediaElement>>,
}
impl AudioTrackList {
pub fn new_inherited(
pub(crate) fn new_inherited(
tracks: &[&AudioTrack],
media_element: Option<&HTMLMediaElement>,
) -> AudioTrackList {
@ -36,7 +36,7 @@ impl AudioTrackList {
}
}
pub fn new(
pub(crate) fn new(
window: &Window,
tracks: &[&AudioTrack],
media_element: Option<&HTMLMediaElement>,
@ -48,29 +48,29 @@ impl AudioTrackList {
)
}
pub fn len(&self) -> usize {
pub(crate) fn len(&self) -> usize {
self.tracks.borrow().len()
}
pub fn find(&self, track: &AudioTrack) -> Option<usize> {
pub(crate) fn find(&self, track: &AudioTrack) -> Option<usize> {
self.tracks.borrow().iter().position(|t| &**t == track)
}
pub fn item(&self, idx: usize) -> Option<DomRoot<AudioTrack>> {
pub(crate) fn item(&self, idx: usize) -> Option<DomRoot<AudioTrack>> {
self.tracks
.borrow()
.get(idx)
.map(|track| DomRoot::from_ref(&**track))
}
pub fn enabled_index(&self) -> Option<usize> {
pub(crate) fn enabled_index(&self) -> Option<usize> {
self.tracks
.borrow()
.iter()
.position(|track| track.enabled())
}
pub fn set_enabled(&self, idx: usize, value: bool) {
pub(crate) fn set_enabled(&self, idx: usize, value: bool) {
let track = match self.item(idx) {
Some(t) => t,
None => return,
@ -96,12 +96,12 @@ impl AudioTrackList {
}));
}
pub fn add(&self, track: &AudioTrack) {
pub(crate) fn add(&self, track: &AudioTrack) {
self.tracks.borrow_mut().push(Dom::from_ref(track));
track.add_track_list(self);
}
pub fn clear(&self) {
pub(crate) fn clear(&self) {
self.tracks
.borrow()
.iter()

View file

@ -69,22 +69,22 @@ use crate::realms::InRealm;
use crate::script_runtime::CanGc;
#[allow(dead_code)]
pub enum BaseAudioContextOptions {
pub(crate) enum BaseAudioContextOptions {
AudioContext(RealTimeAudioContextOptions),
OfflineAudioContext(OfflineAudioContextOptions),
}
#[derive(JSTraceable)]
struct DecodeResolver {
pub promise: Rc<Promise>,
pub success_callback: Option<Rc<DecodeSuccessCallback>>,
pub error_callback: Option<Rc<DecodeErrorCallback>>,
pub(crate) promise: Rc<Promise>,
pub(crate) success_callback: Option<Rc<DecodeSuccessCallback>>,
pub(crate) error_callback: Option<Rc<DecodeErrorCallback>>,
}
type BoxedSliceOfPromises = Box<[Rc<Promise>]>;
#[dom_struct]
pub struct BaseAudioContext {
pub(crate) struct BaseAudioContext {
eventtarget: EventTarget,
#[ignore_malloc_size_of = "servo_media"]
#[no_trace]
@ -113,7 +113,7 @@ pub struct BaseAudioContext {
impl BaseAudioContext {
#[allow(crown::unrooted_must_root)]
pub fn new_inherited(
pub(crate) fn new_inherited(
options: BaseAudioContextOptions,
pipeline_id: PipelineId,
) -> Fallible<BaseAudioContext> {
@ -146,24 +146,24 @@ impl BaseAudioContext {
}
/// Tells whether this is an OfflineAudioContext or not.
pub fn is_offline(&self) -> bool {
pub(crate) fn is_offline(&self) -> bool {
false
}
pub fn audio_context_impl(&self) -> Arc<Mutex<AudioContext>> {
pub(crate) fn audio_context_impl(&self) -> Arc<Mutex<AudioContext>> {
self.audio_context_impl.clone()
}
pub fn destination_node(&self) -> NodeId {
pub(crate) fn destination_node(&self) -> NodeId {
self.audio_context_impl.lock().unwrap().dest_node()
}
pub fn listener(&self) -> NodeId {
pub(crate) fn listener(&self) -> NodeId {
self.audio_context_impl.lock().unwrap().listener()
}
// https://webaudio.github.io/web-audio-api/#allowed-to-start
pub fn is_allowed_to_start(&self) -> bool {
pub(crate) fn is_allowed_to_start(&self) -> bool {
self.state.get() == AudioContextState::Suspended
}
@ -219,16 +219,16 @@ impl BaseAudioContext {
}
/// Control thread processing state
pub fn control_thread_state(&self) -> ProcessingState {
pub(crate) fn control_thread_state(&self) -> ProcessingState {
self.audio_context_impl.lock().unwrap().state()
}
/// Set audio context state
pub fn set_state_attribute(&self, state: AudioContextState) {
pub(crate) fn set_state_attribute(&self, state: AudioContextState) {
self.state.set(state);
}
pub fn resume(&self) {
pub(crate) fn resume(&self) {
let this = Trusted::new(self);
// Set the rendering thread state to 'running' and start
// rendering the audio graph.
@ -264,7 +264,7 @@ impl BaseAudioContext {
}
}
pub fn channel_count(&self) -> u32 {
pub(crate) fn channel_count(&self) -> u32 {
self.channel_count
}
}

View file

@ -20,7 +20,7 @@ use crate::script_runtime::CanGc;
// https://html.spec.whatwg.org/multipage/#beforeunloadevent
#[dom_struct]
pub struct BeforeUnloadEvent {
pub(crate) struct BeforeUnloadEvent {
event: Event,
return_value: DomRefCell<DOMString>,
}
@ -33,7 +33,7 @@ impl BeforeUnloadEvent {
}
}
pub fn new_uninitialized(window: &Window) -> DomRoot<BeforeUnloadEvent> {
pub(crate) fn new_uninitialized(window: &Window) -> DomRoot<BeforeUnloadEvent> {
reflect_dom_object(
Box::new(BeforeUnloadEvent::new_inherited()),
window,
@ -41,7 +41,7 @@ impl BeforeUnloadEvent {
)
}
pub fn new(
pub(crate) fn new(
window: &Window,
type_: Atom,
bubbles: EventBubbles,

View file

@ -25,7 +25,7 @@ use crate::script_runtime::JSContext;
/// <https://webidl.spec.whatwg.org/#BufferSource>
#[allow(dead_code)]
pub enum BufferSource {
pub(crate) enum BufferSource {
Int8Array(Box<Heap<*mut JSObject>>),
Int16Array(Box<Heap<*mut JSObject>>),
Int32Array(Box<Heap<*mut JSObject>>),
@ -42,7 +42,7 @@ pub enum BufferSource {
Default(Box<Heap<*mut JSObject>>),
}
pub struct HeapBufferSource<T> {
pub(crate) struct HeapBufferSource<T> {
buffer_source: BufferSource,
phantom: PhantomData<T>,
}
@ -71,7 +71,7 @@ unsafe impl<T> crate::dom::bindings::trace::JSTraceable for HeapBufferSource<T>
}
}
pub fn new_initialized_heap_buffer_source<T>(
pub(crate) fn new_initialized_heap_buffer_source<T>(
init: HeapTypedArrayInit,
) -> Result<HeapBufferSource<T>, ()>
where
@ -116,7 +116,7 @@ where
Ok(heap_buffer_source)
}
pub enum HeapTypedArrayInit {
pub(crate) enum HeapTypedArrayInit {
Buffer(BufferSource),
Info { len: u32, cx: JSContext },
}
@ -126,14 +126,14 @@ where
T: TypedArrayElement + TypedArrayElementCreator,
T::Element: Clone + Copy,
{
pub fn default() -> HeapBufferSource<T> {
pub(crate) fn default() -> HeapBufferSource<T> {
HeapBufferSource {
buffer_source: BufferSource::Default(Box::default()),
phantom: PhantomData,
}
}
pub fn set_data(&self, cx: JSContext, data: &[T::Element]) -> Result<(), ()> {
pub(crate) fn set_data(&self, cx: JSContext, data: &[T::Element]) -> Result<(), ()> {
rooted!(in (*cx) let mut array = ptr::null_mut::<JSObject>());
let _: TypedArray<T, *mut JSObject> = create_buffer_source(cx, data, array.handle_mut())?;
@ -158,7 +158,7 @@ where
Ok(())
}
pub fn acquire_data(&self, cx: JSContext) -> Result<Vec<T::Element>, ()> {
pub(crate) fn acquire_data(&self, cx: JSContext) -> Result<Vec<T::Element>, ()> {
assert!(self.is_initialized());
typedarray!(in(*cx) let array: TypedArray = match &self.buffer_source {
@ -211,7 +211,7 @@ where
}
/// <https://tc39.es/ecma262/#sec-detacharraybuffer>
pub fn detach_buffer(&self, cx: JSContext) -> bool {
pub(crate) fn detach_buffer(&self, cx: JSContext) -> bool {
match &self.buffer_source {
BufferSource::Int8Array(buffer) |
BufferSource::Int16Array(buffer) |
@ -247,7 +247,7 @@ where
}
}
pub fn copy_data_to(
pub(crate) fn copy_data_to(
&self,
cx: JSContext,
dest: &mut [T::Element],
@ -285,7 +285,7 @@ where
Ok(())
}
pub fn copy_data_from(
pub(crate) fn copy_data_from(
&self,
cx: JSContext,
source: CustomAutoRooterGuard<TypedArray<T, *mut JSObject>>,
@ -324,7 +324,7 @@ where
Ok(())
}
pub fn is_initialized(&self) -> bool {
pub(crate) fn is_initialized(&self) -> bool {
match &self.buffer_source {
BufferSource::Int8Array(buffer) |
BufferSource::Int16Array(buffer) |
@ -343,7 +343,7 @@ where
}
}
pub fn get_buffer(&self) -> Result<TypedArray<T, *mut JSObject>, ()> {
pub(crate) fn get_buffer(&self) -> Result<TypedArray<T, *mut JSObject>, ()> {
TypedArray::from(match &self.buffer_source {
BufferSource::Int8Array(buffer) |
BufferSource::Int16Array(buffer) |
@ -362,7 +362,7 @@ where
})
}
pub fn buffer_to_option(&self) -> Option<TypedArray<T, *mut JSObject>> {
pub(crate) fn buffer_to_option(&self) -> Option<TypedArray<T, *mut JSObject>> {
if self.is_initialized() {
Some(self.get_buffer().expect("Failed to get buffer."))
} else {
@ -373,7 +373,7 @@ where
}
/// <https://webidl.spec.whatwg.org/#arraybufferview-create>
pub fn create_buffer_source<T>(
pub(crate) fn create_buffer_source<T>(
cx: JSContext,
data: &[T::Element],
dest: MutableHandleObject,
@ -408,7 +408,7 @@ where
}
#[derive(JSTraceable, MallocSizeOf)]
pub struct DataBlock {
pub(crate) struct DataBlock {
#[ignore_malloc_size_of = "Arc"]
data: Arc<Box<[u8]>>,
/// Data views (mutable subslices of data)
@ -422,7 +422,7 @@ fn range_overlap<T: std::cmp::PartialOrd>(range1: &Range<T>, range2: &Range<T>)
}
impl DataBlock {
pub fn new_zeroed(size: usize) -> Self {
pub(crate) fn new_zeroed(size: usize) -> Self {
let data = vec![0; size];
Self {
data: Arc::new(data.into_boxed_slice()),
@ -431,23 +431,23 @@ impl DataBlock {
}
/// Panics if there is any active view or src data is not same length
pub fn load(&mut self, src: &[u8]) {
pub(crate) fn load(&mut self, src: &[u8]) {
// `Arc::get_mut` ensures there are no views
Arc::get_mut(&mut self.data).unwrap().clone_from_slice(src)
}
/// Panics if there is any active view
pub fn data(&mut self) -> &mut [u8] {
pub(crate) fn data(&mut self) -> &mut [u8] {
// `Arc::get_mut` ensures there are no views
Arc::get_mut(&mut self.data).unwrap()
}
pub fn clear_views(&mut self) {
pub(crate) fn clear_views(&mut self) {
self.data_views.clear()
}
/// Returns error if requested range is already mapped
pub fn view(&mut self, range: Range<usize>) -> Result<&DataView, ()> {
pub(crate) fn view(&mut self, range: Range<usize>) -> Result<&DataView, ()> {
if self
.data_views
.iter()
@ -485,7 +485,7 @@ impl DataBlock {
}
#[derive(JSTraceable, MallocSizeOf)]
pub struct DataView {
pub(crate) struct DataView {
#[no_trace]
range: Range<usize>,
#[ignore_malloc_size_of = "defined in mozjs"]
@ -493,7 +493,7 @@ pub struct DataView {
}
impl DataView {
pub fn array_buffer(&self) -> ArrayBuffer {
pub(crate) fn array_buffer(&self) -> ArrayBuffer {
unsafe { ArrayBuffer::from(self.buffer.underlying_object().get()).unwrap() }
}
}

View file

@ -31,7 +31,7 @@ use crate::script_runtime::{CanGc, JSContext};
/// The exception handling used for a call.
#[derive(Clone, Copy, PartialEq)]
pub enum ExceptionHandling {
pub(crate) enum ExceptionHandling {
/// Report any exception and don't throw it to the caller code.
Report,
/// Throw any exception to the caller code.
@ -42,7 +42,7 @@ pub enum ExceptionHandling {
/// callback interface types.
#[derive(JSTraceable)]
#[crown::unrooted_must_root_lint::must_root]
pub struct CallbackObject {
pub(crate) struct CallbackObject {
/// The underlying `JSObject`.
callback: Heap<*mut JSObject>,
permanent_js_root: Heap<JSVal>,
@ -73,7 +73,7 @@ impl CallbackObject {
}
}
pub fn get(&self) -> *mut JSObject {
pub(crate) fn get(&self) -> *mut JSObject {
self.callback.get()
}
@ -108,7 +108,7 @@ impl PartialEq for CallbackObject {
/// A trait to be implemented by concrete IDL callback function and
/// callback interface types.
pub trait CallbackContainer {
pub(crate) trait CallbackContainer {
/// Create a new CallbackContainer object for the given `JSObject`.
unsafe fn new(cx: JSContext, callback: *mut JSObject) -> Rc<Self>;
/// Returns the underlying `CallbackObject`.
@ -129,7 +129,7 @@ pub trait CallbackContainer {
/// A common base class for representing IDL callback function types.
#[derive(JSTraceable, PartialEq)]
#[crown::unrooted_must_root_lint::must_root]
pub struct CallbackFunction {
pub(crate) struct CallbackFunction {
object: CallbackObject,
}
@ -138,20 +138,20 @@ impl CallbackFunction {
#[allow(crown::unrooted_must_root)]
// These are used by the bindings and do not need `default()` functions.
#[allow(clippy::new_without_default)]
pub fn new() -> CallbackFunction {
pub(crate) fn new() -> CallbackFunction {
CallbackFunction {
object: CallbackObject::new(),
}
}
/// Returns the underlying `CallbackObject`.
pub fn callback_holder(&self) -> &CallbackObject {
pub(crate) fn callback_holder(&self) -> &CallbackObject {
&self.object
}
/// Initialize the callback function with a value.
/// Should be called once this object is done moving.
pub unsafe fn init(&mut self, cx: JSContext, callback: *mut JSObject) {
pub(crate) unsafe fn init(&mut self, cx: JSContext, callback: *mut JSObject) {
self.object.init(cx, callback);
}
}
@ -159,7 +159,7 @@ impl CallbackFunction {
/// A common base class for representing IDL callback interface types.
#[derive(JSTraceable, PartialEq)]
#[crown::unrooted_must_root_lint::must_root]
pub struct CallbackInterface {
pub(crate) struct CallbackInterface {
object: CallbackObject,
}
@ -167,26 +167,26 @@ impl CallbackInterface {
/// Create a new CallbackInterface object for the given `JSObject`.
// These are used by the bindings and do not need `default()` functions.
#[allow(clippy::new_without_default)]
pub fn new() -> CallbackInterface {
pub(crate) fn new() -> CallbackInterface {
CallbackInterface {
object: CallbackObject::new(),
}
}
/// Returns the underlying `CallbackObject`.
pub fn callback_holder(&self) -> &CallbackObject {
pub(crate) fn callback_holder(&self) -> &CallbackObject {
&self.object
}
/// Initialize the callback function with a value.
/// Should be called once this object is done moving.
pub unsafe fn init(&mut self, cx: JSContext, callback: *mut JSObject) {
pub(crate) unsafe fn init(&mut self, cx: JSContext, callback: *mut JSObject) {
self.object.init(cx, callback);
}
/// Returns the property with the given `name`, if it is a callable object,
/// or an error otherwise.
pub fn get_callable_property(&self, cx: JSContext, name: &str) -> Fallible<JSVal> {
pub(crate) fn get_callable_property(&self, cx: JSContext, name: &str) -> Fallible<JSVal> {
rooted!(in(*cx) let mut callable = UndefinedValue());
rooted!(in(*cx) let obj = self.callback_holder().get());
unsafe {
@ -206,7 +206,7 @@ impl CallbackInterface {
}
}
pub trait ThisReflector {
pub(crate) trait ThisReflector {
fn jsobject(&self) -> *mut JSObject;
}
@ -223,7 +223,7 @@ impl ThisReflector for HandleObject<'_> {
}
/// Wraps the reflector for `p` into the realm of `cx`.
pub fn wrap_call_this_object<T: ThisReflector>(
pub(crate) fn wrap_call_this_object<T: ThisReflector>(
cx: JSContext,
p: &T,
mut rval: MutableHandleObject,
@ -240,7 +240,7 @@ pub fn wrap_call_this_object<T: ThisReflector>(
/// A class that performs whatever setup we need to safely make a call while
/// this class is on the stack. After `new` returns, the call is safe to make.
pub struct CallSetup {
pub(crate) struct CallSetup {
/// The global for reporting exceptions. This is the global object of the
/// (possibly wrapped) callback object.
exception_global: DomRoot<GlobalScope>,
@ -261,7 +261,10 @@ pub struct CallSetup {
impl CallSetup {
/// Performs the setup needed to make a call.
#[allow(crown::unrooted_must_root)]
pub fn new<T: CallbackContainer>(callback: &T, handling: ExceptionHandling) -> CallSetup {
pub(crate) fn new<T: CallbackContainer>(
callback: &T,
handling: ExceptionHandling,
) -> CallSetup {
let global = unsafe { GlobalScope::from_object(callback.callback()) };
if let Some(window) = global.downcast::<Window>() {
window.Document().ensure_safe_to_run_script_or_layout();
@ -281,7 +284,7 @@ impl CallSetup {
}
/// Returns the `JSContext` used for the call.
pub fn get_context(&self) -> JSContext {
pub(crate) fn get_context(&self) -> JSContext {
self.cx
}
}

View file

@ -6,12 +6,12 @@
use std::cell::{BorrowError, BorrowMutError};
#[cfg(not(feature = "refcell_backtrace"))]
pub use std::cell::{Ref, RefCell, RefMut};
pub(crate) use std::cell::{Ref, RefCell, RefMut};
#[cfg(feature = "refcell_backtrace")]
pub use accountable_refcell::{ref_filter_map, Ref, RefCell, RefMut};
pub(crate) use accountable_refcell::{ref_filter_map, Ref, RefCell, RefMut};
#[cfg(not(feature = "refcell_backtrace"))]
pub use ref_filter_map::ref_filter_map;
pub(crate) use ref_filter_map::ref_filter_map;
use crate::dom::bindings::root::{assert_in_layout, assert_in_script};
@ -20,7 +20,7 @@ use crate::dom::bindings::root::{assert_in_layout, assert_in_script};
/// This extends the API of `std::cell::RefCell` to allow unsafe access in
/// certain situations, with dynamic checking in debug builds.
#[derive(Clone, Debug, Default, MallocSizeOf, PartialEq)]
pub struct DomRefCell<T> {
pub(crate) struct DomRefCell<T> {
value: RefCell<T>,
}
@ -42,7 +42,7 @@ impl<T> DomRefCell<T> {
///
/// Panics if the value is currently mutably borrowed.
#[allow(unsafe_code)]
pub unsafe fn borrow_for_layout(&self) -> &T {
pub(crate) unsafe fn borrow_for_layout(&self) -> &T {
assert_in_layout();
self.value
.try_borrow_unguarded()
@ -61,7 +61,7 @@ impl<T> DomRefCell<T> {
///
/// Panics if this is called from anywhere other than the script thread.
#[allow(unsafe_code, clippy::mut_from_ref)]
pub unsafe fn borrow_for_script_deallocation(&self) -> &mut T {
pub(crate) unsafe fn borrow_for_script_deallocation(&self) -> &mut T {
assert_in_script();
&mut *self.value.as_ptr()
}
@ -79,7 +79,7 @@ impl<T> DomRefCell<T> {
///
/// Panics if this is called from anywhere other than the layout thread.
#[allow(unsafe_code, clippy::mut_from_ref)]
pub unsafe fn borrow_mut_for_layout(&self) -> &mut T {
pub(crate) unsafe fn borrow_mut_for_layout(&self) -> &mut T {
assert_in_layout();
&mut *self.value.as_ptr()
}
@ -89,7 +89,7 @@ impl<T> DomRefCell<T> {
// ===================================================
impl<T> DomRefCell<T> {
/// Create a new `DomRefCell` containing `value`.
pub fn new(value: T) -> DomRefCell<T> {
pub(crate) fn new(value: T) -> DomRefCell<T> {
DomRefCell {
value: RefCell::new(value),
}
@ -104,7 +104,7 @@ impl<T> DomRefCell<T> {
///
/// Panics if the value is currently mutably borrowed.
#[track_caller]
pub fn borrow(&self) -> Ref<T> {
pub(crate) fn borrow(&self) -> Ref<T> {
self.value.borrow()
}
@ -117,7 +117,7 @@ impl<T> DomRefCell<T> {
///
/// Panics if the value is currently borrowed.
#[track_caller]
pub fn borrow_mut(&self) -> RefMut<T> {
pub(crate) fn borrow_mut(&self) -> RefMut<T> {
self.value.borrow_mut()
}
@ -131,7 +131,7 @@ impl<T> DomRefCell<T> {
/// # Panics
///
/// Panics if this is called off the script thread.
pub fn try_borrow(&self) -> Result<Ref<T>, BorrowError> {
pub(crate) fn try_borrow(&self) -> Result<Ref<T>, BorrowError> {
assert_in_script();
self.value.try_borrow()
}
@ -146,7 +146,7 @@ impl<T> DomRefCell<T> {
/// # Panics
///
/// Panics if this is called off the script thread.
pub fn try_borrow_mut(&self) -> Result<RefMut<T>, BorrowMutError> {
pub(crate) fn try_borrow_mut(&self) -> Result<RefMut<T>, BorrowMutError> {
assert_in_script();
self.value.try_borrow_mut()
}

View file

@ -2281,7 +2281,7 @@ class CGTemplatedType(CGWrapper):
class CGNamespace(CGWrapper):
def __init__(self, namespace, child, public=False):
pub = "pub " if public else ""
pub = "pub(crate) " if public else ""
pre = f"{pub}mod {namespace} {{\n"
post = f"}} // mod {namespace}"
CGWrapper.__init__(self, child, pre=pre, post=post)
@ -2656,7 +2656,7 @@ def DomTypes(descriptors, descriptorProvider, dictionaries, callbacks, typedefs,
"Sized",
]
joinedTraits = ' + '.join(traits)
elements = [CGGeneric(f"pub trait DomTypes: {joinedTraits} where Self: 'static {{\n")]
elements = [CGGeneric(f"pub(crate) trait DomTypes: {joinedTraits} where Self: 'static {{\n")]
for descriptor in descriptors:
iface_name = descriptor.interface.identifier.name
traits = []
@ -2737,7 +2737,7 @@ def DomTypeHolder(descriptors, descriptorProvider, dictionaries, callbacks, type
elements = [
CGGeneric(
"#[derive(JSTraceable, MallocSizeOf, PartialEq)]\n"
"pub struct DomTypeHolder;\n"
"pub(crate) struct DomTypeHolder;\n"
"impl crate::DomTypes for DomTypeHolder {\n"
),
]
@ -4882,7 +4882,7 @@ class CGEnum(CGThing):
decl = f"""
#[repr(usize)]
#[derive({derives})]
pub enum {ident} {{
pub(crate) enum {ident} {{
{enums}
}}
"""
@ -4900,12 +4900,12 @@ use js::rust::HandleValue;
use js::rust::MutableHandleValue;
use js::jsval::JSVal;
pub const pairs: &[(&str, super::{ident})] = &[
pub(crate) const pairs: &[(&str, super::{ident})] = &[
{pairs},
];
impl super::{ident} {{
pub fn as_str(&self) -> &'static str {{
pub(crate) fn as_str(&self) -> &'static str {{
pairs[*self as usize].0
}}
}}
@ -4994,7 +4994,7 @@ class CGConstant(CGThing):
elif tag == IDLType.Tags.double:
const_type = "f64"
return f"pub const {name}: {const_type} = {value};\n"
return f"pub(crate) const {name}: {const_type} = {value};\n"
def getUnionTypeTemplateVars(type, descriptorProvider):
@ -5093,7 +5093,7 @@ class CGUnionStruct(CGThing):
derives = ["JSTraceable"] + self.derives
return f"""
#[derive({", ".join(derives)})]
pub enum {self.type} {{
pub(crate) enum {self.type} {{
{joinedEnumValues}
}}
@ -5468,7 +5468,7 @@ class ClassConstructor(ClassItem):
body = f' {{\n{body}}}'
return f"""
pub unsafe fn {self.getDecorators(True)}new({args}) -> Rc<{cgClass.getNameString()}>{body}
pub(crate) unsafe fn {self.getDecorators(True)}new({args}) -> Rc<{cgClass.getNameString()}>{body}
"""
def define(self, cgClass):
@ -5560,7 +5560,7 @@ class CGClass(CGThing):
myself = ''
if self.decorators != '':
myself += f'{self.decorators}\n'
myself += f'{self.indent}pub struct {self.name}{specialization}'
myself += f'{self.indent}pub(crate) struct {self.name}{specialization}'
result += myself
assert len(self.bases) == 1 # XXjdm Can we support multiple inheritance?
@ -5568,7 +5568,7 @@ class CGClass(CGThing):
result += ' {\n'
if self.bases:
self.members = [ClassMember("parent", self.bases[0].name, "pub")] + self.members
self.members = [ClassMember("parent", self.bases[0].name, "pub(crate)")] + self.members
result += CGIndenter(CGGeneric(self.extradeclarations),
len(self.indent)).define()
@ -6628,8 +6628,9 @@ class CGInterfaceTrait(CGThing):
methods.append(CGGeneric("fn Length(&self) -> u32;\n"))
if methods:
name = descriptor.interface.identifier.name
self.cgRoot = CGWrapper(CGIndenter(CGList(methods, "")),
pre=f"pub trait {descriptor.interface.identifier.name}Methods<D: DomTypes> {{\n",
pre=f"pub(crate) trait {name}Methods<D: DomTypes> {{\n",
post="}")
else:
self.cgRoot = CGGeneric("")
@ -6950,7 +6951,8 @@ class CGDescriptor(CGThing):
if reexports:
reexports = ', '.join([reexportedName(name) for name in reexports])
cgThings = CGList([CGGeneric(f'pub use self::{toBindingNamespace(descriptor.name)}::{{{reexports}}};'),
namespace = toBindingNamespace(descriptor.name)
cgThings = CGList([CGGeneric(f'pub(crate) use self::{namespace}::{{{reexports}}};'),
cgThings], '\n')
self.cgRoot = cgThings
@ -6972,7 +6974,7 @@ class CGNonNamespacedEnum(CGThing):
# Build the enum body.
joinedEntries = ',\n'.join(entries)
enumstr = f"{comment}pub enum {enumName} {{\n{joinedEntries}\n}}\n"
enumstr = f"{comment}pub(crate) enum {enumName} {{\n{joinedEntries}\n}}\n"
if repr:
enumstr = f"#[repr({repr})]\n{enumstr}"
if deriving:
@ -7025,10 +7027,10 @@ class CGDictionary(CGThing):
typeName = f"{self.makeModuleName(d.parent)}::{self.makeClassName(d.parent)}"
if type_needs_tracing(d.parent):
typeName = f"RootedTraceableBox<{typeName}>"
inheritance = f" pub parent: {typeName},\n"
inheritance = f" pub(crate) parent: {typeName},\n"
else:
inheritance = ""
memberDecls = [f" pub {self.makeMemberName(m[0].identifier.name)}: {self.getMemberType(m)},"
memberDecls = [f" pub(crate) {self.makeMemberName(m[0].identifier.name)}: {self.getMemberType(m)},"
for m in self.memberInfo]
derive = ["JSTraceable"] + self.derives
@ -7069,7 +7071,7 @@ class CGDictionary(CGThing):
return (
f"#[derive({', '.join(derive)})]\n"
f"{mustRoot}"
f"pub struct {self.makeClassName(d)} {{\n"
f"pub(crate) struct {self.makeClassName(d)} {{\n"
f"{inheritance}"
f"{joinedMemberDecls}\n"
"}\n"
@ -7142,7 +7144,7 @@ class CGDictionary(CGThing):
return (
f"impl {selfName} {{\n"
f"{CGIndenter(CGGeneric(self.makeEmpty()), indentLevel=4).define()}\n"
" pub fn new(cx: SafeJSContext, val: HandleValue) \n"
" pub(crate) fn new(cx: SafeJSContext, val: HandleValue) \n"
f" -> Result<ConversionResult<{actualType}>, ()> {{\n"
f" {unsafe_if_necessary} {{\n"
" let object = if val.get().is_null_or_undefined() {\n"
@ -7246,7 +7248,7 @@ class CGDictionary(CGThing):
parentTemplate = "parent: %s::%s::empty(),\n"
fieldTemplate = "%s: %s,\n"
functionTemplate = (
"pub fn empty() -> Self {\n"
"pub(crate) fn empty() -> Self {\n"
" Self {\n"
"%s"
" }\n"
@ -7256,7 +7258,7 @@ class CGDictionary(CGThing):
parentTemplate = "dictionary.parent = %s::%s::empty();\n"
fieldTemplate = "dictionary.%s = %s;\n"
functionTemplate = (
"pub fn empty() -> RootedTraceableBox<Self> {\n"
"pub(crate) fn empty() -> RootedTraceableBox<Self> {\n"
" let mut dictionary = RootedTraceableBox::new(Self::default());\n"
"%s"
" dictionary\n"
@ -7341,14 +7343,14 @@ class CGRegisterProxyHandlers(CGThing):
def __init__(self, config):
descriptors = config.getDescriptors(proxy=True)
body = "".join(
f" pub static {desc.name}: std::sync::atomic::AtomicPtr<libc::c_void> =\n"
f" pub(crate) static {desc.name}: std::sync::atomic::AtomicPtr<libc::c_void> =\n"
" std::sync::atomic::AtomicPtr::new(std::ptr::null_mut());\n"
for desc in descriptors
)
self.root = CGList([
CGGeneric(
"#[allow(non_upper_case_globals)]\n"
"pub mod proxy_handlers {\n"
"pub(crate) mod proxy_handlers {\n"
f"{body}}}\n"
),
CGRegisterProxyHandlersMethod(descriptors),
@ -7400,9 +7402,9 @@ class CGBindingRoot(CGThing):
if t.innerType.isUnion() and not t.innerType.nullable():
# Allow using the typedef's name for accessing variants.
typeDefinition = f"pub use self::{type} as {name};"
typeDefinition = f"pub(crate) use self::{type} as {name};"
else:
typeDefinition = f"pub type {name} = {type};"
typeDefinition = f"pub(crate) type {name} = {type};"
cgthings.append(CGGeneric(typeDefinition))
@ -8207,7 +8209,6 @@ class GlobalGenRoots():
"crate::dom::bindings::codegen",
"crate::script_runtime::JSContext",
"js::rust::HandleObject",
"phf",
]
imports = CGList([CGGeneric(f"use {mod};") for mod in mods], "\n")
@ -8220,7 +8221,7 @@ class GlobalGenRoots():
global_flags = CGWrapper(CGIndenter(CGList([
CGGeneric(f"const {args[0]} = {args[1]};")
for args in flags
], "\n")), pre="#[derive(Clone, Copy)]\npub struct Globals: u8 {\n", post="\n}")
], "\n")), pre="#[derive(Clone, Copy)]\npub(crate) struct Globals: u8 {\n", post="\n}")
globals_ = CGWrapper(CGIndenter(global_flags), pre="bitflags::bitflags! {\n", post="\n}")
phf = CGGeneric("include!(concat!(env!(\"OUT_DIR\"), \"/InterfaceObjectMapPhf.rs\"));")
@ -8262,9 +8263,9 @@ class GlobalGenRoots():
return CGList([
CGGeneric(AUTOGENERATED_WARNING_COMMENT),
CGGeneric(f"pub const PROTO_OR_IFACE_LENGTH: usize = {len(protos) + len(constructors)};\n"),
CGGeneric(f"pub const MAX_PROTO_CHAIN_LENGTH: usize = {config.maxProtoChainLength};\n\n"),
CGGeneric("#[allow(clippy::enum_variant_names)]"),
CGGeneric(f"pub(crate) const PROTO_OR_IFACE_LENGTH: usize = {len(protos) + len(constructors)};\n"),
CGGeneric(f"pub(crate) const MAX_PROTO_CHAIN_LENGTH: usize = {config.maxProtoChainLength};\n\n"),
CGGeneric("#[allow(clippy::enum_variant_names, dead_code)]"),
CGNonNamespacedEnum('ID', protos, 0, deriving="PartialEq, Copy, Clone", repr="u16"),
CGNonNamespacedEnum('Constructor', constructors, len(protos),
deriving="PartialEq, Copy, Clone", repr="u16"),
@ -8273,7 +8274,7 @@ class GlobalGenRoots():
indentLevel=4),
pre=f"static INTERFACES: [&str; {len(protos)}] = [\n",
post="\n];\n\n"),
CGGeneric("pub fn proto_id_to_name(proto_id: u16) -> &'static str {\n"
CGGeneric("pub(crate) fn proto_id_to_name(proto_id: u16) -> &'static str {\n"
" debug_assert!(proto_id < ID::Last as u16);\n"
" INTERFACES[proto_id as usize]\n"
"}\n\n"),
@ -8296,7 +8297,7 @@ class GlobalGenRoots():
for d in config.getDescriptors(register=True,
isCallback=False,
isIteratorInterface=False)])
curr = CGList([CGGeneric(f"pub use crate::dom::{name.lower()}::{MakeNativeName(name)};\n")
curr = CGList([CGGeneric(f"pub(crate) use crate::dom::{name.lower()}::{MakeNativeName(name)};\n")
for name in descriptors])
curr = CGWrapper(curr, pre=AUTOGENERATED_WARNING_COMMENT)
return curr
@ -8313,7 +8314,7 @@ class GlobalGenRoots():
| set(leafModule(d) for d in config.getDictionaries()))
curr = CGList([CGGeneric(
"#[allow(clippy::derivable_impls)]\n"
f"pub mod {name};\n"
f"pub(crate) mod {name};\n"
) for name in sorted(descriptors)])
curr = CGWrapper(curr, pre=AUTOGENERATED_WARNING_COMMENT)
return curr
@ -8360,17 +8361,17 @@ class GlobalGenRoots():
typeIdCode = []
topTypeVariants = [
("ID used by abstract interfaces.", "pub abstract_: ()"),
("ID used by interfaces that are not castable.", "pub alone: ()"),
("ID used by abstract interfaces.", "pub(crate) abstract_: ()"),
("ID used by interfaces that are not castable.", "pub(crate) alone: ()"),
]
topTypeVariants += [
(f"ID used by interfaces that derive from {typeName}.",
f"pub {typeName.lower()}: {typeName}TypeId")
f"pub(crate) {typeName.lower()}: {typeName}TypeId")
for typeName in topTypes
]
topTypeVariantsAsStrings = [CGGeneric(f"/// {variant[0]}\n{variant[1]},") for variant in topTypeVariants]
typeIdCode.append(CGWrapper(CGIndenter(CGList(topTypeVariantsAsStrings, "\n"), 4),
pre="#[derive(Copy)]\npub union TopTypeId {\n",
pre="#[derive(Copy)]\npub(crate) union TopTypeId {\n",
post="\n}\n\n"))
typeIdCode.append(CGGeneric("""\
@ -8393,12 +8394,12 @@ impl Clone for TopTypeId {
variants += [CGGeneric(type_id_variant(derivedName)) for derivedName in derived]
derives = "Clone, Copy, Debug, PartialEq"
typeIdCode.append(CGWrapper(CGIndenter(CGList(variants, ",\n"), 4),
pre=f"#[derive({derives})]\npub enum {base}TypeId {{\n",
pre=f"#[derive({derives})]\npub(crate) enum {base}TypeId {{\n",
post="\n}\n\n"))
if base in topTypes:
typeIdCode.append(CGGeneric(f"""
impl {base} {{
pub fn type_id(&self) -> &'static {base}TypeId {{
pub(crate) fn type_id(&self) -> &'static {base}TypeId {{
unsafe {{
&get_dom_class(self.reflector().get_jsobject().get())
.unwrap()

View file

@ -15,17 +15,17 @@ use crate::script_runtime::JSContext;
/// Representation of an IDL constant.
#[derive(Clone)]
pub struct ConstantSpec {
pub(crate) struct ConstantSpec {
/// name of the constant.
pub name: &'static CStr,
pub(crate) name: &'static CStr,
/// value of the constant.
pub value: ConstantVal,
pub(crate) value: ConstantVal,
}
/// Representation of an IDL constant value.
#[derive(Clone)]
#[allow(dead_code)]
pub enum ConstantVal {
pub(crate) enum ConstantVal {
/// `long` constant.
Int(i32),
/// `unsigned long` constant.
@ -40,7 +40,7 @@ pub enum ConstantVal {
impl ConstantSpec {
/// Returns a `JSVal` that represents the value of this `ConstantSpec`.
pub fn get_value(&self) -> JSVal {
pub(crate) fn get_value(&self) -> JSVal {
match self.value {
ConstantVal::Null => NullValue(),
ConstantVal::Int(i) => Int32Value(i),
@ -53,7 +53,7 @@ impl ConstantSpec {
/// Defines constants on `obj`.
/// Fails on JSAPI failure.
pub fn define_constants(cx: JSContext, obj: HandleObject, constants: &[ConstantSpec]) {
pub(crate) fn define_constants(cx: JSContext, obj: HandleObject, constants: &[ConstantSpec]) {
for spec in constants {
rooted!(in(*cx) let value = spec.get_value());
unsafe {

View file

@ -226,7 +226,7 @@ unsafe fn html_constructor(
/// given local name. This list should only include elements marked with the
/// [HTMLConstructor](https://html.spec.whatwg.org/multipage/#htmlconstructor)
/// extended attribute.
pub fn get_constructor_object_from_local_name(
pub(crate) fn get_constructor_object_from_local_name(
name: LocalName,
cx: JSContext,
global: HandleObject,
@ -370,15 +370,15 @@ pub fn get_constructor_object_from_local_name(
}
}
pub fn pop_current_element_queue(can_gc: CanGc) {
pub(crate) fn pop_current_element_queue(can_gc: CanGc) {
ScriptThread::pop_current_element_queue(can_gc);
}
pub fn push_new_element_queue() {
pub(crate) fn push_new_element_queue() {
ScriptThread::push_new_element_queue();
}
pub unsafe fn call_html_constructor<T: DerivedFrom<Element> + DomObject>(
pub(crate) unsafe fn call_html_constructor<T: DerivedFrom<Element> + DomObject>(
cx: JSContext,
args: &CallArgs,
global: &GlobalScope,
@ -402,7 +402,7 @@ pub unsafe fn call_html_constructor<T: DerivedFrom<Element> + DomObject>(
.is_ok()
}
pub unsafe fn call_default_constructor(
pub(crate) unsafe fn call_default_constructor(
cx: JSContext,
args: &CallArgs,
global: &GlobalScope,

View file

@ -35,7 +35,7 @@
use std::{char, ffi, ptr, slice};
use js::conversions::latin1_to_string;
pub use js::conversions::{
pub(crate) use js::conversions::{
ConversionBehavior, ConversionResult, FromJSValConvertible, ToJSValConvertible,
};
use js::error::throw_type_error;
@ -70,13 +70,13 @@ use crate::dom::nodelist::NodeList;
use crate::dom::windowproxy::WindowProxy;
/// A trait to check whether a given `JSObject` implements an IDL interface.
pub trait IDLInterface {
pub(crate) trait IDLInterface {
/// Returns whether the given DOM class derives that interface.
fn derives(_: &'static DOMClass) -> bool;
}
/// A trait to mark an IDL interface as deriving from another one.
pub trait DerivedFrom<T: Castable>: Castable {}
pub(crate) trait DerivedFrom<T: Castable>: Castable {}
impl<T: Float + ToJSValConvertible> ToJSValConvertible for Finite<T> {
#[inline]
@ -160,7 +160,7 @@ where
/// integer.
///
/// Handling of invalid UTF-16 in strings depends on the relevant option.
pub unsafe fn jsid_to_string(cx: *mut JSContext, id: HandleId) -> Option<DOMString> {
pub(crate) unsafe fn jsid_to_string(cx: *mut JSContext, id: HandleId) -> Option<DOMString> {
let id_raw = *id;
if id_raw.is_string() {
let jsstr = std::ptr::NonNull::new(id_raw.to_string()).unwrap();
@ -221,7 +221,7 @@ impl FromJSValConvertible for DOMString {
/// Convert the given `JSString` to a `DOMString`. Fails if the string does not
/// contain valid UTF-16.
pub unsafe fn jsstring_to_str(cx: *mut JSContext, s: ptr::NonNull<JSString>) -> DOMString {
pub(crate) unsafe fn jsstring_to_str(cx: *mut JSContext, s: ptr::NonNull<JSString>) -> DOMString {
let latin1 = JS_DeprecatedStringHasLatin1Chars(s.as_ptr());
DOMString::from_string(if latin1 {
latin1_to_string(cx, s.as_ptr())
@ -355,7 +355,7 @@ impl ToJSValConvertible for Reflector {
}
/// Returns whether `obj` is a DOM object implemented as a proxy.
pub fn is_dom_proxy(obj: *mut JSObject) -> bool {
pub(crate) fn is_dom_proxy(obj: *mut JSObject) -> bool {
use js::glue::IsProxyHandlerFamily;
unsafe {
let clasp = get_object_class(obj);
@ -367,10 +367,10 @@ pub fn is_dom_proxy(obj: *mut JSObject) -> bool {
/// stored for non-proxy bindings.
// We use slot 0 for holding the raw object. This is safe for both
// globals and non-globals.
pub const DOM_OBJECT_SLOT: u32 = 0;
pub(crate) const DOM_OBJECT_SLOT: u32 = 0;
/// Get the private pointer of a DOM object from a given reflector.
pub unsafe fn private_from_object(obj: *mut JSObject) -> *const libc::c_void {
pub(crate) unsafe fn private_from_object(obj: *mut JSObject) -> *const libc::c_void {
let mut value = UndefinedValue();
if is_dom_object(obj) {
JS_GetReservedSlot(obj, DOM_OBJECT_SLOT, &mut value);
@ -386,7 +386,7 @@ pub unsafe fn private_from_object(obj: *mut JSObject) -> *const libc::c_void {
}
/// Get the `DOMClass` from `obj`, or `Err(())` if `obj` is not a DOM object.
pub unsafe fn get_dom_class(obj: *mut JSObject) -> Result<&'static DOMClass, ()> {
pub(crate) unsafe fn get_dom_class(obj: *mut JSObject) -> Result<&'static DOMClass, ()> {
use js::glue::GetProxyHandlerExtra;
use crate::dom::bindings::utils::DOMJSClass;
@ -478,7 +478,7 @@ unsafe fn private_from_proto_check_static(
}
/// Get a `*const T` for a DOM object accessible from a `JSObject`.
pub fn native_from_object<T>(obj: *mut JSObject, cx: *mut JSContext) -> Result<*const T, ()>
pub(crate) fn native_from_object<T>(obj: *mut JSObject, cx: *mut JSContext) -> Result<*const T, ()>
where
T: DomObject + IDLInterface,
{
@ -490,7 +490,7 @@ where
/// Get a `*const T` for a DOM object accessible from a `JSObject`, where the DOM object
/// is guaranteed not to be a wrapper.
pub fn native_from_object_static<T>(obj: *mut JSObject) -> Result<*const T, ()>
pub(crate) fn native_from_object_static<T>(obj: *mut JSObject) -> Result<*const T, ()>
where
T: DomObject + IDLInterface,
{
@ -503,7 +503,7 @@ where
/// Returns Err(()) if `obj` is an opaque security wrapper or if the object is
/// not a reflector for a DOM object of the given type (as defined by the
/// proto_id and proto_depth).
pub fn root_from_object<T>(obj: *mut JSObject, cx: *mut JSContext) -> Result<DomRoot<T>, ()>
pub(crate) fn root_from_object<T>(obj: *mut JSObject, cx: *mut JSContext) -> Result<DomRoot<T>, ()>
where
T: DomObject + IDLInterface,
{
@ -516,7 +516,7 @@ where
/// Returns Err(()) if `obj` is an opaque security wrapper or if the object is
/// not a reflector for a DOM object of the given type (as defined by the
/// proto_id and proto_depth).
pub fn root_from_object_static<T>(obj: *mut JSObject) -> Result<DomRoot<T>, ()>
pub(crate) fn root_from_object_static<T>(obj: *mut JSObject) -> Result<DomRoot<T>, ()>
where
T: DomObject + IDLInterface,
{
@ -525,7 +525,7 @@ where
/// Get a `*const T` for a DOM object accessible from a `HandleValue`.
/// Caller is responsible for throwing a JS exception if needed in case of error.
pub fn native_from_handlevalue<T>(v: HandleValue, cx: *mut JSContext) -> Result<*const T, ()>
pub(crate) fn native_from_handlevalue<T>(v: HandleValue, cx: *mut JSContext) -> Result<*const T, ()>
where
T: DomObject + IDLInterface,
{
@ -537,7 +537,7 @@ where
/// Get a `DomRoot<T>` for a DOM object accessible from a `HandleValue`.
/// Caller is responsible for throwing a JS exception if needed in case of error.
pub fn root_from_handlevalue<T>(v: HandleValue, cx: *mut JSContext) -> Result<DomRoot<T>, ()>
pub(crate) fn root_from_handlevalue<T>(v: HandleValue, cx: *mut JSContext) -> Result<DomRoot<T>, ()>
where
T: DomObject + IDLInterface,
{
@ -548,7 +548,10 @@ where
}
/// Get a `DomRoot<T>` for a DOM object accessible from a `HandleObject`.
pub fn root_from_handleobject<T>(obj: HandleObject, cx: *mut JSContext) -> Result<DomRoot<T>, ()>
pub(crate) fn root_from_handleobject<T>(
obj: HandleObject,
cx: *mut JSContext,
) -> Result<DomRoot<T>, ()>
where
T: DomObject + IDLInterface,
{
@ -564,7 +567,7 @@ impl<T: DomObject> ToJSValConvertible for DomRoot<T> {
/// Returns whether `value` is an array-like object (Array, FileList,
/// HTMLCollection, HTMLFormControlsCollection, HTMLOptionsCollection,
/// NodeList).
pub unsafe fn is_array_like(cx: *mut JSContext, value: HandleValue) -> bool {
pub(crate) unsafe fn is_array_like(cx: *mut JSContext, value: HandleValue) -> bool {
let mut is_array = false;
assert!(IsArrayObject(cx, value, &mut is_array));
if is_array {
@ -596,7 +599,7 @@ pub unsafe fn is_array_like(cx: *mut JSContext, value: HandleValue) -> bool {
}
/// Get a property from a JS object.
pub unsafe fn get_property_jsval(
pub(crate) unsafe fn get_property_jsval(
cx: *mut JSContext,
object: HandleObject,
name: &str,
@ -622,7 +625,7 @@ pub unsafe fn get_property_jsval(
}
/// Get a property from a JS object, and convert it to a Rust value.
pub unsafe fn get_property<T>(
pub(crate) unsafe fn get_property<T>(
cx: *mut JSContext,
object: HandleObject,
name: &str,
@ -648,7 +651,7 @@ where
/// Get a `DomRoot<T>` for a WindowProxy accessible from a `HandleValue`.
/// Caller is responsible for throwing a JS exception if needed in case of error.
pub unsafe fn windowproxy_from_handlevalue(
pub(crate) unsafe fn windowproxy_from_handlevalue(
v: HandleValue,
_cx: *mut JSContext,
) -> Result<DomRoot<WindowProxy>, ()> {

View file

@ -40,7 +40,7 @@ thread_local! {
/// DOM exceptions that can be thrown by a native DOM method.
#[derive(Clone, Debug, MallocSizeOf)]
pub enum Error {
pub(crate) enum Error {
/// IndexSizeError DOMException
IndexSize,
/// NotFoundError DOMException
@ -100,14 +100,14 @@ pub enum Error {
}
/// The return type for IDL operations that can throw DOM exceptions.
pub type Fallible<T> = Result<T, Error>;
pub(crate) type Fallible<T> = Result<T, Error>;
/// The return type for IDL operations that can throw DOM exceptions and
/// return `()`.
pub type ErrorResult = Fallible<()>;
pub(crate) type ErrorResult = Fallible<()>;
/// Set a pending exception for the given `result` on `cx`.
pub fn throw_dom_exception(cx: SafeJSContext, global: &GlobalScope, result: Error) {
pub(crate) fn throw_dom_exception(cx: SafeJSContext, global: &GlobalScope, result: Error) {
#[cfg(feature = "js_backtrace")]
unsafe {
capture_stack!(in(*cx) let stack);
@ -170,15 +170,15 @@ pub fn throw_dom_exception(cx: SafeJSContext, global: &GlobalScope, result: Erro
/// A struct encapsulating information about a runtime script error.
#[derive(Default)]
pub struct ErrorInfo {
pub(crate) struct ErrorInfo {
/// The error message.
pub message: String,
pub(crate) message: String,
/// The file name.
pub filename: String,
pub(crate) filename: String,
/// The line number.
pub lineno: c_uint,
pub(crate) lineno: c_uint,
/// The column number.
pub column: c_uint,
pub(crate) column: c_uint,
}
impl ErrorInfo {
@ -267,7 +267,7 @@ impl ErrorInfo {
///
/// The `dispatch_event` argument is temporary and non-standard; passing false
/// prevents dispatching the `error` event.
pub unsafe fn report_pending_exception(
pub(crate) unsafe fn report_pending_exception(
cx: *mut JSContext,
dispatch_event: bool,
realm: InRealm,
@ -310,7 +310,7 @@ pub unsafe fn report_pending_exception(
/// Throw an exception to signal that a `JSObject` can not be converted to a
/// given DOM type.
pub unsafe fn throw_invalid_this(cx: *mut JSContext, proto_id: u16) {
pub(crate) unsafe fn throw_invalid_this(cx: *mut JSContext, proto_id: u16) {
debug_assert!(!JS_IsExceptionPending(cx));
let error = format!(
"\"this\" object does not implement interface {}.",
@ -319,7 +319,7 @@ pub unsafe fn throw_invalid_this(cx: *mut JSContext, proto_id: u16) {
throw_type_error(cx, &error);
}
pub unsafe fn throw_constructor_without_new(cx: *mut JSContext, name: &str) {
pub(crate) unsafe fn throw_constructor_without_new(cx: *mut JSContext, name: &str) {
debug_assert!(!JS_IsExceptionPending(cx));
let error = format!("{} constructor: 'new' is required", name);
throw_type_error(cx, &error);
@ -328,7 +328,7 @@ pub unsafe fn throw_constructor_without_new(cx: *mut JSContext, name: &str) {
impl Error {
/// Convert this error value to a JS value, consuming it in the process.
#[allow(clippy::wrong_self_convention)]
pub unsafe fn to_jsval(
pub(crate) unsafe fn to_jsval(
self,
cx: *mut JSContext,
global: &GlobalScope,

View file

@ -14,7 +14,7 @@ use js::jsval::UndefinedValue;
use crate::dom::bindings::utils::finalize_global as do_finalize_global;
use crate::dom::bindings::weakref::{WeakBox, WeakReferenceable, DOM_WEAK_SLOT};
pub unsafe fn finalize_common<T>(this: *const T) {
pub(crate) unsafe fn finalize_common<T>(this: *const T) {
if !this.is_null() {
// The pointer can be null if the object is the unforgeable holder of that interface.
let _ = Box::from_raw(this as *mut T);
@ -22,12 +22,12 @@ pub unsafe fn finalize_common<T>(this: *const T) {
debug!("{} finalize: {:p}", type_name::<T>(), this);
}
pub unsafe fn finalize_global<T>(obj: *mut JSObject, this: *const T) {
pub(crate) unsafe fn finalize_global<T>(obj: *mut JSObject, this: *const T) {
do_finalize_global(obj);
finalize_common::<T>(this);
}
pub unsafe fn finalize_weak_referenceable<T: WeakReferenceable>(
pub(crate) unsafe fn finalize_weak_referenceable<T: WeakReferenceable>(
obj: *mut JSObject,
this: *const T,
) {

View file

@ -12,18 +12,18 @@ use crate::dom::bindings::utils::to_frozen_array;
use crate::script_runtime::JSContext;
#[derive(JSTraceable)]
pub struct CachedFrozenArray {
pub(crate) struct CachedFrozenArray {
frozen_value: DomRefCell<Option<Heap<JSVal>>>,
}
impl CachedFrozenArray {
pub fn new() -> CachedFrozenArray {
pub(crate) fn new() -> CachedFrozenArray {
CachedFrozenArray {
frozen_value: DomRefCell::new(None),
}
}
pub fn get_or_init<F: FnOnce() -> Vec<T>, T: ToJSValConvertible>(
pub(crate) fn get_or_init<F: FnOnce() -> Vec<T>, T: ToJSValConvertible>(
&self,
f: F,
cx: JSContext,
@ -46,7 +46,7 @@ impl CachedFrozenArray {
.set(retval.get());
}
pub fn clear(&self) {
pub(crate) fn clear(&self) {
*self.frozen_value.borrow_mut() = None;
}
}

View file

@ -14,21 +14,26 @@ use crate::realms::{AlreadyInRealm, InRealm};
use crate::script_runtime::JSContext;
/// A container with a list of conditions.
pub struct Guard<T: Clone + Copy> {
pub(crate) struct Guard<T: Clone + Copy> {
conditions: &'static [Condition],
value: T,
}
impl<T: Clone + Copy> Guard<T> {
/// Construct a new guarded value.
pub const fn new(conditions: &'static [Condition], value: T) -> Self {
pub(crate) const fn new(conditions: &'static [Condition], value: T) -> Self {
Guard { conditions, value }
}
/// Expose the value if the conditions are satisfied.
///
/// The passed handle is the object on which the value may be exposed.
pub fn expose(&self, cx: JSContext, obj: HandleObject, global: HandleObject) -> Option<T> {
pub(crate) fn expose(
&self,
cx: JSContext,
obj: HandleObject,
global: HandleObject,
) -> Option<T> {
let mut exposed_on_global = false;
let conditions_satisfied = self.conditions.iter().all(|c| match c {
Condition::Satisfied => {
@ -53,7 +58,7 @@ impl<T: Clone + Copy> Guard<T> {
/// A condition to expose things.
#[derive(Clone, Copy)]
pub enum Condition {
pub(crate) enum Condition {
/// The condition is satisfied if the function returns true.
Func(fn(JSContext, HandleObject) -> bool),
/// The condition is satisfied if the preference is set.
@ -73,7 +78,12 @@ fn is_secure_context(cx: JSContext) -> bool {
}
impl Condition {
pub fn is_satisfied(&self, cx: JSContext, obj: HandleObject, global: HandleObject) -> bool {
pub(crate) fn is_satisfied(
&self,
cx: JSContext,
obj: HandleObject,
global: HandleObject,
) -> bool {
match *self {
Condition::Pref(name) => prefs::pref_map().get(name).as_bool().unwrap_or(false),
Condition::Func(f) => f(cx, obj),

View file

@ -3,60 +3,60 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#[allow(unused_imports)]
pub mod base {
pub use std::ptr;
pub use std::rc::Rc;
pub(crate) mod base {
pub(crate) use std::ptr;
pub(crate) use std::rc::Rc;
pub use js::error::throw_type_error;
pub use js::jsapi::{
pub(crate) use js::error::throw_type_error;
pub(crate) use js::jsapi::{
CurrentGlobalOrNull, HandleValue as RawHandleValue, HandleValueArray, Heap, IsCallable,
JSContext, JSObject, JS_NewObject,
};
pub use js::jsval::{JSVal, NullValue, ObjectOrNullValue, ObjectValue, UndefinedValue};
pub use js::panic::maybe_resume_unwind;
pub use js::rust::wrappers::{JS_CallFunctionValue, JS_WrapValue};
pub use js::rust::{HandleObject, HandleValue, MutableHandleObject, MutableHandleValue};
pub(crate) use js::jsval::{JSVal, NullValue, ObjectOrNullValue, ObjectValue, UndefinedValue};
pub(crate) use js::panic::maybe_resume_unwind;
pub(crate) use js::rust::wrappers::{JS_CallFunctionValue, JS_WrapValue};
pub(crate) use js::rust::{HandleObject, HandleValue, MutableHandleObject, MutableHandleValue};
pub use crate::dom::bindings::callback::{
pub(crate) use crate::dom::bindings::callback::{
wrap_call_this_object, CallSetup, CallbackContainer, CallbackFunction, CallbackInterface,
CallbackObject, ExceptionHandling, ThisReflector,
};
pub use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{
pub(crate) use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{
ChannelCountMode, ChannelCountModeValues, ChannelInterpretation,
ChannelInterpretationValues,
};
pub use crate::dom::bindings::codegen::DomTypes::DomTypes;
pub use crate::dom::bindings::codegen::UnionTypes;
pub use crate::dom::bindings::conversions::{
pub(crate) use crate::dom::bindings::codegen::DomTypes::DomTypes;
pub(crate) use crate::dom::bindings::codegen::UnionTypes;
pub(crate) use crate::dom::bindings::conversions::{
root_from_handlevalue, ConversionBehavior, ConversionResult, FromJSValConvertible,
StringificationBehavior, ToJSValConvertible,
};
pub use crate::dom::bindings::error::Error::JSFailed;
pub use crate::dom::bindings::error::{throw_dom_exception, Fallible};
pub use crate::dom::bindings::num::Finite;
pub use crate::dom::bindings::proxyhandler::CrossOriginProperties;
pub use crate::dom::bindings::reflector::DomObject;
pub use crate::dom::bindings::root::DomRoot;
pub use crate::dom::bindings::str::{ByteString, DOMString, USVString};
pub use crate::dom::bindings::trace::RootedTraceableBox;
pub use crate::dom::bindings::utils::{
pub(crate) use crate::dom::bindings::error::Error::JSFailed;
pub(crate) use crate::dom::bindings::error::{throw_dom_exception, Fallible};
pub(crate) use crate::dom::bindings::num::Finite;
pub(crate) use crate::dom::bindings::proxyhandler::CrossOriginProperties;
pub(crate) use crate::dom::bindings::reflector::DomObject;
pub(crate) use crate::dom::bindings::root::DomRoot;
pub(crate) use crate::dom::bindings::str::{ByteString, DOMString, USVString};
pub(crate) use crate::dom::bindings::trace::RootedTraceableBox;
pub(crate) use crate::dom::bindings::utils::{
get_dictionary_property, set_dictionary_property, ThreadUnsafeOnceLock,
};
pub use crate::dom::globalscope::GlobalScope;
pub use crate::script_runtime::JSContext as SafeJSContext;
pub(crate) use crate::dom::globalscope::GlobalScope;
pub(crate) use crate::script_runtime::JSContext as SafeJSContext;
}
#[allow(unused_imports)]
pub mod module {
pub use std::cmp;
pub use std::ffi::CString;
pub use std::ptr::NonNull;
pub(crate) mod module {
pub(crate) use std::cmp;
pub(crate) use std::ffi::CString;
pub(crate) use std::ptr::NonNull;
pub use js::glue::{
pub(crate) use js::glue::{
CreateProxyHandler, GetProxyReservedSlot, JS_GetReservedSlot, ProxyTraps,
SetProxyReservedSlot,
};
pub use js::jsapi::{
pub(crate) use js::jsapi::{
JSJitInfo_OpType, JSJitInfo__bindgen_ty_1, JSJitInfo__bindgen_ty_2,
JSJitInfo__bindgen_ty_3, JSJitMethodCallArgs, JSJitSetterCallArgs, JSNativeWrapper,
JSPropertySpec, JSPropertySpec_Accessor, JSPropertySpec_AccessorsOrValue,
@ -76,79 +76,87 @@ pub mod module {
JSCLASS_FOREGROUND_FINALIZE, JSCLASS_RESERVED_SLOTS_SHIFT, JSITER_HIDDEN, JSITER_OWNONLY,
JSITER_SYMBOLS, JSPROP_ENUMERATE, JSPROP_PERMANENT, JSPROP_READONLY,
};
pub use js::jsval::PrivateValue;
pub use js::panic::wrap_panic;
pub use js::rust::wrappers::{
pub(crate) use js::jsval::PrivateValue;
pub(crate) use js::panic::wrap_panic;
pub(crate) use js::rust::wrappers::{
int_to_jsid, AppendToIdVector, Call, GetPropertyKeys, JS_CopyOwnPropertiesAndPrivateFields,
JS_DefineProperty, JS_DefinePropertyById2, JS_GetProperty,
JS_InitializePropertiesFromCompatibleNativeObject, JS_NewObjectWithGivenProto,
JS_NewObjectWithoutMetadata, JS_SetImmutablePrototype, JS_SetProperty, JS_SetPrototype,
JS_WrapObject, NewProxyObject, RUST_INTERNED_STRING_TO_JSID, RUST_SYMBOL_TO_JSID,
};
pub use js::rust::{
pub(crate) use js::rust::{
get_context_realm, get_object_class, get_object_realm, CustomAutoRooterGuard, GCMethods,
Handle, MutableHandle,
};
pub use js::typedarray::{
pub(crate) use js::typedarray::{
ArrayBuffer, ArrayBufferView, Float32Array, Float64Array, Uint8Array, Uint8ClampedArray,
};
pub use js::{
pub(crate) use js::{
jsapi, typedarray, JSCLASS_GLOBAL_SLOT_COUNT, JSCLASS_IS_DOMJSCLASS, JSCLASS_IS_GLOBAL,
JSCLASS_RESERVED_SLOTS_MASK, JS_CALLEE,
};
pub use servo_config::pref;
pub(crate) use servo_config::pref;
pub use super::base::*;
pub use crate::dom::bindings::codegen::Bindings::AnalyserNodeBinding::AnalyserOptions;
pub use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{
pub(crate) use super::base::*;
pub(crate) use crate::dom::bindings::codegen::Bindings::AnalyserNodeBinding::AnalyserOptions;
pub(crate) use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{
AudioNode_Binding, ChannelCountMode, ChannelCountModeValues, ChannelInterpretation,
ChannelInterpretationValues,
};
pub use crate::dom::bindings::codegen::Bindings::EventTargetBinding::EventTarget_Binding;
pub use crate::dom::bindings::codegen::{InterfaceObjectMap, PrototypeList, RegisterBindings};
pub use crate::dom::bindings::constant::{ConstantSpec, ConstantVal};
pub use crate::dom::bindings::constructor::{
pub(crate) use crate::dom::bindings::codegen::Bindings::EventTargetBinding::EventTarget_Binding;
pub(crate) use crate::dom::bindings::codegen::{
InterfaceObjectMap, PrototypeList, RegisterBindings,
};
pub(crate) use crate::dom::bindings::constant::{ConstantSpec, ConstantVal};
pub(crate) use crate::dom::bindings::constructor::{
call_default_constructor, call_html_constructor, pop_current_element_queue,
push_new_element_queue,
};
pub use crate::dom::bindings::conversions::{
pub(crate) use crate::dom::bindings::conversions::{
is_array_like, jsid_to_string, native_from_handlevalue, native_from_object_static,
IDLInterface, StringificationBehavior, ToJSValConvertible, DOM_OBJECT_SLOT,
};
pub use crate::dom::bindings::error::{throw_constructor_without_new, Error, ErrorResult};
pub use crate::dom::bindings::finalize::{
pub(crate) use crate::dom::bindings::error::{
throw_constructor_without_new, Error, ErrorResult,
};
pub(crate) use crate::dom::bindings::finalize::{
finalize_common, finalize_global, finalize_weak_referenceable,
};
pub use crate::dom::bindings::guard::{Condition, Guard};
pub use crate::dom::bindings::inheritance::Castable;
pub use crate::dom::bindings::interface::{
pub(crate) use crate::dom::bindings::guard::{Condition, Guard};
pub(crate) use crate::dom::bindings::inheritance::Castable;
pub(crate) use crate::dom::bindings::interface::{
create_callback_interface_object, create_global_object, create_interface_prototype_object,
create_named_constructors, create_noncallback_interface_object, define_dom_interface,
define_guarded_methods, define_guarded_properties, get_desired_proto,
get_per_interface_object_handle, is_exposed_in, ConstructorClassHook,
InterfaceConstructorBehavior, NonCallbackInterfaceObjectClass, ProtoOrIfaceIndex,
};
pub use crate::dom::bindings::iterable::{Iterable, IteratorType};
pub use crate::dom::bindings::like::{Maplike, Setlike};
pub use crate::dom::bindings::namespace::{create_namespace_object, NamespaceObjectClass};
pub use crate::dom::bindings::proxyhandler;
pub use crate::dom::bindings::proxyhandler::{
pub(crate) use crate::dom::bindings::iterable::{Iterable, IteratorType};
pub(crate) use crate::dom::bindings::like::{Maplike, Setlike};
pub(crate) use crate::dom::bindings::namespace::{
create_namespace_object, NamespaceObjectClass,
};
pub(crate) use crate::dom::bindings::proxyhandler;
pub(crate) use crate::dom::bindings::proxyhandler::{
ensure_expando_object, get_expando_object, set_property_descriptor,
};
pub use crate::dom::bindings::record::Record;
pub use crate::dom::bindings::reflector::{DomObjectIteratorWrap, DomObjectWrap, Reflector};
pub use crate::dom::bindings::root::{Dom, DomSlice, MaybeUnreflectedDom, Root};
pub use crate::dom::bindings::trace::JSTraceable;
pub use crate::dom::bindings::utils::{
pub(crate) use crate::dom::bindings::record::Record;
pub(crate) use crate::dom::bindings::reflector::{
DomObjectIteratorWrap, DomObjectWrap, Reflector,
};
pub(crate) use crate::dom::bindings::root::{Dom, DomSlice, MaybeUnreflectedDom, Root};
pub(crate) use crate::dom::bindings::trace::JSTraceable;
pub(crate) use crate::dom::bindings::utils::{
enumerate_global, exception_to_promise, generic_getter, generic_lenient_getter,
generic_lenient_setter, generic_method, generic_setter, generic_static_promise_method,
get_array_index_from_id, get_property_on_prototype, has_property_on_prototype,
resolve_global, trace_global, AsVoidPtr, DOMClass, DOMJSClass, ProtoOrIfaceArray,
DOM_PROTO_UNFORGEABLE_HOLDER_SLOT, JSCLASS_DOM_GLOBAL,
};
pub use crate::dom::bindings::weakref::{WeakReferenceable, DOM_WEAK_SLOT};
pub use crate::dom::types::{AnalyserNode, AudioNode, BaseAudioContext, EventTarget};
pub use crate::mem::malloc_size_of_including_raw_self;
pub use crate::realms::{AlreadyInRealm, InRealm};
pub use crate::script_runtime::CanGc;
pub(crate) use crate::dom::bindings::weakref::{WeakReferenceable, DOM_WEAK_SLOT};
pub(crate) use crate::dom::types::{AnalyserNode, AudioNode, BaseAudioContext, EventTarget};
pub(crate) use crate::mem::malloc_size_of_including_raw_self;
pub(crate) use crate::realms::{AlreadyInRealm, InRealm};
pub(crate) use crate::script_runtime::CanGc;
}

View file

@ -6,14 +6,14 @@
use std::mem;
pub use crate::dom::bindings::codegen::InheritTypes::*;
pub(crate) use crate::dom::bindings::codegen::InheritTypes::*;
use crate::dom::bindings::conversions::{get_dom_class, DerivedFrom, IDLInterface};
use crate::dom::bindings::reflector::DomObject;
use crate::script_runtime::runtime_is_alive;
/// A trait to hold the cast functions of IDL interfaces that either derive
/// or are derived from other interfaces.
pub trait Castable: IDLInterface + DomObject + Sized {
pub(crate) trait Castable: IDLInterface + DomObject + Sized {
/// Check whether a DOM object implements one of its deriving interfaces.
fn is<T>(&self) -> bool
where
@ -54,7 +54,7 @@ pub trait Castable: IDLInterface + DomObject + Sized {
}
#[allow(missing_docs)]
pub trait HasParent {
pub(crate) trait HasParent {
#[crown::unrooted_must_root_lint::must_root]
type Parent;
fn as_parent(&self) -> &Self::Parent;

View file

@ -46,22 +46,22 @@ use crate::script_runtime::JSContext as SafeJSContext;
/// The class of a non-callback interface object.
#[derive(Clone, Copy)]
pub struct NonCallbackInterfaceObjectClass {
pub(crate) struct NonCallbackInterfaceObjectClass {
/// The SpiderMonkey class structure.
pub _class: JSClass,
pub(crate) _class: JSClass,
/// The prototype id of that interface, used in the hasInstance hook.
pub _proto_id: PrototypeList::ID,
pub(crate) _proto_id: PrototypeList::ID,
/// The prototype depth of that interface, used in the hasInstance hook.
pub _proto_depth: u16,
pub(crate) _proto_depth: u16,
/// The string representation of the object.
pub representation: &'static [u8],
pub(crate) representation: &'static [u8],
}
unsafe impl Sync for NonCallbackInterfaceObjectClass {}
impl NonCallbackInterfaceObjectClass {
/// Create a new `NonCallbackInterfaceObjectClass` structure.
pub const fn new(
pub(crate) const fn new(
constructor_behavior: &'static InterfaceConstructorBehavior,
string_rep: &'static [u8],
proto_id: PrototypeList::ID,
@ -83,21 +83,21 @@ impl NonCallbackInterfaceObjectClass {
}
/// cast own reference to `JSClass` reference
pub fn as_jsclass(&self) -> &JSClass {
pub(crate) fn as_jsclass(&self) -> &JSClass {
unsafe { &*(self as *const _ as *const JSClass) }
}
}
/// A constructor class hook.
pub type ConstructorClassHook =
pub(crate) type ConstructorClassHook =
unsafe extern "C" fn(cx: *mut JSContext, argc: u32, vp: *mut Value) -> bool;
/// The constructor behavior of a non-callback interface object.
pub struct InterfaceConstructorBehavior(JSClassOps);
pub(crate) struct InterfaceConstructorBehavior(JSClassOps);
impl InterfaceConstructorBehavior {
/// An interface constructor that unconditionally throws a type error.
pub const fn throw() -> Self {
pub(crate) const fn throw() -> Self {
InterfaceConstructorBehavior(JSClassOps {
addProperty: None,
delProperty: None,
@ -113,7 +113,7 @@ impl InterfaceConstructorBehavior {
}
/// An interface constructor that calls a native Rust function.
pub const fn call(hook: ConstructorClassHook) -> Self {
pub(crate) const fn call(hook: ConstructorClassHook) -> Self {
InterfaceConstructorBehavior(JSClassOps {
addProperty: None,
delProperty: None,
@ -130,10 +130,10 @@ impl InterfaceConstructorBehavior {
}
/// A trace hook.
pub type TraceHook = unsafe extern "C" fn(trc: *mut JSTracer, obj: *mut JSObject);
pub(crate) type TraceHook = unsafe extern "C" fn(trc: *mut JSTracer, obj: *mut JSObject);
/// Create a global object with the given class.
pub unsafe fn create_global_object(
pub(crate) unsafe fn create_global_object(
cx: SafeJSContext,
class: &'static JSClass,
private: *const libc::c_void,
@ -210,7 +210,7 @@ fn select_compartment(cx: SafeJSContext, options: &mut RealmOptions) {
}
/// Create and define the interface object of a callback interface.
pub fn create_callback_interface_object(
pub(crate) fn create_callback_interface_object(
cx: SafeJSContext,
global: HandleObject,
constants: &[Guard<&[ConstantSpec]>],
@ -229,7 +229,7 @@ pub fn create_callback_interface_object(
/// Create the interface prototype object of a non-callback interface.
#[allow(clippy::too_many_arguments)]
pub fn create_interface_prototype_object(
pub(crate) fn create_interface_prototype_object(
cx: SafeJSContext,
global: HandleObject,
proto: HandleObject,
@ -274,7 +274,7 @@ pub fn create_interface_prototype_object(
/// Create and define the interface object of a non-callback interface.
#[allow(clippy::too_many_arguments)]
pub fn create_noncallback_interface_object(
pub(crate) fn create_noncallback_interface_object(
cx: SafeJSContext,
global: HandleObject,
proto: HandleObject,
@ -317,7 +317,7 @@ pub fn create_noncallback_interface_object(
}
/// Create and define the named constructors of a non-callback interface.
pub fn create_named_constructors(
pub(crate) fn create_named_constructors(
cx: SafeJSContext,
global: HandleObject,
named_constructors: &[(ConstructorClassHook, &CStr, u32)],
@ -347,7 +347,7 @@ pub fn create_named_constructors(
/// Create a new object with a unique type.
#[allow(clippy::too_many_arguments)]
pub fn create_object(
pub(crate) fn create_object(
cx: SafeJSContext,
global: HandleObject,
proto: HandleObject,
@ -367,7 +367,7 @@ pub fn create_object(
}
/// Conditionally define constants on an object.
pub fn define_guarded_constants(
pub(crate) fn define_guarded_constants(
cx: SafeJSContext,
obj: HandleObject,
constants: &[Guard<&[ConstantSpec]>],
@ -381,7 +381,7 @@ pub fn define_guarded_constants(
}
/// Conditionally define methods on an object.
pub fn define_guarded_methods(
pub(crate) fn define_guarded_methods(
cx: SafeJSContext,
obj: HandleObject,
methods: &[Guard<&'static [JSFunctionSpec]>],
@ -397,7 +397,7 @@ pub fn define_guarded_methods(
}
/// Conditionally define properties on an object.
pub fn define_guarded_properties(
pub(crate) fn define_guarded_properties(
cx: SafeJSContext,
obj: HandleObject,
properties: &[Guard<&'static [JSPropertySpec]>],
@ -414,7 +414,7 @@ pub fn define_guarded_properties(
/// Returns whether an interface with exposure set given by `globals` should
/// be exposed in the global object `obj`.
pub fn is_exposed_in(object: HandleObject, globals: Globals) -> bool {
pub(crate) fn is_exposed_in(object: HandleObject, globals: Globals) -> bool {
unsafe {
let unwrapped = UncheckedUnwrapObject(object.get(), /* stopAtWindowProxy = */ false);
let dom_class = get_dom_class(unwrapped).unwrap();
@ -424,7 +424,7 @@ pub fn is_exposed_in(object: HandleObject, globals: Globals) -> bool {
/// Define a property with a given name on the global object. Should be called
/// through the resolve hook.
pub fn define_on_global_object(
pub(crate) fn define_on_global_object(
cx: SafeJSContext,
global: HandleObject,
name: &CStr,
@ -529,7 +529,7 @@ unsafe extern "C" fn non_new_constructor(
false
}
pub enum ProtoOrIfaceIndex {
pub(crate) enum ProtoOrIfaceIndex {
ID(PrototypeList::ID),
Constructor(PrototypeList::Constructor),
}
@ -543,7 +543,7 @@ impl From<ProtoOrIfaceIndex> for usize {
}
}
pub fn get_per_interface_object_handle(
pub(crate) fn get_per_interface_object_handle(
cx: SafeJSContext,
global: HandleObject,
id: ProtoOrIfaceIndex,
@ -567,7 +567,7 @@ pub fn get_per_interface_object_handle(
}
}
pub fn define_dom_interface(
pub(crate) fn define_dom_interface(
cx: SafeJSContext,
global: HandleObject,
id: ProtoOrIfaceIndex,
@ -597,7 +597,7 @@ fn get_proto_id_for_new_target(new_target: HandleObject) -> Option<PrototypeList
}
}
pub fn get_desired_proto(
pub(crate) fn get_desired_proto(
cx: SafeJSContext,
args: &CallArgs,
proto_id: PrototypeList::ID,

View file

@ -30,7 +30,7 @@ use crate::script_runtime::{CanGc, JSContext};
/// The values that an iterator will iterate over.
#[derive(JSTraceable, MallocSizeOf)]
pub enum IteratorType {
pub(crate) enum IteratorType {
/// The keys of the iterable object.
Keys,
/// The values of the iterable object.
@ -40,7 +40,7 @@ pub enum IteratorType {
}
/// A DOM object that can be iterated over using a pair value iterator.
pub trait Iterable {
pub(crate) trait Iterable {
/// The type of the key of the iterator pair.
type Key: ToJSValConvertible;
/// The type of the value of the iterator pair.
@ -56,7 +56,7 @@ pub trait Iterable {
/// An iterator over the iterable entries of a given DOM interface.
//FIXME: #12811 prevents dom_struct with type parameters
#[dom_struct]
pub struct IterableIterator<T: DomObjectIteratorWrap + JSTraceable + Iterable> {
pub(crate) struct IterableIterator<T: DomObjectIteratorWrap + JSTraceable + Iterable> {
reflector: Reflector,
iterable: Dom<T>,
type_: IteratorType,
@ -65,7 +65,7 @@ pub struct IterableIterator<T: DomObjectIteratorWrap + JSTraceable + Iterable> {
impl<T: DomObjectIteratorWrap + JSTraceable + Iterable> IterableIterator<T> {
/// Create a new iterator instance for the provided iterable DOM interface.
pub fn new(iterable: &T, type_: IteratorType) -> DomRoot<Self> {
pub(crate) fn new(iterable: &T, type_: IteratorType) -> DomRoot<Self> {
let iterator = Box::new(IterableIterator {
reflector: Reflector::new(),
type_,
@ -77,7 +77,7 @@ impl<T: DomObjectIteratorWrap + JSTraceable + Iterable> IterableIterator<T> {
/// Return the next value from the iterable object.
#[allow(non_snake_case)]
pub fn Next(&self, cx: JSContext) -> Fallible<NonNull<JSObject>> {
pub(crate) fn Next(&self, cx: JSContext) -> Fallible<NonNull<JSObject>> {
let index = self.index.get();
rooted!(in(*cx) let mut value = UndefinedValue());
rooted!(in(*cx) let mut rval = ptr::null_mut::<JSObject>());

View file

@ -20,7 +20,7 @@ use crate::dom::bindings::cell::DomRefCell;
///
/// In case you use a type that implements Setlike as underlying storage it's recommended to use `setlike` macro.
// In webidl: `setlike<Key>`
pub trait Setlike {
pub(crate) trait Setlike {
/// The type of the key of the set.
type Key: ToJSValConvertible + Clone; // clone is for impl<T: Setlike> Maplike for T
@ -111,7 +111,7 @@ where
/// Usage:
/// ```rust
/// pub struct TestBindingSetlike {
/// pub(crate) struct TestBindingSetlike {
/// // setlike<DOMString>
/// internal: DomRefCell<IndexSet<DOMString>>,
/// }
@ -161,7 +161,7 @@ macro_rules! setlike {
///
/// In case you use a type that implements Maplike as underlying storage it's recommended to use `maplike` macro.
// In webidl: `maplike<Key, Value>`
pub trait Maplike {
pub(crate) trait Maplike {
/// The type of the key of the map.
type Key: ToJSValConvertible;
/// The type of the value of the map.
@ -248,7 +248,7 @@ where
/// Usage:
/// ```rust
/// pub struct TestBindingMaplike {
/// pub(crate) struct TestBindingMaplike {
/// // maplike<DOMString, long>
/// internal: DomRefCell<IndexMap<DOMString, i32>>,
/// }

View file

@ -134,65 +134,67 @@
#![deny(missing_docs)]
#![deny(non_snake_case)]
pub mod buffer_source;
pub mod callback;
pub mod cell;
pub mod constant;
pub mod constructor;
pub mod conversions;
pub mod error;
pub mod finalize;
pub mod frozenarray;
pub mod function;
pub mod guard;
pub mod import;
pub mod inheritance;
pub mod interface;
pub mod iterable;
pub mod like;
pub mod namespace;
pub mod num;
pub mod principals;
pub mod proxyhandler;
pub mod record;
pub mod refcounted;
pub mod reflector;
pub mod root;
pub mod serializable;
pub mod settings_stack;
pub mod str;
pub mod structuredclone;
pub mod trace;
pub mod transferable;
pub mod utils;
pub mod weakref;
pub mod xmlname;
pub(crate) mod buffer_source;
pub(crate) mod callback;
#[allow(dead_code)]
pub(crate) mod cell;
pub(crate) mod constant;
pub(crate) mod constructor;
pub(crate) mod conversions;
pub(crate) mod error;
pub(crate) mod finalize;
pub(crate) mod frozenarray;
pub(crate) mod function;
pub(crate) mod guard;
pub(crate) mod import;
pub(crate) mod inheritance;
pub(crate) mod interface;
pub(crate) mod iterable;
pub(crate) mod like;
pub(crate) mod namespace;
pub(crate) mod num;
pub(crate) mod principals;
pub(crate) mod proxyhandler;
pub(crate) mod record;
pub(crate) mod refcounted;
pub(crate) mod reflector;
pub(crate) mod root;
pub(crate) mod serializable;
pub(crate) mod settings_stack;
#[allow(dead_code)]
pub(crate) mod str;
pub(crate) mod structuredclone;
pub(crate) mod trace;
pub(crate) mod transferable;
pub(crate) mod utils;
pub(crate) mod weakref;
pub(crate) mod xmlname;
/// Generated JS-Rust bindings.
#[allow(missing_docs, non_snake_case)]
pub mod codegen {
pub mod DomTypeHolder {
pub(crate) mod codegen {
pub(crate) mod DomTypeHolder {
include!(concat!(env!("OUT_DIR"), "/DomTypeHolder.rs"));
}
pub mod DomTypes {
pub(crate) mod DomTypes {
include!(concat!(env!("OUT_DIR"), "/DomTypes.rs"));
}
#[allow(dead_code)]
pub mod Bindings {
pub(crate) mod Bindings {
include!(concat!(env!("OUT_DIR"), "/Bindings/mod.rs"));
}
pub mod InterfaceObjectMap {
pub(crate) mod InterfaceObjectMap {
include!(concat!(env!("OUT_DIR"), "/InterfaceObjectMap.rs"));
}
#[allow(dead_code, unused_imports, clippy::enum_variant_names)]
pub mod InheritTypes {
pub(crate) mod InheritTypes {
include!(concat!(env!("OUT_DIR"), "/InheritTypes.rs"));
}
#[allow(clippy::upper_case_acronyms)]
pub mod PrototypeList {
pub(crate) mod PrototypeList {
include!(concat!(env!("OUT_DIR"), "/PrototypeList.rs"));
}
pub mod RegisterBindings {
pub(crate) mod RegisterBindings {
include!(concat!(env!("OUT_DIR"), "/RegisterBindings.rs"));
}
#[allow(
@ -203,7 +205,7 @@ pub mod codegen {
clippy::upper_case_acronyms,
clippy::enum_variant_names
)]
pub mod UnionTypes {
pub(crate) mod UnionTypes {
include!(concat!(env!("OUT_DIR"), "/UnionTypes.rs"));
}
}

View file

@ -17,13 +17,13 @@ use crate::script_runtime::JSContext;
/// The class of a namespace object.
#[derive(Clone, Copy)]
pub struct NamespaceObjectClass(JSClass);
pub(crate) struct NamespaceObjectClass(JSClass);
unsafe impl Sync for NamespaceObjectClass {}
impl NamespaceObjectClass {
/// Create a new `NamespaceObjectClass` structure.
pub const unsafe fn new(name: &'static CStr) -> Self {
pub(crate) const unsafe fn new(name: &'static CStr) -> Self {
NamespaceObjectClass(JSClass {
name: name.as_ptr(),
flags: 0,
@ -37,7 +37,7 @@ impl NamespaceObjectClass {
/// Create a new namespace object.
#[allow(clippy::too_many_arguments)]
pub fn create_namespace_object(
pub(crate) fn create_namespace_object(
cx: JSContext,
global: HandleObject,
proto: HandleObject,

View file

@ -12,11 +12,11 @@ use num_traits::Float;
/// Encapsulates the IDL restricted float type.
#[derive(Clone, Copy, Eq, JSTraceable, PartialEq)]
pub struct Finite<T: Float>(T);
pub(crate) struct Finite<T: Float>(T);
impl<T: Float> Finite<T> {
/// Create a new `Finite<T: Float>` safely.
pub fn new(value: T) -> Option<Finite<T>> {
pub(crate) fn new(value: T) -> Option<Finite<T>> {
if value.is_finite() {
Some(Finite(value))
} else {
@ -26,7 +26,7 @@ impl<T: Float> Finite<T> {
/// Create a new `Finite<T: Float>`.
#[inline]
pub fn wrap(value: T) -> Finite<T> {
pub(crate) fn wrap(value: T) -> Finite<T> {
assert!(
value.is_finite(),
"Finite<T> doesn't encapsulate unrestricted value."

View file

@ -22,10 +22,10 @@ use super::structuredclone::StructuredCloneTags;
/// An owned reference to Servo's `JSPrincipals` instance.
#[repr(transparent)]
pub struct ServoJSPrincipals(NonNull<JSPrincipals>);
pub(crate) struct ServoJSPrincipals(NonNull<JSPrincipals>);
impl ServoJSPrincipals {
pub fn new(origin: &MutableOrigin) -> Self {
pub(crate) fn new(origin: &MutableOrigin) -> Self {
unsafe {
let private: Box<MutableOrigin> = Box::new(origin.clone());
let raw = CreateRustJSPrincipals(&PRINCIPALS_CALLBACKS, Box::into_raw(private) as _);
@ -38,24 +38,24 @@ impl ServoJSPrincipals {
/// Construct `Self` from a raw `*mut JSPrincipals`, incrementing its
/// reference count.
#[inline]
pub unsafe fn from_raw_nonnull(raw: NonNull<JSPrincipals>) -> Self {
pub(crate) unsafe fn from_raw_nonnull(raw: NonNull<JSPrincipals>) -> Self {
JS_HoldPrincipals(raw.as_ptr());
Self(raw)
}
#[inline]
pub unsafe fn origin(&self) -> MutableOrigin {
pub(crate) unsafe fn origin(&self) -> MutableOrigin {
let origin = GetRustJSPrincipalsPrivate(self.0.as_ptr()) as *mut MutableOrigin;
(*origin).clone()
}
#[inline]
pub fn as_raw_nonnull(&self) -> NonNull<JSPrincipals> {
pub(crate) fn as_raw_nonnull(&self) -> NonNull<JSPrincipals> {
self.0
}
#[inline]
pub fn as_raw(&self) -> *mut JSPrincipals {
pub(crate) fn as_raw(&self) -> *mut JSPrincipals {
self.0.as_ptr()
}
}
@ -78,7 +78,7 @@ impl Drop for ServoJSPrincipals {
/// A borrowed reference to Servo's `JSPrincipals` instance. Does not update the
/// reference count on creation and deletion.
pub struct ServoJSPrincipalsRef<'a>(ManuallyDrop<ServoJSPrincipals>, PhantomData<&'a ()>);
pub(crate) struct ServoJSPrincipalsRef<'a>(ManuallyDrop<ServoJSPrincipals>, PhantomData<&'a ()>);
impl ServoJSPrincipalsRef<'_> {
/// Construct `Self` from a raw `NonNull<JSPrincipals>`.
@ -90,7 +90,7 @@ impl ServoJSPrincipalsRef<'_> {
/// returned `ServoJSPrincipalsRef` object or any clones are not used past
/// the lifetime of the wrapped object.
#[inline]
pub unsafe fn from_raw_nonnull(raw: NonNull<JSPrincipals>) -> Self {
pub(crate) unsafe fn from_raw_nonnull(raw: NonNull<JSPrincipals>) -> Self {
// Don't use `ServoJSPrincipals::from_raw_nonnull`; we don't want to
// update the reference count
Self(ManuallyDrop::new(ServoJSPrincipals(raw)), PhantomData)
@ -103,7 +103,7 @@ impl ServoJSPrincipalsRef<'_> {
/// The behavior is undefined if `raw` is null. See also
/// [`Self::from_raw_nonnull`].
#[inline]
pub unsafe fn from_raw_unchecked(raw: *mut JSPrincipals) -> Self {
pub(crate) unsafe fn from_raw_unchecked(raw: *mut JSPrincipals) -> Self {
Self::from_raw_nonnull(NonNull::new_unchecked(raw))
}
}
@ -125,12 +125,12 @@ impl Deref for ServoJSPrincipalsRef<'_> {
}
#[allow(unused)]
pub unsafe extern "C" fn destroy_servo_jsprincipal(principals: *mut JSPrincipals) {
pub(crate) unsafe extern "C" fn destroy_servo_jsprincipal(principals: *mut JSPrincipals) {
Box::from_raw(GetRustJSPrincipalsPrivate(principals) as *mut MutableOrigin);
DestroyRustJSPrincipals(principals);
}
pub unsafe extern "C" fn write_jsprincipal(
pub(crate) unsafe extern "C" fn write_jsprincipal(
principal: *mut JSPrincipals,
_cx: *mut JSContext,
writer: *mut JSStructuredCloneWriter,
@ -155,7 +155,7 @@ pub unsafe extern "C" fn write_jsprincipal(
true
}
pub unsafe extern "C" fn read_jsprincipal(
pub(crate) unsafe extern "C" fn read_jsprincipal(
_cx: *mut JSContext,
reader: *mut JSStructuredCloneReader,
principals: *mut *mut JSPrincipals,
@ -192,7 +192,7 @@ unsafe extern "C" fn principals_is_system_or_addon_principal(_: *mut JSPrincipal
}
//TODO is same_origin_domain equivalent to subsumes for our purposes
pub unsafe extern "C" fn subsumes(obj: *mut JSPrincipals, other: *mut JSPrincipals) -> bool {
pub(crate) unsafe extern "C" fn subsumes(obj: *mut JSPrincipals, other: *mut JSPrincipals) -> bool {
match (NonNull::new(obj), NonNull::new(other)) {
(Some(obj), Some(other)) => {
let obj = ServoJSPrincipalsRef::from_raw_nonnull(obj);

View file

@ -47,7 +47,7 @@ use crate::realms::{AlreadyInRealm, InRealm};
use crate::script_runtime::JSContext as SafeJSContext;
/// Determine if this id shadows any existing properties for this proxy.
pub unsafe extern "C" fn shadow_check_callback(
pub(crate) unsafe extern "C" fn shadow_check_callback(
cx: *mut JSContext,
object: RawHandleObject,
id: RawHandleId,
@ -74,7 +74,7 @@ pub unsafe extern "C" fn shadow_check_callback(
}
/// Initialize the infrastructure for DOM proxy objects.
pub unsafe fn init() {
pub(crate) unsafe fn init() {
SetDOMProxyInformation(
GetProxyHandlerFamily(),
Some(shadow_check_callback),
@ -83,7 +83,7 @@ pub unsafe fn init() {
}
/// Defines an expando on the given `proxy`.
pub unsafe extern "C" fn define_property(
pub(crate) unsafe extern "C" fn define_property(
cx: *mut JSContext,
proxy: RawHandleObject,
id: RawHandleId,
@ -96,7 +96,7 @@ pub unsafe extern "C" fn define_property(
}
/// Deletes an expando off the given `proxy`.
pub unsafe extern "C" fn delete(
pub(crate) unsafe extern "C" fn delete(
cx: *mut JSContext,
proxy: RawHandleObject,
id: RawHandleId,
@ -113,7 +113,7 @@ pub unsafe extern "C" fn delete(
}
/// Controls whether the Extensible bit can be changed
pub unsafe extern "C" fn prevent_extensions(
pub(crate) unsafe extern "C" fn prevent_extensions(
_cx: *mut JSContext,
_proxy: RawHandleObject,
result: *mut ObjectOpResult,
@ -123,7 +123,7 @@ pub unsafe extern "C" fn prevent_extensions(
}
/// Reports whether the object is Extensible
pub unsafe extern "C" fn is_extensible(
pub(crate) unsafe extern "C" fn is_extensible(
_cx: *mut JSContext,
_proxy: RawHandleObject,
succeeded: *mut bool,
@ -141,7 +141,7 @@ pub unsafe extern "C" fn is_extensible(
/// This implementation always handles the case of the ordinary
/// `[[GetPrototypeOf]]` behavior. An alternative implementation will be
/// necessary for maybe-cross-origin objects.
pub unsafe extern "C" fn get_prototype_if_ordinary(
pub(crate) unsafe extern "C" fn get_prototype_if_ordinary(
_: *mut JSContext,
proxy: RawHandleObject,
is_ordinary: *mut bool,
@ -153,7 +153,7 @@ pub unsafe extern "C" fn get_prototype_if_ordinary(
}
/// Get the expando object, or null if there is none.
pub unsafe fn get_expando_object(obj: RawHandleObject, mut expando: MutableHandleObject) {
pub(crate) unsafe fn get_expando_object(obj: RawHandleObject, mut expando: MutableHandleObject) {
assert!(is_dom_proxy(obj.get()));
let val = &mut UndefinedValue();
GetProxyPrivate(obj.get(), val);
@ -166,7 +166,7 @@ pub unsafe fn get_expando_object(obj: RawHandleObject, mut expando: MutableHandl
/// Get the expando object, or create it if it doesn't exist yet.
/// Fails on JSAPI failure.
pub unsafe fn ensure_expando_object(
pub(crate) unsafe fn ensure_expando_object(
cx: *mut JSContext,
obj: RawHandleObject,
mut expando: MutableHandleObject,
@ -187,7 +187,7 @@ pub unsafe fn ensure_expando_object(
/// Set the property descriptor's object to `obj` and set it to enumerable,
/// and writable if `readonly` is true.
pub fn set_property_descriptor(
pub(crate) fn set_property_descriptor(
desc: MutableHandle<PropertyDescriptor>,
value: HandleValue,
attrs: u32,
@ -200,7 +200,10 @@ pub fn set_property_descriptor(
}
/// <https://html.spec.whatwg.org/multipage/#isplatformobjectsameorigin-(-o-)>
pub unsafe fn is_platform_object_same_origin(cx: SafeJSContext, obj: RawHandleObject) -> bool {
pub(crate) unsafe fn is_platform_object_same_origin(
cx: SafeJSContext,
obj: RawHandleObject,
) -> bool {
let subject_realm = get_context_realm(*cx);
let obj_realm = GetObjectRealmOrNull(*obj);
assert!(!obj_realm.is_null());
@ -236,7 +239,11 @@ pub unsafe fn is_platform_object_same_origin(cx: SafeJSContext, obj: RawHandleOb
/// What this function does corresponds to the operations in
/// <https://html.spec.whatwg.org/multipage/#the-location-interface> denoted as
/// "Throw a `SecurityError` DOMException".
pub unsafe fn report_cross_origin_denial(cx: SafeJSContext, id: RawHandleId, access: &str) -> bool {
pub(crate) unsafe fn report_cross_origin_denial(
cx: SafeJSContext,
id: RawHandleId,
access: &str,
) -> bool {
debug!(
"permission denied to {} property {} on cross-origin object",
access,
@ -267,9 +274,9 @@ unsafe fn id_to_source(cx: SafeJSContext, id: RawHandleId) -> Option<DOMString>
/// [`CrossOriginProperties(O)`].
///
/// [`CrossOriginProperties(O)`]: https://html.spec.whatwg.org/multipage/#crossoriginproperties-(-o-)
pub struct CrossOriginProperties {
pub attributes: &'static [JSPropertySpec],
pub methods: &'static [JSFunctionSpec],
pub(crate) struct CrossOriginProperties {
pub(crate) attributes: &'static [JSPropertySpec],
pub(crate) methods: &'static [JSFunctionSpec],
}
impl CrossOriginProperties {
@ -287,7 +294,7 @@ impl CrossOriginProperties {
/// Implementation of [`CrossOriginOwnPropertyKeys`].
///
/// [`CrossOriginOwnPropertyKeys`]: https://html.spec.whatwg.org/multipage/#crossoriginownpropertykeys-(-o-)
pub unsafe fn cross_origin_own_property_keys(
pub(crate) unsafe fn cross_origin_own_property_keys(
cx: SafeJSContext,
_proxy: RawHandleObject,
cross_origin_properties: &'static CrossOriginProperties,
@ -312,7 +319,7 @@ pub unsafe fn cross_origin_own_property_keys(
/// Implementation of `[[Set]]` for [`Location`].
///
/// [`Location`]: https://html.spec.whatwg.org/multipage/#location-set
pub unsafe extern "C" fn maybe_cross_origin_set_rawcx(
pub(crate) unsafe extern "C" fn maybe_cross_origin_set_rawcx(
cx: *mut JSContext,
proxy: RawHandleObject,
id: RawHandleId,
@ -355,7 +362,7 @@ pub unsafe extern "C" fn maybe_cross_origin_set_rawcx(
)
}
pub unsafe extern "C" fn maybe_cross_origin_get_prototype_if_ordinary_rawcx(
pub(crate) unsafe extern "C" fn maybe_cross_origin_get_prototype_if_ordinary_rawcx(
_: *mut JSContext,
_proxy: RawHandleObject,
is_ordinary: *mut bool,
@ -369,7 +376,7 @@ pub unsafe extern "C" fn maybe_cross_origin_get_prototype_if_ordinary_rawcx(
/// Implementation of `[[GetPrototypeOf]]` for [`Location`].
///
/// [`Location`]: https://html.spec.whatwg.org/multipage/#location-getprototypeof
pub unsafe fn maybe_cross_origin_get_prototype(
pub(crate) unsafe fn maybe_cross_origin_get_prototype(
cx: SafeJSContext,
proxy: RawHandleObject,
get_proto_object: unsafe fn(cx: SafeJSContext, global: HandleObject, rval: MutableHandleObject),
@ -396,7 +403,7 @@ pub unsafe fn maybe_cross_origin_get_prototype(
///
/// [`Location`]: https://html.spec.whatwg.org/multipage/#location-setprototypeof
/// [`WindowProxy`]: https://html.spec.whatwg.org/multipage/#windowproxy-setprototypeof
pub unsafe extern "C" fn maybe_cross_origin_set_prototype_rawcx(
pub(crate) unsafe extern "C" fn maybe_cross_origin_set_prototype_rawcx(
cx: *mut JSContext,
proxy: RawHandleObject,
proto: RawHandleObject,
@ -431,7 +438,7 @@ pub unsafe extern "C" fn maybe_cross_origin_set_prototype_rawcx(
/// for a maybe-cross-origin object.
///
/// [`CrossOriginGet`]: https://html.spec.whatwg.org/multipage/#crossoriginget-(-o,-p,-receiver-)
pub unsafe fn cross_origin_get(
pub(crate) unsafe fn cross_origin_get(
cx: SafeJSContext,
proxy: RawHandleObject,
receiver: RawHandleValue,
@ -497,7 +504,7 @@ pub unsafe fn cross_origin_get(
/// for a maybe-cross-origin object.
///
/// [`CrossOriginSet`]: https://html.spec.whatwg.org/multipage/#crossoriginset-(-o,-p,-v,-receiver-)
pub unsafe fn cross_origin_set(
pub(crate) unsafe fn cross_origin_set(
cx: SafeJSContext,
proxy: RawHandleObject,
id: RawHandleId,
@ -588,7 +595,7 @@ fn is_data_descriptor(d: &PropertyDescriptor) -> bool {
///
/// `cx` and `proxy` are expected to be different-Realm here. `proxy` is a proxy
/// for a maybe-cross-origin object.
pub unsafe fn cross_origin_has_own(
pub(crate) unsafe fn cross_origin_has_own(
cx: SafeJSContext,
_proxy: RawHandleObject,
cross_origin_properties: &'static CrossOriginProperties,
@ -614,7 +621,7 @@ pub unsafe fn cross_origin_has_own(
/// for a maybe-cross-origin object.
///
/// [`CrossOriginGetOwnPropertyHelper`]: https://html.spec.whatwg.org/multipage/#crossorigingetownpropertyhelper-(-o,-p-)
pub unsafe fn cross_origin_get_own_property_helper(
pub(crate) unsafe fn cross_origin_get_own_property_helper(
cx: SafeJSContext,
proxy: RawHandleObject,
cross_origin_properties: &'static CrossOriginProperties,
@ -640,7 +647,7 @@ pub unsafe fn cross_origin_get_own_property_helper(
/// for a maybe-cross-origin object.
///
/// [`CrossOriginPropertyFallback`]: https://html.spec.whatwg.org/multipage/#crossoriginpropertyfallback-(-p-)
pub unsafe fn cross_origin_property_fallback(
pub(crate) unsafe fn cross_origin_property_fallback(
cx: SafeJSContext,
_proxy: RawHandleObject,
id: RawHandleId,

View file

@ -23,7 +23,7 @@ use js::rust::{HandleId, HandleValue, IdVector, MutableHandleValue};
use crate::dom::bindings::conversions::jsid_to_string;
use crate::dom::bindings::str::{ByteString, DOMString, USVString};
pub trait RecordKey: Eq + Hash + Sized {
pub(crate) trait RecordKey: Eq + Hash + Sized {
fn to_utf16_vec(&self) -> Vec<u16>;
unsafe fn from_id(cx: *mut JSContext, id: HandleId) -> Result<ConversionResult<Self>, ()>;
}
@ -71,14 +71,14 @@ impl RecordKey for ByteString {
/// The `Record` (open-ended dictionary) type.
#[derive(Clone, JSTraceable)]
pub struct Record<K: RecordKey, V> {
pub(crate) struct Record<K: RecordKey, V> {
#[custom_trace]
map: IndexMap<K, V>,
}
impl<K: RecordKey, V> Record<K, V> {
/// Create an empty `Record`.
pub fn new() -> Self {
pub(crate) fn new() -> Self {
Record {
map: IndexMap::new(),
}

View file

@ -47,10 +47,10 @@ mod dummy {
use std::rc::Rc;
use super::LiveDOMReferences;
thread_local!(pub static LIVE_REFERENCES: Rc<RefCell<Option<LiveDOMReferences>>> =
thread_local!(pub(crate) static LIVE_REFERENCES: Rc<RefCell<Option<LiveDOMReferences>>> =
Rc::new(RefCell::new(None)));
}
pub use self::dummy::LIVE_REFERENCES;
pub(crate) use self::dummy::LIVE_REFERENCES;
/// A pointer to a Rust DOM object that needs to be destroyed.
#[derive(MallocSizeOf)]
@ -84,7 +84,7 @@ impl TrustedPromise {
/// be prevented from being GCed for the duration of the resulting `TrustedPromise` object's
/// lifetime.
#[allow(crown::unrooted_must_root)]
pub fn new(promise: Rc<Promise>) -> TrustedPromise {
pub(crate) fn new(promise: Rc<Promise>) -> TrustedPromise {
LIVE_REFERENCES.with(|r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
@ -100,7 +100,7 @@ impl TrustedPromise {
/// Obtain a usable DOM Promise from a pinned `TrustedPromise` value. Fails if used on
/// a different thread than the original value from which this `TrustedPromise` was
/// obtained.
pub fn root(self) -> Rc<Promise> {
pub(crate) fn root(self) -> Rc<Promise> {
LIVE_REFERENCES.with(|r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
@ -134,7 +134,7 @@ impl TrustedPromise {
/// A task which will reject the promise.
#[allow(crown::unrooted_must_root)]
pub fn reject_task(self, error: Error) -> impl TaskOnce {
pub(crate) fn reject_task(self, error: Error) -> impl TaskOnce {
let this = self;
task!(reject_promise: move || {
debug!("Rejecting promise.");
@ -144,7 +144,7 @@ impl TrustedPromise {
/// A task which will resolve the promise.
#[allow(crown::unrooted_must_root)]
pub fn resolve_task<T>(self, value: T) -> impl TaskOnce
pub(crate) fn resolve_task<T>(self, value: T) -> impl TaskOnce
where
T: ToJSValConvertible + Send,
{
@ -162,7 +162,7 @@ impl TrustedPromise {
/// `Trusted<T>` instance.
#[crown::unrooted_must_root_lint::allow_unrooted_interior]
#[derive(MallocSizeOf)]
pub struct Trusted<T: DomObject> {
pub(crate) struct Trusted<T: DomObject> {
/// A pointer to the Rust DOM object of type T, but void to allow
/// sending `Trusted<T>` between threads, regardless of T's sendability.
#[conditional_malloc_size_of]
@ -178,7 +178,7 @@ impl<T: DomObject> Trusted<T> {
/// Create a new `Trusted<T>` instance from an existing DOM pointer. The DOM object will
/// be prevented from being GCed for the duration of the resulting `Trusted<T>` object's
/// lifetime.
pub fn new(ptr: &T) -> Trusted<T> {
pub(crate) fn new(ptr: &T) -> Trusted<T> {
fn add_live_reference(
ptr: *const libc::c_void,
) -> (Arc<TrustedReference>, *const LiveDOMReferences) {
@ -201,7 +201,7 @@ impl<T: DomObject> Trusted<T> {
/// Obtain a usable DOM pointer from a pinned `Trusted<T>` value. Fails if used on
/// a different thread than the original value from which this `Trusted<T>` was
/// obtained.
pub fn root(&self) -> DomRoot<T> {
pub(crate) fn root(&self) -> DomRoot<T> {
fn validate(owner_thread: *const LiveDOMReferences) {
assert!(LIVE_REFERENCES.with(|r| {
let r = r.borrow();
@ -227,7 +227,7 @@ impl<T: DomObject> Clone for Trusted<T> {
/// The set of live, pinned DOM objects that are currently prevented
/// from being garbage collected due to outstanding references.
#[allow(crown::unrooted_must_root)]
pub struct LiveDOMReferences {
pub(crate) struct LiveDOMReferences {
// keyed on pointer to Rust DOM object
reflectable_table: RefCell<HashMap<*const libc::c_void, Weak<TrustedReference>>>,
promise_table: RefCell<HashMap<*const Promise, Vec<Rc<Promise>>>>,
@ -235,7 +235,7 @@ pub struct LiveDOMReferences {
impl LiveDOMReferences {
/// Set up the thread-local data required for storing the outstanding DOM references.
pub fn initialize() {
pub(crate) fn initialize() {
LIVE_REFERENCES.with(|r| {
*r.borrow_mut() = Some(LiveDOMReferences {
reflectable_table: RefCell::new(HashMap::new()),
@ -244,7 +244,7 @@ impl LiveDOMReferences {
});
}
pub fn destruct() {
pub(crate) fn destruct() {
LIVE_REFERENCES.with(|r| {
*r.borrow_mut() = None;
});
@ -302,7 +302,7 @@ fn remove_nulls<K: Eq + Hash + Clone, V>(table: &mut HashMap<K, Weak<V>>) {
/// A JSTraceDataOp for tracing reflectors held in LIVE_REFERENCES
#[allow(crown::unrooted_must_root)]
pub unsafe fn trace_refcounted_objects(tracer: *mut JSTracer) {
pub(crate) unsafe fn trace_refcounted_objects(tracer: *mut JSTracer) {
trace!("tracing live refcounted references");
LIVE_REFERENCES.with(|r| {
let r = r.borrow();

View file

@ -19,7 +19,7 @@ use crate::script_runtime::{CanGc, JSContext};
/// Create the reflector for a new DOM object and yield ownership to the
/// reflector.
pub fn reflect_dom_object<T, U>(obj: Box<T>, global: &U, can_gc: CanGc) -> DomRoot<T>
pub(crate) fn reflect_dom_object<T, U>(obj: Box<T>, global: &U, can_gc: CanGc) -> DomRoot<T>
where
T: DomObject + DomObjectWrap,
U: DerivedFrom<GlobalScope>,
@ -28,7 +28,7 @@ where
unsafe { T::WRAP(GlobalScope::get_cx(), global_scope, None, obj, can_gc) }
}
pub fn reflect_dom_object_with_proto<T, U>(
pub(crate) fn reflect_dom_object_with_proto<T, U>(
obj: Box<T>,
global: &U,
proto: Option<HandleObject>,
@ -47,7 +47,7 @@ where
#[derive(MallocSizeOf)]
#[crown::unrooted_must_root_lint::must_root]
// If you're renaming or moving this field, update the path in plugins::reflector as well
pub struct Reflector {
pub(crate) struct Reflector {
#[ignore_malloc_size_of = "defined and measured in rust-mozjs"]
object: Heap<*mut JSObject>,
}
@ -62,7 +62,7 @@ impl PartialEq for Reflector {
impl Reflector {
/// Get the reflector.
#[inline]
pub fn get_jsobject(&self) -> HandleObject {
pub(crate) fn get_jsobject(&self) -> HandleObject {
// We're rooted, so it's safe to hand out a handle to object in Heap
unsafe { HandleObject::from_raw(self.object.handle()) }
}
@ -72,7 +72,7 @@ impl Reflector {
/// # Safety
///
/// The provided [`JSObject`] pointer must point to a valid [`JSObject`].
pub unsafe fn set_jsobject(&self, object: *mut JSObject) {
pub(crate) unsafe fn set_jsobject(&self, object: *mut JSObject) {
assert!(self.object.get().is_null());
assert!(!object.is_null());
self.object.set(object);
@ -81,14 +81,14 @@ impl Reflector {
/// Return a pointer to the memory location at which the JS reflector
/// object is stored. Used to root the reflector, as
/// required by the JSAPI rooting APIs.
pub fn rootable(&self) -> &Heap<*mut JSObject> {
pub(crate) fn rootable(&self) -> &Heap<*mut JSObject> {
&self.object
}
/// Create an uninitialized `Reflector`.
// These are used by the bindings and do not need `default()` functions.
#[allow(clippy::new_without_default)]
pub fn new() -> Reflector {
pub(crate) fn new() -> Reflector {
Reflector {
object: Heap::default(),
}
@ -96,7 +96,7 @@ impl Reflector {
}
/// A trait to provide access to the `Reflector` for a DOM object.
pub trait DomObject: JSTraceable + 'static {
pub(crate) trait DomObject: JSTraceable + 'static {
/// Returns the receiver's reflector.
fn reflector(&self) -> &Reflector;
@ -119,7 +119,7 @@ impl DomObject for Reflector {
}
/// A trait to initialize the `Reflector` for a DOM object.
pub trait MutDomObject: DomObject {
pub(crate) trait MutDomObject: DomObject {
/// Initializes the Reflector
///
/// # Safety
@ -135,7 +135,7 @@ impl MutDomObject for Reflector {
}
/// A trait to provide a function pointer to wrap function for DOM objects.
pub trait DomObjectWrap: Sized + DomObject {
pub(crate) trait DomObjectWrap: Sized + DomObject {
/// Function pointer to the general wrap function type
#[allow(clippy::type_complexity)]
const WRAP: unsafe fn(
@ -149,7 +149,7 @@ pub trait DomObjectWrap: Sized + DomObject {
/// A trait to provide a function pointer to wrap function for
/// DOM iterator interfaces.
pub trait DomObjectIteratorWrap: DomObjectWrap + JSTraceable + Iterable {
pub(crate) trait DomObjectIteratorWrap: DomObjectWrap + JSTraceable + Iterable {
/// Function pointer to the wrap function for `IterableIterator<T>`
#[allow(clippy::type_complexity)]
const ITER_WRAP: unsafe fn(

View file

@ -45,7 +45,7 @@ use crate::dom::node::Node;
/// A rooted value.
#[allow(crown::unrooted_must_root)]
#[crown::unrooted_must_root_lint::allow_unrooted_interior]
pub struct Root<T: StableTraceObject> {
pub(crate) struct Root<T: StableTraceObject> {
/// The value to root.
value: T,
/// List that ensures correct dynamic root ordering
@ -60,7 +60,7 @@ where
/// It cannot outlive its associated `RootCollection`, and it gives
/// out references which cannot outlive this new `Root`.
#[allow(crown::unrooted_must_root)]
pub unsafe fn new(value: T) -> Self {
pub(crate) unsafe fn new(value: T) -> Self {
unsafe fn add_to_root_list(object: *const dyn JSTraceable) -> *const RootCollection {
assert_in_script();
STACK_ROOTS.with(|root_list| {
@ -85,7 +85,7 @@ where
/// owned and referenced objects, so that the garbage collector can accurately determine which
/// objects are still in use. Failing to adhere to this contract may result in undefined behavior,
/// such as use-after-free errors.
pub unsafe trait StableTraceObject {
pub(crate) unsafe trait StableTraceObject {
/// Returns a stable trace object which address won't change for the whole
/// lifetime of the value.
fn stable_trace_object(&self) -> *const dyn JSTraceable;
@ -160,11 +160,11 @@ where
}
/// A rooted reference to a DOM object.
pub type DomRoot<T> = Root<Dom<T>>;
pub(crate) type DomRoot<T> = Root<Dom<T>>;
impl<T: Castable> DomRoot<T> {
/// Cast a DOM object root upwards to one of the interfaces it derives from.
pub fn upcast<U>(root: DomRoot<T>) -> DomRoot<U>
pub(crate) fn upcast<U>(root: DomRoot<T>) -> DomRoot<U>
where
U: Castable,
T: DerivedFrom<U>,
@ -173,7 +173,7 @@ impl<T: Castable> DomRoot<T> {
}
/// Cast a DOM object root downwards to one of the interfaces it might implement.
pub fn downcast<U>(root: DomRoot<T>) -> Option<DomRoot<U>>
pub(crate) fn downcast<U>(root: DomRoot<T>) -> Option<DomRoot<U>>
where
U: DerivedFrom<T>,
{
@ -187,7 +187,7 @@ impl<T: Castable> DomRoot<T> {
impl<T: DomObject> DomRoot<T> {
/// Generate a new root from a reference
pub fn from_ref(unrooted: &T) -> DomRoot<T> {
pub(crate) fn from_ref(unrooted: &T) -> DomRoot<T> {
unsafe { DomRoot::new(Dom::from_ref(unrooted)) }
}
@ -245,16 +245,16 @@ where
/// See also [*Exact Stack Rooting - Storing a GCPointer on the CStack*][cstack].
///
/// [cstack]: https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Internals/GC/Exact_Stack_Rooting
pub struct RootCollection {
pub(crate) struct RootCollection {
roots: UnsafeCell<Vec<*const dyn JSTraceable>>,
}
thread_local!(static STACK_ROOTS: Cell<Option<*const RootCollection>> = const { Cell::new(None) });
pub struct ThreadLocalStackRoots<'a>(PhantomData<&'a u32>);
pub(crate) struct ThreadLocalStackRoots<'a>(PhantomData<&'a u32>);
impl<'a> ThreadLocalStackRoots<'a> {
pub fn new(roots: &'a RootCollection) -> Self {
pub(crate) fn new(roots: &'a RootCollection) -> Self {
STACK_ROOTS.with(|r| r.set(Some(roots)));
ThreadLocalStackRoots(PhantomData)
}
@ -268,7 +268,7 @@ impl Drop for ThreadLocalStackRoots<'_> {
impl RootCollection {
/// Create an empty collection of roots
pub fn new() -> RootCollection {
pub(crate) fn new() -> RootCollection {
assert_in_script();
RootCollection {
roots: UnsafeCell::new(vec![]),
@ -298,7 +298,7 @@ impl RootCollection {
}
/// SM Callback that traces the rooted reflectors
pub unsafe fn trace_roots(tracer: *mut JSTracer) {
pub(crate) unsafe fn trace_roots(tracer: *mut JSTracer) {
trace!("tracing stack roots");
STACK_ROOTS.with(|collection| {
let collection = &*(*collection.get().unwrap()).roots.get();
@ -309,7 +309,7 @@ pub unsafe fn trace_roots(tracer: *mut JSTracer) {
}
/// Get a slice of references to DOM objects.
pub trait DomSlice<T>
pub(crate) trait DomSlice<T>
where
T: JSTraceable + DomObject,
{
@ -336,7 +336,7 @@ where
///
/// This should only be used as a field in other DOM objects.
#[crown::unrooted_must_root_lint::must_root]
pub struct Dom<T> {
pub(crate) struct Dom<T> {
ptr: ptr::NonNull<T>,
}
@ -354,7 +354,7 @@ impl<T> Dom<T> {
/// # Safety
///
/// The `self` parameter to this method must meet all the requirements of [`ptr::NonNull::as_ref`].
pub unsafe fn to_layout(&self) -> LayoutDom<T> {
pub(crate) unsafe fn to_layout(&self) -> LayoutDom<T> {
assert_in_layout();
LayoutDom {
value: self.ptr.as_ref(),
@ -365,7 +365,7 @@ impl<T> Dom<T> {
impl<T: DomObject> Dom<T> {
/// Create a `Dom<T>` from a `&T`
#[allow(crown::unrooted_must_root)]
pub fn from_ref(obj: &T) -> Dom<T> {
pub(crate) fn from_ref(obj: &T) -> Dom<T> {
assert_in_script();
Dom {
ptr: ptr::NonNull::from(obj),
@ -404,7 +404,7 @@ unsafe impl<T: DomObject> JSTraceable for Dom<T> {
/// A traced reference to a DOM object that may not be reflected yet.
#[crown::unrooted_must_root_lint::must_root]
pub struct MaybeUnreflectedDom<T> {
pub(crate) struct MaybeUnreflectedDom<T> {
ptr: ptr::NonNull<T>,
}
@ -413,7 +413,7 @@ where
T: DomObject,
{
#[allow(crown::unrooted_must_root)]
pub unsafe fn from_box(value: Box<T>) -> Self {
pub(crate) unsafe fn from_box(value: Box<T>) -> Self {
Self {
ptr: Box::leak(value).into(),
}
@ -424,7 +424,7 @@ impl<T> Root<MaybeUnreflectedDom<T>>
where
T: DomObject,
{
pub fn as_ptr(&self) -> *const T {
pub(crate) fn as_ptr(&self) -> *const T {
self.value.ptr.as_ptr()
}
}
@ -433,7 +433,7 @@ impl<T> Root<MaybeUnreflectedDom<T>>
where
T: MutDomObject,
{
pub unsafe fn reflect_with(self, obj: *mut JSObject) -> DomRoot<T> {
pub(crate) unsafe fn reflect_with(self, obj: *mut JSObject) -> DomRoot<T> {
let ptr = self.as_ptr();
drop(self);
let root = DomRoot::from_ref(&*ptr);
@ -445,7 +445,7 @@ where
/// An unrooted reference to a DOM object for use in layout. `Layout*Helpers`
/// traits must be implemented on this.
#[crown::unrooted_must_root_lint::allow_unrooted_interior]
pub struct LayoutDom<'dom, T> {
pub(crate) struct LayoutDom<'dom, T> {
value: &'dom T,
}
@ -454,7 +454,7 @@ where
T: Castable,
{
/// Cast a DOM object root upwards to one of the interfaces it derives from.
pub fn upcast<U>(&self) -> LayoutDom<'dom, U>
pub(crate) fn upcast<U>(&self) -> LayoutDom<'dom, U>
where
U: Castable,
T: DerivedFrom<U>,
@ -466,7 +466,7 @@ where
}
/// Cast a DOM object downwards to one of the interfaces it might implement.
pub fn downcast<U>(&self) -> Option<LayoutDom<'dom, U>>
pub(crate) fn downcast<U>(&self) -> Option<LayoutDom<'dom, U>>
where
U: DerivedFrom<T>,
{
@ -475,7 +475,7 @@ where
}
/// Returns whether this inner object is a U.
pub fn is<U>(&self) -> bool
pub(crate) fn is<U>(&self) -> bool
where
U: DerivedFrom<T>,
{
@ -489,7 +489,7 @@ where
T: DomObject,
{
/// Get the reflector.
pub unsafe fn get_jsobject(&self) -> *mut JSObject {
pub(crate) unsafe fn get_jsobject(&self) -> *mut JSObject {
assert_in_layout();
self.value.reflector().get_jsobject().get()
}
@ -552,7 +552,7 @@ impl<T> Clone for LayoutDom<'_, T> {
impl LayoutDom<'_, Node> {
/// Create a new JS-owned value wrapped from an address known to be a
/// `Node` pointer.
pub unsafe fn from_trusted_node_address(inner: TrustedNodeAddress) -> Self {
pub(crate) unsafe fn from_trusted_node_address(inner: TrustedNodeAddress) -> Self {
assert_in_layout();
let TrustedNodeAddress(addr) = inner;
LayoutDom {
@ -568,13 +568,13 @@ impl LayoutDom<'_, Node> {
/// on `Dom<T>`.
#[crown::unrooted_must_root_lint::must_root]
#[derive(JSTraceable)]
pub struct MutDom<T: DomObject> {
pub(crate) struct MutDom<T: DomObject> {
val: UnsafeCell<Dom<T>>,
}
impl<T: DomObject> MutDom<T> {
/// Create a new `MutDom`.
pub fn new(initial: &T) -> MutDom<T> {
pub(crate) fn new(initial: &T) -> MutDom<T> {
assert_in_script();
MutDom {
val: UnsafeCell::new(Dom::from_ref(initial)),
@ -582,7 +582,7 @@ impl<T: DomObject> MutDom<T> {
}
/// Set this `MutDom` to the given value.
pub fn set(&self, val: &T) {
pub(crate) fn set(&self, val: &T) {
assert_in_script();
unsafe {
*self.val.get() = Dom::from_ref(val);
@ -590,7 +590,7 @@ impl<T: DomObject> MutDom<T> {
}
/// Get the value in this `MutDom`.
pub fn get(&self) -> DomRoot<T> {
pub(crate) fn get(&self) -> DomRoot<T> {
assert_in_script();
unsafe { DomRoot::from_ref(&*ptr::read(self.val.get())) }
}
@ -631,13 +631,13 @@ pub(crate) fn assert_in_layout() {
/// on `Dom<T>`.
#[crown::unrooted_must_root_lint::must_root]
#[derive(JSTraceable)]
pub struct MutNullableDom<T: DomObject> {
pub(crate) struct MutNullableDom<T: DomObject> {
ptr: UnsafeCell<Option<Dom<T>>>,
}
impl<T: DomObject> MutNullableDom<T> {
/// Create a new `MutNullableDom`.
pub fn new(initial: Option<&T>) -> MutNullableDom<T> {
pub(crate) fn new(initial: Option<&T>) -> MutNullableDom<T> {
assert_in_script();
MutNullableDom {
ptr: UnsafeCell::new(initial.map(Dom::from_ref)),
@ -646,7 +646,7 @@ impl<T: DomObject> MutNullableDom<T> {
/// Retrieve a copy of the current inner value. If it is `None`, it is
/// initialized with the result of `cb` first.
pub fn or_init<F>(&self, cb: F) -> DomRoot<T>
pub(crate) fn or_init<F>(&self, cb: F) -> DomRoot<T>
where
F: FnOnce() -> DomRoot<T>,
{
@ -664,20 +664,20 @@ impl<T: DomObject> MutNullableDom<T> {
/// Retrieve a copy of the inner optional `Dom<T>` as `LayoutDom<T>`.
/// For use by layout, which can't use safe types like Temporary.
#[allow(crown::unrooted_must_root)]
pub unsafe fn get_inner_as_layout(&self) -> Option<LayoutDom<T>> {
pub(crate) unsafe fn get_inner_as_layout(&self) -> Option<LayoutDom<T>> {
assert_in_layout();
(*self.ptr.get()).as_ref().map(|js| js.to_layout())
}
/// Get a rooted value out of this object
#[allow(crown::unrooted_must_root)]
pub fn get(&self) -> Option<DomRoot<T>> {
pub(crate) fn get(&self) -> Option<DomRoot<T>> {
assert_in_script();
unsafe { ptr::read(self.ptr.get()).map(|o| DomRoot::from_ref(&*o)) }
}
/// Set this `MutNullableDom` to the given value.
pub fn set(&self, val: Option<&T>) {
pub(crate) fn set(&self, val: Option<&T>) {
assert_in_script();
unsafe {
*self.ptr.get() = val.map(|p| Dom::from_ref(p));
@ -685,7 +685,7 @@ impl<T: DomObject> MutNullableDom<T> {
}
/// Gets the current value out of this object and sets it to `None`.
pub fn take(&self) -> Option<DomRoot<T>> {
pub(crate) fn take(&self) -> Option<DomRoot<T>> {
let value = self.get();
self.set(None);
value
@ -728,7 +728,7 @@ impl<T: DomObject> MallocSizeOf for MutNullableDom<T> {
/// This should only be used as a field in other DOM objects; see warning
/// on `Dom<T>`.
#[crown::unrooted_must_root_lint::must_root]
pub struct DomOnceCell<T: DomObject> {
pub(crate) struct DomOnceCell<T: DomObject> {
ptr: OnceCell<Dom<T>>,
}
@ -739,7 +739,7 @@ where
/// Retrieve a copy of the current inner value. If it is `None`, it is
/// initialized with the result of `cb` first.
#[allow(crown::unrooted_must_root)]
pub fn init_once<F>(&self, cb: F) -> &T
pub(crate) fn init_once<F>(&self, cb: F) -> &T
where
F: FnOnce() -> DomRoot<T>,
{
@ -780,14 +780,14 @@ where
{
/// Returns a reference to the interior of this JS object. The fact
/// that this is unsafe is what necessitates the layout wrappers.
pub fn unsafe_get(self) -> &'dom T {
pub(crate) fn unsafe_get(self) -> &'dom T {
assert_in_layout();
self.value
}
/// Transforms a slice of `Dom<T>` into a slice of `LayoutDom<T>`.
// FIXME(nox): This should probably be done through a ToLayout trait.
pub unsafe fn to_layout_slice(slice: &'dom [Dom<T>]) -> &'dom [LayoutDom<'dom, T>] {
pub(crate) unsafe fn to_layout_slice(slice: &'dom [Dom<T>]) -> &'dom [LayoutDom<'dom, T>] {
// This doesn't compile if Dom and LayoutDom don't have the same
// representation.
let _ = mem::transmute::<Dom<T>, LayoutDom<T>>;

View file

@ -13,14 +13,14 @@ use crate::script_runtime::CanGc;
/// The key corresponding to the storage location
/// of a serialized platform object stored in a StructuredDataHolder.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct StorageKey {
pub index: u32,
pub name_space: u32,
pub(crate) struct StorageKey {
pub(crate) index: u32,
pub(crate) name_space: u32,
}
/// Interface for serializable platform objects.
/// <https://html.spec.whatwg.org/multipage/#serializable>
pub trait Serializable: DomObject {
pub(crate) trait Serializable: DomObject {
/// <https://html.spec.whatwg.org/multipage/#serialization-steps>
fn serialize(&self, sc_writer: &mut StructuredDataWriter) -> Result<StorageKey, ()>;
/// <https://html.spec.whatwg.org/multipage/#deserialization-steps>

View file

@ -29,18 +29,18 @@ struct StackEntry {
}
/// Traces the script settings stack.
pub unsafe fn trace(tracer: *mut JSTracer) {
pub(crate) unsafe fn trace(tracer: *mut JSTracer) {
STACK.with(|stack| {
stack.borrow().trace(tracer);
})
}
pub fn is_execution_stack_empty() -> bool {
pub(crate) fn is_execution_stack_empty() -> bool {
STACK.with(|stack| stack.borrow().is_empty())
}
/// RAII struct that pushes and pops entries from the script settings stack.
pub struct AutoEntryScript {
pub(crate) struct AutoEntryScript {
global: DomRoot<GlobalScope>,
#[cfg(feature = "tracing")]
span: tracing::span::EnteredSpan,
@ -48,7 +48,7 @@ pub struct AutoEntryScript {
impl AutoEntryScript {
/// <https://html.spec.whatwg.org/multipage/#prepare-to-run-script>
pub fn new(global: &GlobalScope) -> Self {
pub(crate) fn new(global: &GlobalScope) -> Self {
STACK.with(|stack| {
trace!("Prepare to run script with {:p}", global);
let mut stack = stack.borrow_mut();
@ -94,7 +94,7 @@ impl Drop for AutoEntryScript {
/// Returns the ["entry"] global object.
///
/// ["entry"]: https://html.spec.whatwg.org/multipage/#entry
pub fn entry_global() -> DomRoot<GlobalScope> {
pub(crate) fn entry_global() -> DomRoot<GlobalScope> {
STACK
.with(|stack| {
stack
@ -108,13 +108,13 @@ pub fn entry_global() -> DomRoot<GlobalScope> {
}
/// RAII struct that pushes and pops entries from the script settings stack.
pub struct AutoIncumbentScript {
pub(crate) struct AutoIncumbentScript {
global: usize,
}
impl AutoIncumbentScript {
/// <https://html.spec.whatwg.org/multipage/#prepare-to-run-a-callback>
pub fn new(global: &GlobalScope) -> Self {
pub(crate) fn new(global: &GlobalScope) -> Self {
// Step 2-3.
unsafe {
let cx =
@ -166,7 +166,7 @@ impl Drop for AutoIncumbentScript {
/// Returns the ["incumbent"] global object.
///
/// ["incumbent"]: https://html.spec.whatwg.org/multipage/#incumbent
pub fn incumbent_global() -> Option<DomRoot<GlobalScope>> {
pub(crate) fn incumbent_global() -> Option<DomRoot<GlobalScope>> {
// https://html.spec.whatwg.org/multipage/#incumbent-settings-object
// Step 1, 3: See what the JS engine has to say. If we've got a scripted

View file

@ -31,22 +31,22 @@ impl ByteString {
/// Returns `self` as a string, if it encodes valid UTF-8, and `None`
/// otherwise.
pub fn as_str(&self) -> Option<&str> {
pub(crate) fn as_str(&self) -> Option<&str> {
str::from_utf8(&self.0).ok()
}
/// Returns the length.
pub fn len(&self) -> usize {
pub(crate) fn len(&self) -> usize {
self.0.len()
}
/// Checks if the ByteString is empty.
pub fn is_empty(&self) -> bool {
pub(crate) fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Returns `self` with AZ replaced by az.
pub fn to_lower(&self) -> ByteString {
pub(crate) fn to_lower(&self) -> ByteString {
ByteString::new(self.0.to_ascii_lowercase())
}
}
@ -80,7 +80,7 @@ impl ops::Deref for ByteString {
/// A string that is constructed from a UCS-2 buffer by replacing invalid code
/// points with the replacement character.
#[derive(Clone, Default, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd)]
pub struct USVString(pub String);
pub(crate) struct USVString(pub(crate) String);
impl Borrow<str> for USVString {
#[inline]
@ -138,7 +138,7 @@ impl From<String> for USVString {
/// Returns whether `s` is a `token`, as defined by
/// [RFC 2616](http://tools.ietf.org/html/rfc2616#page-17).
pub fn is_token(s: &[u8]) -> bool {
pub(crate) fn is_token(s: &[u8]) -> bool {
if s.is_empty() {
return false; // A token must be at least a single character
}
@ -195,43 +195,43 @@ pub struct DOMString(String, PhantomData<*const ()>);
impl DOMString {
/// Creates a new `DOMString`.
pub fn new() -> DOMString {
pub(crate) fn new() -> DOMString {
DOMString(String::new(), PhantomData)
}
/// Creates a new `DOMString` from a `String`.
pub fn from_string(s: String) -> DOMString {
pub(crate) fn from_string(s: String) -> DOMString {
DOMString(s, PhantomData)
}
/// Get the internal `&str` value of this [`DOMString`].
pub fn str(&self) -> &str {
pub(crate) fn str(&self) -> &str {
&self.0
}
/// Appends a given string slice onto the end of this String.
pub fn push_str(&mut self, string: &str) {
pub(crate) fn push_str(&mut self, string: &str) {
self.0.push_str(string)
}
/// Clears this `DOMString`, removing all contents.
pub fn clear(&mut self) {
pub(crate) fn clear(&mut self) {
self.0.clear()
}
/// Shortens this String to the specified length.
pub fn truncate(&mut self, new_len: usize) {
pub(crate) fn truncate(&mut self, new_len: usize) {
self.0.truncate(new_len);
}
/// Removes newline characters according to <https://infra.spec.whatwg.org/#strip-newlines>.
pub fn strip_newlines(&mut self) {
pub(crate) fn strip_newlines(&mut self) {
self.0.retain(|c| c != '\r' && c != '\n');
}
/// Removes leading and trailing ASCII whitespaces according to
/// <https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace>.
pub fn strip_leading_and_trailing_ascii_whitespace(&mut self) {
pub(crate) fn strip_leading_and_trailing_ascii_whitespace(&mut self) {
if self.0.is_empty() {
return;
}
@ -250,7 +250,7 @@ impl DOMString {
}
/// <https://html.spec.whatwg.org/multipage/#valid-floating-point-number>
pub fn is_valid_floating_point_number_string(&self) -> bool {
pub(crate) fn is_valid_floating_point_number_string(&self) -> bool {
static RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"^-?(?:\d+\.\d+|\d+|\.\d+)(?:(e|E)(\+|\-)?\d+)?$").unwrap()
});
@ -259,7 +259,7 @@ impl DOMString {
}
/// <https://html.spec.whatwg.org/multipage/#rules-for-parsing-floating-point-number-values>
pub fn parse_floating_point_number(&self) -> Option<f64> {
pub(crate) fn parse_floating_point_number(&self) -> Option<f64> {
// Steps 15-16 are telling us things about IEEE rounding modes
// for floating-point significands; this code assumes the Rust
// compiler already matches them in any cases where
@ -286,7 +286,7 @@ impl DOMString {
///
/// <https://html.spec.whatwg.org/multipage/#best-representation-of-the-number-as-a-floating-point-number>
/// <https://tc39.es/ecma262/#sec-numeric-types-number-tostring>
pub fn set_best_representation_of_the_floating_point_number(&mut self) {
pub(crate) fn set_best_representation_of_the_floating_point_number(&mut self) {
if let Some(val) = self.parse_floating_point_number() {
// [tc39] Step 2: If x is either +0 or -0, return "0".
let parsed_value = if val.is_zero() { 0.0_f64 } else { val };

View file

@ -255,32 +255,32 @@ static STRUCTURED_CLONE_CALLBACKS: JSStructuredCloneCallbacks = JSStructuredClon
/// Reader and writer structs for results from, and inputs to, structured-data read/write operations.
/// <https://html.spec.whatwg.org/multipage/#safe-passing-of-structured-data>
pub struct StructuredDataReader {
pub(crate) struct StructuredDataReader {
/// A map of deserialized blobs, stored temporarily here to keep them rooted.
pub blobs: Option<HashMap<StorageKey, DomRoot<Blob>>>,
pub(crate) blobs: Option<HashMap<StorageKey, DomRoot<Blob>>>,
/// A vec of transfer-received DOM ports,
/// to be made available to script through a message event.
pub message_ports: Option<Vec<DomRoot<MessagePort>>>,
pub(crate) message_ports: Option<Vec<DomRoot<MessagePort>>>,
/// A map of port implementations,
/// used as part of the "transfer-receiving" steps of ports,
/// to produce the DOM ports stored in `message_ports` above.
pub port_impls: Option<HashMap<MessagePortId, MessagePortImpl>>,
pub(crate) port_impls: Option<HashMap<MessagePortId, MessagePortImpl>>,
/// A map of blob implementations,
/// used as part of the "deserialize" steps of blobs,
/// to produce the DOM blobs stored in `blobs` above.
pub blob_impls: Option<HashMap<BlobId, BlobImpl>>,
pub(crate) blob_impls: Option<HashMap<BlobId, BlobImpl>>,
}
/// A data holder for transferred and serialized objects.
pub struct StructuredDataWriter {
pub(crate) struct StructuredDataWriter {
/// Transferred ports.
pub ports: Option<HashMap<MessagePortId, MessagePortImpl>>,
pub(crate) ports: Option<HashMap<MessagePortId, MessagePortImpl>>,
/// Serialized blobs.
pub blobs: Option<HashMap<BlobId, BlobImpl>>,
pub(crate) blobs: Option<HashMap<BlobId, BlobImpl>>,
}
/// Writes a structured clone. Returns a `DataClone` error if that fails.
pub fn write(
pub(crate) fn write(
cx: SafeJSContext,
message: HandleValue,
transfer: Option<CustomAutoRooterGuard<Vec<*mut JSObject>>>,
@ -339,7 +339,7 @@ pub fn write(
/// Read structured serialized data, possibly containing transferred objects.
/// Returns a vec of rooted transfer-received ports, or an error.
pub fn read(
pub(crate) fn read(
global: &GlobalScope,
mut data: StructuredSerializedData,
rval: MutableHandleValue,

View file

@ -40,8 +40,8 @@ use std::ops::{Deref, DerefMut};
use crossbeam_channel::Sender;
use indexmap::IndexMap;
/// A trait to allow tracing (only) DOM objects.
pub use js::gc::Traceable as JSTraceable;
pub use js::gc::{RootableVec, RootedVec};
pub(crate) use js::gc::Traceable as JSTraceable;
pub(crate) use js::gc::{RootableVec, RootedVec};
use js::glue::{CallObjectTracer, CallScriptTracer, CallStringTracer, CallValueTracer};
use js::jsapi::{GCTraceKindToAscii, Heap, JSObject, JSScript, JSString, JSTracer, TraceKind};
use js::jsval::JSVal;
@ -76,7 +76,7 @@ use crate::task::TaskBox;
///
/// This trait is unsafe; if it is implemented incorrectly, the GC may end up collecting objects
/// that are still reachable.
pub unsafe trait CustomTraceable {
pub(crate) unsafe trait CustomTraceable {
/// Trace `self`.
///
/// # Safety
@ -117,7 +117,7 @@ unsafe impl<T> CustomTraceable for Sender<T> {
/// SAFETY: Inner type must not impl JSTraceable
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[crown::trace_in_no_trace_lint::must_not_have_traceable]
pub struct NoTrace<T>(pub T);
pub(crate) struct NoTrace<T>(pub(crate) T);
impl<T: Display> Display for NoTrace<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
@ -148,7 +148,7 @@ impl<T: MallocSizeOf> MallocSizeOf for NoTrace<T> {
/// Not all methods are reexposed, but you can access inner type via .0
#[crown::trace_in_no_trace_lint::must_not_have_traceable(0)]
#[derive(Clone, Debug)]
pub struct HashMapTracedValues<K, V, S = RandomState>(pub HashMap<K, V, S>);
pub(crate) struct HashMapTracedValues<K, V, S = RandomState>(pub(crate) HashMap<K, V, S>);
impl<K, V, S: Default> Default for HashMapTracedValues<K, V, S> {
fn default() -> Self {
@ -160,24 +160,24 @@ impl<K, V> HashMapTracedValues<K, V, RandomState> {
/// Wrapper for HashMap::new()
#[inline]
#[must_use]
pub fn new() -> HashMapTracedValues<K, V, RandomState> {
pub(crate) fn new() -> HashMapTracedValues<K, V, RandomState> {
Self(HashMap::new())
}
}
impl<K, V, S> HashMapTracedValues<K, V, S> {
#[inline]
pub fn iter(&self) -> std::collections::hash_map::Iter<'_, K, V> {
pub(crate) fn iter(&self) -> std::collections::hash_map::Iter<'_, K, V> {
self.0.iter()
}
#[inline]
pub fn drain(&mut self) -> std::collections::hash_map::Drain<'_, K, V> {
pub(crate) fn drain(&mut self) -> std::collections::hash_map::Drain<'_, K, V> {
self.0.drain()
}
#[inline]
pub fn is_empty(&self) -> bool {
pub(crate) fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
@ -188,12 +188,12 @@ where
S: BuildHasher,
{
#[inline]
pub fn insert(&mut self, k: K, v: V) -> Option<V> {
pub(crate) fn insert(&mut self, k: K, v: V) -> Option<V> {
self.0.insert(k, v)
}
#[inline]
pub fn get<Q>(&self, k: &Q) -> Option<&V>
pub(crate) fn get<Q>(&self, k: &Q) -> Option<&V>
where
K: std::borrow::Borrow<Q>,
Q: Hash + Eq + ?Sized,
@ -202,7 +202,7 @@ where
}
#[inline]
pub fn get_mut<Q: Hash + Eq + ?Sized>(&mut self, k: &Q) -> Option<&mut V>
pub(crate) fn get_mut<Q: Hash + Eq + ?Sized>(&mut self, k: &Q) -> Option<&mut V>
where
K: std::borrow::Borrow<Q>,
{
@ -210,7 +210,7 @@ where
}
#[inline]
pub fn contains_key<Q: Hash + Eq + ?Sized>(&self, k: &Q) -> bool
pub(crate) fn contains_key<Q: Hash + Eq + ?Sized>(&self, k: &Q) -> bool
where
K: std::borrow::Borrow<Q>,
{
@ -218,7 +218,7 @@ where
}
#[inline]
pub fn remove<Q: Hash + Eq + ?Sized>(&mut self, k: &Q) -> Option<V>
pub(crate) fn remove<Q: Hash + Eq + ?Sized>(&mut self, k: &Q) -> Option<V>
where
K: std::borrow::Borrow<Q>,
{
@ -226,7 +226,7 @@ where
}
#[inline]
pub fn entry(&mut self, key: K) -> std::collections::hash_map::Entry<'_, K, V> {
pub(crate) fn entry(&mut self, key: K) -> std::collections::hash_map::Entry<'_, K, V> {
self.0.entry(key)
}
}
@ -260,7 +260,7 @@ unsafe_no_jsmanaged_fields!(Reflector);
#[allow(dead_code)]
/// Trace a `JSScript`.
pub fn trace_script(tracer: *mut JSTracer, description: &str, script: &Heap<*mut JSScript>) {
pub(crate) fn trace_script(tracer: *mut JSTracer, description: &str, script: &Heap<*mut JSScript>) {
unsafe {
trace!("tracing {}", description);
CallScriptTracer(
@ -273,7 +273,7 @@ pub fn trace_script(tracer: *mut JSTracer, description: &str, script: &Heap<*mut
#[allow(dead_code)]
/// Trace a `JSVal`.
pub fn trace_jsval(tracer: *mut JSTracer, description: &str, val: &Heap<JSVal>) {
pub(crate) fn trace_jsval(tracer: *mut JSTracer, description: &str, val: &Heap<JSVal>) {
unsafe {
if !val.get().is_markable() {
return;
@ -290,13 +290,13 @@ pub fn trace_jsval(tracer: *mut JSTracer, description: &str, val: &Heap<JSVal>)
/// Trace the `JSObject` held by `reflector`.
#[allow(crown::unrooted_must_root)]
pub fn trace_reflector(tracer: *mut JSTracer, description: &str, reflector: &Reflector) {
pub(crate) fn trace_reflector(tracer: *mut JSTracer, description: &str, reflector: &Reflector) {
trace!("tracing reflector {}", description);
trace_object(tracer, description, reflector.rootable())
}
/// Trace a `JSObject`.
pub fn trace_object(tracer: *mut JSTracer, description: &str, obj: &Heap<*mut JSObject>) {
pub(crate) fn trace_object(tracer: *mut JSTracer, description: &str, obj: &Heap<*mut JSObject>) {
unsafe {
trace!("tracing {}", description);
CallObjectTracer(
@ -309,7 +309,7 @@ pub fn trace_object(tracer: *mut JSTracer, description: &str, obj: &Heap<*mut JS
#[allow(dead_code)]
/// Trace a `JSString`.
pub fn trace_string(tracer: *mut JSTracer, description: &str, s: &Heap<*mut JSString>) {
pub(crate) fn trace_string(tracer: *mut JSTracer, description: &str, s: &Heap<*mut JSString>) {
unsafe {
trace!("tracing {}", description);
CallStringTracer(
@ -491,7 +491,7 @@ where
/// If you have an arbitrary number of DomObjects to root, use rooted_vec!.
/// If you know what you're doing, use this.
#[crown::unrooted_must_root_lint::allow_unrooted_interior]
pub struct RootedTraceableBox<T: JSTraceable + 'static>(js::gc::RootedTraceableBox<T>);
pub(crate) struct RootedTraceableBox<T: JSTraceable + 'static>(js::gc::RootedTraceableBox<T>);
unsafe impl<T: JSTraceable + 'static> JSTraceable for RootedTraceableBox<T> {
unsafe fn trace(&self, tracer: *mut JSTracer) {
@ -501,12 +501,12 @@ unsafe impl<T: JSTraceable + 'static> JSTraceable for RootedTraceableBox<T> {
impl<T: JSTraceable + 'static> RootedTraceableBox<T> {
/// DomRoot a JSTraceable thing for the life of this RootedTraceableBox
pub fn new(traceable: T) -> RootedTraceableBox<T> {
pub(crate) fn new(traceable: T) -> RootedTraceableBox<T> {
Self(js::gc::RootedTraceableBox::new(traceable))
}
/// Consumes a boxed JSTraceable and roots it for the life of this RootedTraceableBox.
pub fn from_box(boxed_traceable: Box<T>) -> RootedTraceableBox<T> {
pub(crate) fn from_box(boxed_traceable: Box<T>) -> RootedTraceableBox<T> {
Self(js::gc::RootedTraceableBox::from_box(boxed_traceable))
}
}
@ -516,7 +516,7 @@ where
Heap<T>: JSTraceable + 'static,
T: GCMethods + Copy,
{
pub fn handle(&self) -> Handle<T> {
pub(crate) fn handle(&self) -> Handle<T> {
self.0.handle()
}
}

View file

@ -11,7 +11,7 @@ use crate::dom::bindings::reflector::DomObject;
use crate::dom::bindings::structuredclone::{StructuredDataReader, StructuredDataWriter};
use crate::dom::globalscope::GlobalScope;
pub trait Transferable: DomObject {
pub(crate) trait Transferable: DomObject {
fn transfer(&self, sc_writer: &mut StructuredDataWriter) -> Result<u64, ()>;
fn transfer_receive(
owner: &GlobalScope,

View file

@ -55,15 +55,15 @@ use crate::script_runtime::JSContext as SafeJSContext;
/// This is needed to allow using JS API types (which usually involve raw pointers) in static initializers,
/// when Servo guarantees through the use of OnceLock that only one thread will ever initialize
/// the value.
pub struct ThreadUnsafeOnceLock<T>(OnceLock<T>);
pub(crate) struct ThreadUnsafeOnceLock<T>(OnceLock<T>);
impl<T> ThreadUnsafeOnceLock<T> {
pub const fn new() -> Self {
pub(crate) const fn new() -> Self {
Self(OnceLock::new())
}
/// Initialize the value inside this lock. Panics if the lock has been previously initialized.
pub fn set(&self, val: T) {
pub(crate) fn set(&self, val: T) {
assert!(self.0.set(val).is_ok());
}
@ -72,7 +72,7 @@ impl<T> ThreadUnsafeOnceLock<T> {
/// SAFETY:
/// The caller must ensure that it does not mutate value contained inside this lock
/// (using interior mutability).
pub unsafe fn get(&self) -> &T {
pub(crate) unsafe fn get(&self) -> &T {
self.0.get().unwrap()
}
}
@ -82,15 +82,15 @@ unsafe impl<T> Send for ThreadUnsafeOnceLock<T> {}
#[derive(JSTraceable, MallocSizeOf)]
/// Static data associated with a global object.
pub struct GlobalStaticData {
pub(crate) struct GlobalStaticData {
#[ignore_malloc_size_of = "WindowProxyHandler does not properly implement it anyway"]
/// The WindowProxy proxy handler for this global.
pub windowproxy_handler: &'static WindowProxyHandler,
pub(crate) windowproxy_handler: &'static WindowProxyHandler,
}
impl GlobalStaticData {
/// Creates a new GlobalStaticData.
pub fn new() -> GlobalStaticData {
pub(crate) fn new() -> GlobalStaticData {
GlobalStaticData {
windowproxy_handler: WindowProxyHandler::proxy_handler(),
}
@ -99,47 +99,47 @@ impl GlobalStaticData {
/// The index of the slot where the object holder of that interface's
/// unforgeable members are defined.
pub const DOM_PROTO_UNFORGEABLE_HOLDER_SLOT: u32 = 0;
pub(crate) const DOM_PROTO_UNFORGEABLE_HOLDER_SLOT: u32 = 0;
/// The index of the slot that contains a reference to the ProtoOrIfaceArray.
// All DOM globals must have a slot at DOM_PROTOTYPE_SLOT.
pub const DOM_PROTOTYPE_SLOT: u32 = js::JSCLASS_GLOBAL_SLOT_COUNT;
pub(crate) const DOM_PROTOTYPE_SLOT: u32 = js::JSCLASS_GLOBAL_SLOT_COUNT;
/// The flag set on the `JSClass`es for DOM global objects.
// NOTE: This is baked into the Ion JIT as 0 in codegen for LGetDOMProperty and
// LSetDOMProperty. Those constants need to be changed accordingly if this value
// changes.
pub const JSCLASS_DOM_GLOBAL: u32 = js::JSCLASS_USERBIT1;
pub(crate) const JSCLASS_DOM_GLOBAL: u32 = js::JSCLASS_USERBIT1;
/// The struct that holds inheritance information for DOM object reflectors.
#[derive(Clone, Copy)]
pub struct DOMClass {
pub(crate) struct DOMClass {
/// A list of interfaces that this object implements, in order of decreasing
/// derivedness.
pub interface_chain: [PrototypeList::ID; MAX_PROTO_CHAIN_LENGTH],
pub(crate) interface_chain: [PrototypeList::ID; MAX_PROTO_CHAIN_LENGTH],
/// The last valid index of `interface_chain`.
pub depth: u8,
pub(crate) depth: u8,
/// The type ID of that interface.
pub type_id: TopTypeId,
pub(crate) type_id: TopTypeId,
/// The MallocSizeOf function wrapper for that interface.
pub malloc_size_of: unsafe fn(ops: &mut MallocSizeOfOps, *const c_void) -> usize,
pub(crate) malloc_size_of: unsafe fn(ops: &mut MallocSizeOfOps, *const c_void) -> usize,
/// The `Globals` flag for this global interface, if any.
pub global: InterfaceObjectMap::Globals,
pub(crate) global: InterfaceObjectMap::Globals,
}
unsafe impl Sync for DOMClass {}
/// The JSClass used for DOM object reflectors.
#[derive(Copy)]
#[repr(C)]
pub struct DOMJSClass {
pub(crate) struct DOMJSClass {
/// The actual JSClass.
pub base: js::jsapi::JSClass,
pub(crate) base: js::jsapi::JSClass,
/// Associated data for DOM object reflectors.
pub dom_class: DOMClass,
pub(crate) dom_class: DOMClass,
}
impl Clone for DOMJSClass {
fn clone(&self) -> DOMJSClass {
@ -149,7 +149,7 @@ impl Clone for DOMJSClass {
unsafe impl Sync for DOMJSClass {}
/// Returns a JSVal representing the frozen JavaScript array
pub fn to_frozen_array<T: ToJSValConvertible>(
pub(crate) fn to_frozen_array<T: ToJSValConvertible>(
convertibles: &[T],
cx: SafeJSContext,
rval: MutableHandleValue,
@ -162,7 +162,7 @@ pub fn to_frozen_array<T: ToJSValConvertible>(
/// Returns the ProtoOrIfaceArray for the given global object.
/// Fails if `global` is not a DOM global object.
pub fn get_proto_or_iface_array(global: *mut JSObject) -> *mut ProtoOrIfaceArray {
pub(crate) fn get_proto_or_iface_array(global: *mut JSObject) -> *mut ProtoOrIfaceArray {
unsafe {
assert_ne!(((*get_object_class(global)).flags & JSCLASS_DOM_GLOBAL), 0);
let mut slot = UndefinedValue();
@ -172,13 +172,13 @@ pub fn get_proto_or_iface_array(global: *mut JSObject) -> *mut ProtoOrIfaceArray
}
/// An array of *mut JSObject of size PROTO_OR_IFACE_LENGTH.
pub type ProtoOrIfaceArray = [*mut JSObject; PROTO_OR_IFACE_LENGTH];
pub(crate) type ProtoOrIfaceArray = [*mut JSObject; PROTO_OR_IFACE_LENGTH];
/// Gets the property `id` on `proxy`'s prototype. If it exists, `*found` is
/// set to true and `*vp` to the value, otherwise `*found` is set to false.
///
/// Returns false on JSAPI failure.
pub unsafe fn get_property_on_prototype(
pub(crate) unsafe fn get_property_on_prototype(
cx: *mut JSContext,
proxy: HandleObject,
receiver: HandleValue,
@ -205,7 +205,7 @@ pub unsafe fn get_property_on_prototype(
/// Get an array index from the given `jsid`. Returns `None` if the given
/// `jsid` is not an integer.
pub unsafe fn get_array_index_from_id(_cx: *mut JSContext, id: HandleId) -> Option<u32> {
pub(crate) unsafe fn get_array_index_from_id(_cx: *mut JSContext, id: HandleId) -> Option<u32> {
let raw_id = *id;
if raw_id.is_int() {
return Some(raw_id.to_int() as u32);
@ -266,7 +266,7 @@ pub unsafe fn get_array_index_from_id(_cx: *mut JSContext, id: HandleId) -> Opti
/// Find the enum equivelent of a string given by `v` in `pairs`.
/// Returns `Err(())` on JSAPI failure (there is a pending exception), and
/// `Ok((None, value))` if there was no matching string.
pub unsafe fn find_enum_value<'a, T>(
pub(crate) unsafe fn find_enum_value<'a, T>(
cx: *mut JSContext,
v: HandleValue,
pairs: &'a [(&'static str, T)],
@ -289,7 +289,7 @@ pub unsafe fn find_enum_value<'a, T>(
/// Returns wether `obj` is a platform object using dynamic unwrap
/// <https://heycam.github.io/webidl/#dfn-platform-object>
#[allow(dead_code)]
pub fn is_platform_object_dynamic(obj: *mut JSObject, cx: *mut JSContext) -> bool {
pub(crate) fn is_platform_object_dynamic(obj: *mut JSObject, cx: *mut JSContext) -> bool {
is_platform_object(obj, &|o| unsafe {
UnwrapObjectDynamic(o, cx, /* stopAtWindowProxy = */ false)
})
@ -297,7 +297,7 @@ pub fn is_platform_object_dynamic(obj: *mut JSObject, cx: *mut JSContext) -> boo
/// Returns wether `obj` is a platform object using static unwrap
/// <https://heycam.github.io/webidl/#dfn-platform-object>
pub fn is_platform_object_static(obj: *mut JSObject) -> bool {
pub(crate) fn is_platform_object_static(obj: *mut JSObject) -> bool {
is_platform_object(obj, &|o| unsafe { UnwrapObjectStatic(o) })
}
@ -327,7 +327,7 @@ fn is_platform_object(
/// Get the property with name `property` from `object`.
/// Returns `Err(())` on JSAPI failure (there is a pending exception), and
/// `Ok(false)` if there was no property with the given name.
pub fn get_dictionary_property(
pub(crate) fn get_dictionary_property(
cx: *mut JSContext,
object: HandleObject,
property: &str,
@ -374,7 +374,7 @@ pub fn get_dictionary_property(
/// Set the property with name `property` from `object`.
/// Returns `Err(())` on JSAPI failure, or null object,
/// and Ok(()) otherwise
pub fn set_dictionary_property(
pub(crate) fn set_dictionary_property(
cx: *mut JSContext,
object: HandleObject,
property: &str,
@ -395,7 +395,7 @@ pub fn set_dictionary_property(
}
/// Returns whether `proxy` has a property `id` on its prototype.
pub unsafe fn has_property_on_prototype(
pub(crate) unsafe fn has_property_on_prototype(
cx: *mut JSContext,
proxy: HandleObject,
id: HandleId,
@ -410,7 +410,7 @@ pub unsafe fn has_property_on_prototype(
}
/// Drop the resources held by reserved slots of a global object
pub unsafe fn finalize_global(obj: *mut JSObject) {
pub(crate) unsafe fn finalize_global(obj: *mut JSObject) {
let protolist = get_proto_or_iface_array(obj);
let list = (*protolist).as_mut_ptr();
for idx in 0..PROTO_OR_IFACE_LENGTH as isize {
@ -422,7 +422,7 @@ pub unsafe fn finalize_global(obj: *mut JSObject) {
}
/// Trace the resources held by reserved slots of a global object
pub unsafe fn trace_global(tracer: *mut JSTracer, obj: *mut JSObject) {
pub(crate) unsafe fn trace_global(tracer: *mut JSTracer, obj: *mut JSObject) {
let array = get_proto_or_iface_array(obj);
for proto in (*array).iter() {
if !proto.is_null() {
@ -436,7 +436,7 @@ pub unsafe fn trace_global(tracer: *mut JSTracer, obj: *mut JSObject) {
}
/// Enumerate lazy properties of a global object.
pub unsafe extern "C" fn enumerate_global(
pub(crate) unsafe extern "C" fn enumerate_global(
cx: *mut JSContext,
obj: RawHandleObject,
_props: RawMutableHandleIdVector,
@ -453,7 +453,7 @@ pub unsafe extern "C" fn enumerate_global(
}
/// Resolve a lazy global property, for interface objects and named constructors.
pub unsafe extern "C" fn resolve_global(
pub(crate) unsafe extern "C" fn resolve_global(
cx: *mut JSContext,
obj: RawHandleObject,
id: RawHandleId,
@ -491,7 +491,7 @@ pub unsafe extern "C" fn resolve_global(
}
/// Deletes the property `id` from `object`.
pub unsafe fn delete_property_by_id(
pub(crate) unsafe fn delete_property_by_id(
cx: *mut JSContext,
object: HandleObject,
id: HandleId,
@ -564,7 +564,7 @@ unsafe fn generic_call<const EXCEPTION_TO_REJECTION: bool>(
}
/// Generic method of IDL interface.
pub unsafe extern "C" fn generic_method<const EXCEPTION_TO_REJECTION: bool>(
pub(crate) unsafe extern "C" fn generic_method<const EXCEPTION_TO_REJECTION: bool>(
cx: *mut JSContext,
argc: libc::c_uint,
vp: *mut JSVal,
@ -573,7 +573,7 @@ pub unsafe extern "C" fn generic_method<const EXCEPTION_TO_REJECTION: bool>(
}
/// Generic getter of IDL interface.
pub unsafe extern "C" fn generic_getter<const EXCEPTION_TO_REJECTION: bool>(
pub(crate) unsafe extern "C" fn generic_getter<const EXCEPTION_TO_REJECTION: bool>(
cx: *mut JSContext,
argc: libc::c_uint,
vp: *mut JSVal,
@ -582,7 +582,7 @@ pub unsafe extern "C" fn generic_getter<const EXCEPTION_TO_REJECTION: bool>(
}
/// Generic lenient getter of IDL interface.
pub unsafe extern "C" fn generic_lenient_getter<const EXCEPTION_TO_REJECTION: bool>(
pub(crate) unsafe extern "C" fn generic_lenient_getter<const EXCEPTION_TO_REJECTION: bool>(
cx: *mut JSContext,
argc: libc::c_uint,
vp: *mut JSVal,
@ -606,7 +606,7 @@ unsafe extern "C" fn call_setter(
}
/// Generic setter of IDL interface.
pub unsafe extern "C" fn generic_setter(
pub(crate) unsafe extern "C" fn generic_setter(
cx: *mut JSContext,
argc: libc::c_uint,
vp: *mut JSVal,
@ -615,7 +615,7 @@ pub unsafe extern "C" fn generic_setter(
}
/// Generic lenient setter of IDL interface.
pub unsafe extern "C" fn generic_lenient_setter(
pub(crate) unsafe extern "C" fn generic_lenient_setter(
cx: *mut JSContext,
argc: libc::c_uint,
vp: *mut JSVal,
@ -634,12 +634,12 @@ unsafe extern "C" fn instance_class_has_proto_at_depth(
}
#[allow(missing_docs)] // FIXME
pub const DOM_CALLBACKS: DOMCallbacks = DOMCallbacks {
pub(crate) const DOM_CALLBACKS: DOMCallbacks = DOMCallbacks {
instanceClassMatchesProto: Some(instance_class_has_proto_at_depth),
};
// Generic method for returning libc::c_void from caller
pub trait AsVoidPtr {
pub(crate) trait AsVoidPtr {
fn as_void_ptr(&self) -> *const libc::c_void;
}
impl<T> AsVoidPtr for T {
@ -649,7 +649,7 @@ impl<T> AsVoidPtr for T {
}
// Generic method for returning c_char from caller
pub trait AsCCharPtrPtr {
pub(crate) trait AsCCharPtrPtr {
fn as_c_char_ptr(&self) -> *const c_char;
}
@ -660,7 +660,7 @@ impl AsCCharPtrPtr for [u8] {
}
/// <https://searchfox.org/mozilla-central/rev/7279a1df13a819be254fd4649e07c4ff93e4bd45/dom/bindings/BindingUtils.cpp#3300>
pub unsafe extern "C" fn generic_static_promise_method(
pub(crate) unsafe extern "C" fn generic_static_promise_method(
cx: *mut JSContext,
argc: libc::c_uint,
vp: *mut JSVal,
@ -681,7 +681,7 @@ pub unsafe extern "C" fn generic_static_promise_method(
/// Coverts exception to promise rejection
///
/// <https://searchfox.org/mozilla-central/rev/b220e40ff2ee3d10ce68e07d8a8a577d5558e2a2/dom/bindings/BindingUtils.cpp#3315>
pub unsafe fn exception_to_promise(cx: *mut JSContext, rval: RawMutableHandleValue) -> bool {
pub(crate) unsafe fn exception_to_promise(cx: *mut JSContext, rval: RawMutableHandleValue) -> bool {
rooted!(in(cx) let mut exception = UndefinedValue());
if !JS_GetPendingException(cx, exception.handle_mut()) {
return false;

View file

@ -30,27 +30,27 @@ use crate::dom::bindings::trace::JSTraceable;
/// stored for weak-referenceable bindings. We use slot 1 for holding it,
/// this is unsafe for globals, we disallow weak-referenceable globals
/// directly in codegen.
pub const DOM_WEAK_SLOT: u32 = 1;
pub(crate) const DOM_WEAK_SLOT: u32 = 1;
/// A weak reference to a JS-managed DOM object.
#[allow(crown::unrooted_must_root)]
#[crown::unrooted_must_root_lint::allow_unrooted_interior]
pub struct WeakRef<T: WeakReferenceable> {
pub(crate) struct WeakRef<T: WeakReferenceable> {
ptr: ptr::NonNull<WeakBox<T>>,
}
/// The inner box of weak references, public for the finalization in codegen.
#[crown::unrooted_must_root_lint::must_root]
pub struct WeakBox<T: WeakReferenceable> {
pub(crate) struct WeakBox<T: WeakReferenceable> {
/// The reference count. When it reaches zero, the `value` field should
/// have already been set to `None`. The pointee contributes one to the count.
pub count: Cell<usize>,
pub(crate) count: Cell<usize>,
/// The pointer to the JS-managed object, set to None when it is collected.
pub value: Cell<Option<ptr::NonNull<T>>>,
pub(crate) value: Cell<Option<ptr::NonNull<T>>>,
}
/// Trait implemented by weak-referenceable interfaces.
pub trait WeakReferenceable: DomObject + Sized {
pub(crate) trait WeakReferenceable: DomObject + Sized {
/// Downgrade a DOM object reference to a weak one.
fn downgrade(&self) -> WeakRef<Self> {
unsafe {
@ -87,12 +87,12 @@ impl<T: WeakReferenceable> WeakRef<T> {
/// Create a new weak reference from a `WeakReferenceable` interface instance.
/// This is just a convenience wrapper around `<T as WeakReferenceable>::downgrade`
/// to not have to import `WeakReferenceable`.
pub fn new(value: &T) -> Self {
pub(crate) fn new(value: &T) -> Self {
value.downgrade()
}
/// DomRoot a weak reference. Returns `None` if the object was already collected.
pub fn root(&self) -> Option<DomRoot<T>> {
pub(crate) fn root(&self) -> Option<DomRoot<T>> {
unsafe { &*self.ptr.as_ptr() }
.value
.get()
@ -100,7 +100,7 @@ impl<T: WeakReferenceable> WeakRef<T> {
}
/// Return whether the weakly-referenced object is still alive.
pub fn is_alive(&self) -> bool {
pub(crate) fn is_alive(&self) -> bool {
unsafe { &*self.ptr.as_ptr() }.value.get().is_some()
}
}
@ -169,20 +169,20 @@ impl<T: WeakReferenceable> Drop for WeakRef<T> {
/// A mutable weak reference to a JS-managed DOM object. On tracing,
/// the contained weak reference is dropped if the pointee was already
/// collected.
pub struct MutableWeakRef<T: WeakReferenceable> {
pub(crate) struct MutableWeakRef<T: WeakReferenceable> {
cell: UnsafeCell<Option<WeakRef<T>>>,
}
impl<T: WeakReferenceable> MutableWeakRef<T> {
/// Create a new mutable weak reference.
pub fn new(value: Option<&T>) -> MutableWeakRef<T> {
pub(crate) fn new(value: Option<&T>) -> MutableWeakRef<T> {
MutableWeakRef {
cell: UnsafeCell::new(value.map(WeakRef::new)),
}
}
/// Set the pointee of a mutable weak reference.
pub fn set(&self, value: Option<&T>) {
pub(crate) fn set(&self, value: Option<&T>) {
unsafe {
*self.cell.get() = value.map(WeakRef::new);
}
@ -190,7 +190,7 @@ impl<T: WeakReferenceable> MutableWeakRef<T> {
/// DomRoot a mutable weak reference. Returns `None` if the object
/// was already collected.
pub fn root(&self) -> Option<DomRoot<T>> {
pub(crate) fn root(&self) -> Option<DomRoot<T>> {
unsafe { &*self.cell.get() }
.as_ref()
.and_then(WeakRef::root)
@ -220,19 +220,19 @@ unsafe impl<T: WeakReferenceable> JSTraceable for MutableWeakRef<T> {
/// only references which still point to live objects.
#[crown::unrooted_must_root_lint::allow_unrooted_interior]
#[derive(MallocSizeOf)]
pub struct WeakRefVec<T: WeakReferenceable> {
pub(crate) struct WeakRefVec<T: WeakReferenceable> {
vec: Vec<WeakRef<T>>,
}
impl<T: WeakReferenceable> WeakRefVec<T> {
/// Create a new vector of weak references.
pub fn new() -> Self {
pub(crate) fn new() -> Self {
WeakRefVec { vec: vec![] }
}
/// Calls a function on each reference which still points to a
/// live object. The order of the references isn't preserved.
pub fn update<F: FnMut(WeakRefEntry<T>)>(&mut self, mut f: F) {
pub(crate) fn update<F: FnMut(WeakRefEntry<T>)>(&mut self, mut f: F) {
let mut i = 0;
while i < self.vec.len() {
if self.vec[i].is_alive() {
@ -247,7 +247,7 @@ impl<T: WeakReferenceable> WeakRefVec<T> {
}
/// Clears the vector of its dead references.
pub fn retain_alive(&mut self) {
pub(crate) fn retain_alive(&mut self) {
self.update(|_| ());
}
}
@ -269,14 +269,14 @@ impl<T: WeakReferenceable> DerefMut for WeakRefVec<T> {
/// An entry of a vector of weak references. Passed to the closure
/// given to `WeakRefVec::update`.
#[crown::unrooted_must_root_lint::allow_unrooted_interior]
pub struct WeakRefEntry<'a, T: WeakReferenceable> {
pub(crate) struct WeakRefEntry<'a, T: WeakReferenceable> {
vec: &'a mut WeakRefVec<T>,
index: &'a mut usize,
}
impl<'a, T: WeakReferenceable + 'a> WeakRefEntry<'a, T> {
/// Remove the entry from the underlying vector of weak references.
pub fn remove(self) -> WeakRef<T> {
pub(crate) fn remove(self) -> WeakRef<T> {
let ref_ = self.vec.swap_remove(*self.index);
mem::forget(self);
ref_
@ -298,22 +298,22 @@ impl<'a, T: WeakReferenceable + 'a> Drop for WeakRefEntry<'a, T> {
}
#[derive(MallocSizeOf)]
pub struct DOMTracker<T: WeakReferenceable> {
pub(crate) struct DOMTracker<T: WeakReferenceable> {
dom_objects: DomRefCell<WeakRefVec<T>>,
}
impl<T: WeakReferenceable> DOMTracker<T> {
pub fn new() -> Self {
pub(crate) fn new() -> Self {
Self {
dom_objects: DomRefCell::new(WeakRefVec::new()),
}
}
pub fn track(&self, dom_object: &T) {
pub(crate) fn track(&self, dom_object: &T) {
self.dom_objects.borrow_mut().push(WeakRef::new(dom_object));
}
pub fn for_each<F: FnMut(DomRoot<T>)>(&self, mut f: F) {
pub(crate) fn for_each<F: FnMut(DomRoot<T>)>(&self, mut f: F) {
self.dom_objects.borrow_mut().update(|weak_ref| {
let root = weak_ref.root().unwrap();
f(root);

View file

@ -10,7 +10,7 @@ use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
use crate::dom::bindings::str::DOMString;
/// Validate a qualified name. See <https://dom.spec.whatwg.org/#validate> for details.
pub fn validate_qualified_name(qualified_name: &str) -> ErrorResult {
pub(crate) fn validate_qualified_name(qualified_name: &str) -> ErrorResult {
// Step 2.
match xml_name_type(qualified_name) {
XMLName::Invalid => Err(Error::InvalidCharacter),
@ -21,7 +21,7 @@ pub fn validate_qualified_name(qualified_name: &str) -> ErrorResult {
/// Validate a namespace and qualified name and extract their parts.
/// See <https://dom.spec.whatwg.org/#validate-and-extract> for details.
pub fn validate_and_extract(
pub(crate) fn validate_and_extract(
namespace: Option<DOMString>,
qualified_name: &str,
) -> Fallible<(Namespace, Option<Prefix>, LocalName)> {
@ -80,7 +80,7 @@ pub fn validate_and_extract(
/// Results of `xml_name_type`.
#[derive(PartialEq)]
#[allow(missing_docs)]
pub enum XMLName {
pub(crate) enum XMLName {
QName,
Name,
Invalid,
@ -88,7 +88,7 @@ pub enum XMLName {
/// Check if an element name is valid. See <http://www.w3.org/TR/xml/#NT-Name>
/// for details.
pub fn xml_name_type(name: &str) -> XMLName {
pub(crate) fn xml_name_type(name: &str) -> XMLName {
fn is_valid_start(c: char) -> bool {
matches!(c, ':' |
'A'..='Z' |
@ -163,7 +163,7 @@ pub fn xml_name_type(name: &str) -> XMLName {
/// Convert a possibly-null URL to a namespace.
///
/// If the URL is None, returns the empty namespace.
pub fn namespace_from_domstring(url: Option<DOMString>) -> Namespace {
pub(crate) fn namespace_from_domstring(url: Option<DOMString>) -> Namespace {
match url {
None => ns!(),
Some(s) => Namespace::from(s),

View file

@ -31,7 +31,7 @@ use crate::dom::window::Window;
use crate::script_runtime::CanGc;
#[dom_struct]
pub struct BiquadFilterNode {
pub(crate) struct BiquadFilterNode {
node: AudioNode,
gain: Dom<AudioParam>,
frequency: Dom<AudioParam>,
@ -42,7 +42,7 @@ pub struct BiquadFilterNode {
impl BiquadFilterNode {
#[allow(crown::unrooted_must_root)]
pub fn new_inherited(
pub(crate) fn new_inherited(
window: &Window,
context: &BaseAudioContext,
options: &BiquadFilterOptions,
@ -114,7 +114,7 @@ impl BiquadFilterNode {
})
}
pub fn new(
pub(crate) fn new(
window: &Window,
context: &BaseAudioContext,
options: &BiquadFilterOptions,

View file

@ -32,14 +32,14 @@ use crate::script_runtime::CanGc;
// https://w3c.github.io/FileAPI/#blob
#[dom_struct]
pub struct Blob {
pub(crate) struct Blob {
reflector_: Reflector,
#[no_trace]
blob_id: BlobId,
}
impl Blob {
pub fn new(global: &GlobalScope, blob_impl: BlobImpl, can_gc: CanGc) -> DomRoot<Blob> {
pub(crate) fn new(global: &GlobalScope, blob_impl: BlobImpl, can_gc: CanGc) -> DomRoot<Blob> {
Self::new_with_proto(global, None, blob_impl, can_gc)
}
@ -60,7 +60,7 @@ impl Blob {
}
#[allow(crown::unrooted_must_root)]
pub fn new_inherited(blob_impl: &BlobImpl) -> Blob {
pub(crate) fn new_inherited(blob_impl: &BlobImpl) -> Blob {
Blob {
reflector_: Reflector::new(),
blob_id: blob_impl.blob_id(),
@ -68,23 +68,23 @@ impl Blob {
}
/// Get a slice to inner data, this might incur synchronous read and caching
pub fn get_bytes(&self) -> Result<Vec<u8>, ()> {
pub(crate) fn get_bytes(&self) -> Result<Vec<u8>, ()> {
self.global().get_blob_bytes(&self.blob_id)
}
/// Get a copy of the type_string
pub fn type_string(&self) -> String {
pub(crate) fn type_string(&self) -> String {
self.global().get_blob_type_string(&self.blob_id)
}
/// Get a FileID representing the Blob content,
/// used by URL.createObjectURL
pub fn get_blob_url_id(&self) -> Uuid {
pub(crate) fn get_blob_url_id(&self) -> Uuid {
self.global().get_blob_url_id(&self.blob_id)
}
/// <https://w3c.github.io/FileAPI/#blob-get-stream>
pub fn get_stream(&self, can_gc: CanGc) -> Fallible<DomRoot<ReadableStream>> {
pub(crate) fn get_stream(&self, can_gc: CanGc) -> Fallible<DomRoot<ReadableStream>> {
self.global().get_blob_stream(&self.blob_id, can_gc)
}
}
@ -162,7 +162,7 @@ impl Serializable for Blob {
/// Extract bytes from BlobParts, used by Blob and File constructor
/// <https://w3c.github.io/FileAPI/#constructorBlob>
#[allow(unsafe_code)]
pub fn blob_parts_to_bytes(
pub(crate) fn blob_parts_to_bytes(
mut blobparts: Vec<ArrayBufferOrArrayBufferViewOrBlobOrString>,
) -> Result<Vec<u8>, ()> {
let mut ret = vec![];
@ -302,7 +302,7 @@ impl BlobMethods<crate::DomTypeHolder> for Blob {
/// XXX: We will relax the restriction here,
/// since the spec has some problem over this part.
/// see <https://github.com/w3c/FileAPI/issues/43>
pub fn normalize_type_string(s: &str) -> String {
pub(crate) fn normalize_type_string(s: &str) -> String {
if is_ascii_printable(s) {
s.to_ascii_lowercase()
// match s_lower.parse() as Result<Mime, ()> {

View file

@ -66,24 +66,24 @@ const BT_DESC_CONVERSION_ERROR: &str =
#[derive(JSTraceable, MallocSizeOf)]
#[allow(non_snake_case)]
pub struct AllowedBluetoothDevice {
pub deviceId: DOMString,
pub mayUseGATT: bool,
pub(crate) struct AllowedBluetoothDevice {
pub(crate) deviceId: DOMString,
pub(crate) mayUseGATT: bool,
}
#[derive(JSTraceable, MallocSizeOf)]
pub struct BluetoothExtraPermissionData {
pub(crate) struct BluetoothExtraPermissionData {
allowed_devices: DomRefCell<Vec<AllowedBluetoothDevice>>,
}
impl BluetoothExtraPermissionData {
pub fn new() -> BluetoothExtraPermissionData {
pub(crate) fn new() -> BluetoothExtraPermissionData {
BluetoothExtraPermissionData {
allowed_devices: DomRefCell::new(Vec::new()),
}
}
pub fn add_new_allowed_device(&self, allowed_device: AllowedBluetoothDevice) {
pub(crate) fn add_new_allowed_device(&self, allowed_device: AllowedBluetoothDevice) {
self.allowed_devices.borrow_mut().push(allowed_device);
}
@ -91,7 +91,7 @@ impl BluetoothExtraPermissionData {
self.allowed_devices.borrow()
}
pub fn allowed_devices_contains_id(&self, id: DOMString) -> bool {
pub(crate) fn allowed_devices_contains_id(&self, id: DOMString) -> bool {
self.allowed_devices
.borrow()
.iter()
@ -110,7 +110,7 @@ struct BluetoothContext<T: AsyncBluetoothListener + DomObject> {
receiver: Trusted<T>,
}
pub trait AsyncBluetoothListener {
pub(crate) trait AsyncBluetoothListener {
fn handle_response(&self, result: BluetoothResponse, promise: &Rc<Promise>, can_gc: CanGc);
}
@ -138,20 +138,20 @@ where
// https://webbluetoothcg.github.io/web-bluetooth/#bluetooth
#[dom_struct]
pub struct Bluetooth {
pub(crate) struct Bluetooth {
eventtarget: EventTarget,
device_instance_map: DomRefCell<HashMap<String, Dom<BluetoothDevice>>>,
}
impl Bluetooth {
pub fn new_inherited() -> Bluetooth {
pub(crate) fn new_inherited() -> Bluetooth {
Bluetooth {
eventtarget: EventTarget::new_inherited(),
device_instance_map: DomRefCell::new(HashMap::new()),
}
}
pub fn new(global: &GlobalScope) -> DomRoot<Bluetooth> {
pub(crate) fn new(global: &GlobalScope) -> DomRoot<Bluetooth> {
reflect_dom_object(Box::new(Bluetooth::new_inherited()), global, CanGc::note())
}
@ -159,7 +159,7 @@ impl Bluetooth {
self.global().as_window().bluetooth_thread()
}
pub fn get_device_map(&self) -> &DomRefCell<HashMap<String, Dom<BluetoothDevice>>> {
pub(crate) fn get_device_map(&self) -> &DomRefCell<HashMap<String, Dom<BluetoothDevice>>> {
&self.device_instance_map
}
@ -239,7 +239,7 @@ impl Bluetooth {
}
}
pub fn response_async<T: AsyncBluetoothListener + DomObject + 'static>(
pub(crate) fn response_async<T: AsyncBluetoothListener + DomObject + 'static>(
promise: &Rc<Promise>,
receiver: &T,
) -> IpcSender<BluetoothResponseResult> {
@ -284,7 +284,7 @@ pub fn response_async<T: AsyncBluetoothListener + DomObject + 'static>(
// https://webbluetoothcg.github.io/web-bluetooth/#getgattchildren
#[allow(clippy::too_many_arguments)]
pub fn get_gatt_children<T, F>(
pub(crate) fn get_gatt_children<T, F>(
attribute: &T,
single: bool,
uuid_canonicalizer: F,

View file

@ -23,7 +23,7 @@ use crate::script_runtime::CanGc;
// https://webbluetoothcg.github.io/web-bluetooth/#bluetoothadvertisingevent
#[dom_struct]
pub struct BluetoothAdvertisingEvent {
pub(crate) struct BluetoothAdvertisingEvent {
event: Event,
device: Dom<BluetoothDevice>,
name: Option<DOMString>,
@ -34,7 +34,7 @@ pub struct BluetoothAdvertisingEvent {
#[allow(non_snake_case)]
impl BluetoothAdvertisingEvent {
pub fn new_inherited(
pub(crate) fn new_inherited(
device: &BluetoothDevice,
name: Option<DOMString>,
appearance: Option<u16>,

View file

@ -12,7 +12,7 @@ use crate::script_runtime::CanGc;
// https://webbluetoothcg.github.io/web-bluetooth/#characteristicproperties
#[dom_struct]
pub struct BluetoothCharacteristicProperties {
pub(crate) struct BluetoothCharacteristicProperties {
reflector_: Reflector,
broadcast: bool,
read: bool,
@ -28,7 +28,7 @@ pub struct BluetoothCharacteristicProperties {
#[allow(non_snake_case)]
impl BluetoothCharacteristicProperties {
#[allow(clippy::too_many_arguments)]
pub fn new_inherited(
pub(crate) fn new_inherited(
broadcast: bool,
read: bool,
write_without_response: bool,
@ -54,7 +54,7 @@ impl BluetoothCharacteristicProperties {
}
#[allow(clippy::too_many_arguments)]
pub fn new(
pub(crate) fn new(
global: &GlobalScope,
broadcast: bool,
read: bool,

View file

@ -45,7 +45,7 @@ struct AttributeInstanceMap {
// https://webbluetoothcg.github.io/web-bluetooth/#bluetoothdevice
#[dom_struct]
pub struct BluetoothDevice {
pub(crate) struct BluetoothDevice {
eventtarget: EventTarget,
id: DOMString,
name: Option<DOMString>,
@ -56,7 +56,7 @@ pub struct BluetoothDevice {
}
impl BluetoothDevice {
pub fn new_inherited(
pub(crate) fn new_inherited(
id: DOMString,
name: Option<DOMString>,
context: &Bluetooth,
@ -76,7 +76,7 @@ impl BluetoothDevice {
}
}
pub fn new(
pub(crate) fn new(
global: &GlobalScope,
id: DOMString,
name: Option<DOMString>,
@ -89,7 +89,7 @@ impl BluetoothDevice {
)
}
pub fn get_gatt(&self) -> DomRoot<BluetoothRemoteGATTServer> {
pub(crate) fn get_gatt(&self) -> DomRoot<BluetoothRemoteGATTServer> {
self.gatt
.or_init(|| BluetoothRemoteGATTServer::new(&self.global(), self))
}
@ -98,7 +98,7 @@ impl BluetoothDevice {
DomRoot::from_ref(&self.context)
}
pub fn get_or_create_service(
pub(crate) fn get_or_create_service(
&self,
service: &BluetoothServiceMsg,
server: &BluetoothRemoteGATTServer,
@ -119,7 +119,7 @@ impl BluetoothDevice {
bt_service
}
pub fn get_or_create_characteristic(
pub(crate) fn get_or_create_characteristic(
&self,
characteristic: &BluetoothCharacteristicMsg,
service: &BluetoothRemoteGATTService,
@ -155,7 +155,7 @@ impl BluetoothDevice {
bt_characteristic
}
pub fn is_represented_device_null(&self) -> bool {
pub(crate) fn is_represented_device_null(&self) -> bool {
let (sender, receiver) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap();
self.get_bluetooth_thread()
.send(BluetoothRequest::IsRepresentedDeviceNull(
@ -166,7 +166,7 @@ impl BluetoothDevice {
receiver.recv().unwrap()
}
pub fn get_or_create_descriptor(
pub(crate) fn get_or_create_descriptor(
&self,
descriptor: &BluetoothDescriptorMsg,
characteristic: &BluetoothRemoteGATTCharacteristic,
@ -195,7 +195,7 @@ impl BluetoothDevice {
// https://webbluetoothcg.github.io/web-bluetooth/#clean-up-the-disconnected-device
#[allow(crown::unrooted_must_root)]
pub fn clean_up_disconnected_device(&self, can_gc: CanGc) {
pub(crate) fn clean_up_disconnected_device(&self, can_gc: CanGc) {
// Step 1.
self.get_gatt().set_connected(false);
@ -231,7 +231,7 @@ impl BluetoothDevice {
// https://webbluetoothcg.github.io/web-bluetooth/#garbage-collect-the-connection
#[allow(crown::unrooted_must_root)]
pub fn garbage_collect_the_connection(&self) -> ErrorResult {
pub(crate) fn garbage_collect_the_connection(&self) -> ErrorResult {
// Step 1: TODO: Check if other systems using this device.
// Step 2.

View file

@ -29,7 +29,7 @@ use crate::script_runtime::CanGc;
// https://webbluetoothcg.github.io/web-bluetooth/#bluetoothpermissionresult
#[dom_struct]
pub struct BluetoothPermissionResult {
pub(crate) struct BluetoothPermissionResult {
status: PermissionStatus,
devices: DomRefCell<Vec<Dom<BluetoothDevice>>>,
}
@ -45,7 +45,7 @@ impl BluetoothPermissionResult {
result
}
pub fn new(
pub(crate) fn new(
global: &GlobalScope,
status: &PermissionStatus,
) -> DomRoot<BluetoothPermissionResult> {
@ -56,28 +56,28 @@ impl BluetoothPermissionResult {
)
}
pub fn get_bluetooth(&self) -> DomRoot<Bluetooth> {
pub(crate) fn get_bluetooth(&self) -> DomRoot<Bluetooth> {
self.global().as_window().Navigator().Bluetooth()
}
pub fn get_bluetooth_thread(&self) -> IpcSender<BluetoothRequest> {
pub(crate) fn get_bluetooth_thread(&self) -> IpcSender<BluetoothRequest> {
self.global().as_window().bluetooth_thread()
}
pub fn get_query(&self) -> PermissionName {
pub(crate) fn get_query(&self) -> PermissionName {
self.status.get_query()
}
pub fn set_state(&self, state: PermissionState) {
pub(crate) fn set_state(&self, state: PermissionState) {
self.status.set_state(state)
}
pub fn get_state(&self) -> PermissionState {
pub(crate) fn get_state(&self) -> PermissionState {
self.status.State()
}
#[allow(crown::unrooted_must_root)]
pub fn set_devices(&self, devices: Vec<Dom<BluetoothDevice>>) {
pub(crate) fn set_devices(&self, devices: Vec<Dom<BluetoothDevice>>) {
*self.devices.borrow_mut() = devices;
}
}

View file

@ -34,11 +34,11 @@ use crate::script_runtime::CanGc;
// Maximum length of an attribute value.
// https://www.bluetooth.org/DocMan/handlers/DownloadDoc.ashx?doc_id=286439 (Vol. 3, page 2169)
pub const MAXIMUM_ATTRIBUTE_LENGTH: usize = 512;
pub(crate) const MAXIMUM_ATTRIBUTE_LENGTH: usize = 512;
// https://webbluetoothcg.github.io/web-bluetooth/#bluetoothremotegattcharacteristic
#[dom_struct]
pub struct BluetoothRemoteGATTCharacteristic {
pub(crate) struct BluetoothRemoteGATTCharacteristic {
eventtarget: EventTarget,
service: Dom<BluetoothRemoteGATTService>,
uuid: DOMString,
@ -48,7 +48,7 @@ pub struct BluetoothRemoteGATTCharacteristic {
}
impl BluetoothRemoteGATTCharacteristic {
pub fn new_inherited(
pub(crate) fn new_inherited(
service: &BluetoothRemoteGATTService,
uuid: DOMString,
properties: &BluetoothCharacteristicProperties,
@ -64,7 +64,7 @@ impl BluetoothRemoteGATTCharacteristic {
}
}
pub fn new(
pub(crate) fn new(
global: &GlobalScope,
service: &BluetoothRemoteGATTService,
uuid: DOMString,

View file

@ -30,7 +30,7 @@ use crate::script_runtime::CanGc;
// http://webbluetoothcg.github.io/web-bluetooth/#bluetoothremotegattdescriptor
#[dom_struct]
pub struct BluetoothRemoteGATTDescriptor {
pub(crate) struct BluetoothRemoteGATTDescriptor {
reflector_: Reflector,
characteristic: Dom<BluetoothRemoteGATTCharacteristic>,
uuid: DOMString,
@ -39,7 +39,7 @@ pub struct BluetoothRemoteGATTDescriptor {
}
impl BluetoothRemoteGATTDescriptor {
pub fn new_inherited(
pub(crate) fn new_inherited(
characteristic: &BluetoothRemoteGATTCharacteristic,
uuid: DOMString,
instance_id: String,
@ -53,7 +53,7 @@ impl BluetoothRemoteGATTDescriptor {
}
}
pub fn new(
pub(crate) fn new(
global: &GlobalScope,
characteristic: &BluetoothRemoteGATTCharacteristic,
uuid: DOMString,

View file

@ -24,14 +24,14 @@ use crate::script_runtime::CanGc;
// https://webbluetoothcg.github.io/web-bluetooth/#bluetoothremotegattserver
#[dom_struct]
pub struct BluetoothRemoteGATTServer {
pub(crate) struct BluetoothRemoteGATTServer {
reflector_: Reflector,
device: Dom<BluetoothDevice>,
connected: Cell<bool>,
}
impl BluetoothRemoteGATTServer {
pub fn new_inherited(device: &BluetoothDevice) -> BluetoothRemoteGATTServer {
pub(crate) fn new_inherited(device: &BluetoothDevice) -> BluetoothRemoteGATTServer {
BluetoothRemoteGATTServer {
reflector_: Reflector::new(),
device: Dom::from_ref(device),
@ -39,7 +39,7 @@ impl BluetoothRemoteGATTServer {
}
}
pub fn new(
pub(crate) fn new(
global: &GlobalScope,
device: &BluetoothDevice,
) -> DomRoot<BluetoothRemoteGATTServer> {
@ -54,7 +54,7 @@ impl BluetoothRemoteGATTServer {
self.global().as_window().bluetooth_thread()
}
pub fn set_connected(&self, connected: bool) {
pub(crate) fn set_connected(&self, connected: bool) {
self.connected.set(connected);
}
}

View file

@ -23,7 +23,7 @@ use crate::script_runtime::CanGc;
// https://webbluetoothcg.github.io/web-bluetooth/#bluetoothremotegattservice
#[dom_struct]
pub struct BluetoothRemoteGATTService {
pub(crate) struct BluetoothRemoteGATTService {
eventtarget: EventTarget,
device: Dom<BluetoothDevice>,
uuid: DOMString,
@ -32,7 +32,7 @@ pub struct BluetoothRemoteGATTService {
}
impl BluetoothRemoteGATTService {
pub fn new_inherited(
pub(crate) fn new_inherited(
device: &BluetoothDevice,
uuid: DOMString,
is_primary: bool,
@ -48,7 +48,7 @@ impl BluetoothRemoteGATTService {
}
#[allow(non_snake_case)]
pub fn new(
pub(crate) fn new(
global: &GlobalScope,
device: &BluetoothDevice,
uuid: DOMString,

View file

@ -14,14 +14,14 @@ use crate::dom::bindings::str::DOMString;
use crate::dom::window::Window;
#[allow(clippy::upper_case_acronyms)]
pub type UUID = DOMString;
pub type BluetoothServiceUUID = StringOrUnsignedLong;
pub type BluetoothCharacteristicUUID = StringOrUnsignedLong;
pub type BluetoothDescriptorUUID = StringOrUnsignedLong;
pub(crate) type UUID = DOMString;
pub(crate) type BluetoothServiceUUID = StringOrUnsignedLong;
pub(crate) type BluetoothCharacteristicUUID = StringOrUnsignedLong;
pub(crate) type BluetoothDescriptorUUID = StringOrUnsignedLong;
// https://webbluetoothcg.github.io/web-bluetooth/#bluetoothuuid
#[dom_struct]
pub struct BluetoothUUID {
pub(crate) struct BluetoothUUID {
reflector_: Reflector,
}
@ -607,11 +607,11 @@ impl BluetoothUUIDMethods<crate::DomTypeHolder> for BluetoothUUID {
}
impl BluetoothUUID {
pub fn service(name: BluetoothServiceUUID) -> Fallible<UUID> {
pub(crate) fn service(name: BluetoothServiceUUID) -> Fallible<UUID> {
resolve_uuid_name(name, BLUETOOTH_ASSIGNED_SERVICES, SERVICE_PREFIX)
}
pub fn characteristic(name: BluetoothCharacteristicUUID) -> Fallible<UUID> {
pub(crate) fn characteristic(name: BluetoothCharacteristicUUID) -> Fallible<UUID> {
resolve_uuid_name(
name,
BLUETOOTH_ASSIGNED_CHARCTERISTICS,
@ -619,7 +619,7 @@ impl BluetoothUUID {
)
}
pub fn descriptor(name: BluetoothDescriptorUUID) -> Fallible<UUID> {
pub(crate) fn descriptor(name: BluetoothDescriptorUUID) -> Fallible<UUID> {
resolve_uuid_name(name, BLUETOOTH_ASSIGNED_DESCRIPTORS, DESCRIPTOR_PREFIX)
}
}

View file

@ -20,7 +20,7 @@ use crate::dom::globalscope::GlobalScope;
use crate::script_runtime::{CanGc, JSContext as SafeJSContext};
#[dom_struct]
pub struct BroadcastChannel {
pub(crate) struct BroadcastChannel {
eventtarget: EventTarget,
name: DOMString,
closed: Cell<bool>,
@ -45,7 +45,7 @@ impl BroadcastChannel {
channel
}
pub fn new_inherited(name: DOMString) -> BroadcastChannel {
pub(crate) fn new_inherited(name: DOMString) -> BroadcastChannel {
BroadcastChannel {
eventtarget: EventTarget::new_inherited(),
name,
@ -56,12 +56,12 @@ impl BroadcastChannel {
/// The unique Id of this channel.
/// Used for filtering out the sender from the local broadcast.
pub fn id(&self) -> &Uuid {
pub(crate) fn id(&self) -> &Uuid {
&self.id
}
/// Is this channel closed?
pub fn closed(&self) -> bool {
pub(crate) fn closed(&self) -> bool {
self.closed.get()
}
}

View file

@ -22,20 +22,20 @@ use crate::native_fn;
use crate::script_runtime::CanGc;
#[dom_struct]
pub struct ByteLengthQueuingStrategy {
pub(crate) struct ByteLengthQueuingStrategy {
reflector_: Reflector,
high_water_mark: f64,
}
impl ByteLengthQueuingStrategy {
pub fn new_inherited(init: f64) -> Self {
pub(crate) fn new_inherited(init: f64) -> Self {
Self {
reflector_: Reflector::new(),
high_water_mark: init,
}
}
pub fn new(
pub(crate) fn new(
global: &GlobalScope,
proto: Option<HandleObject>,
init: f64,
@ -85,7 +85,7 @@ impl ByteLengthQueuingStrategyMethods<crate::DomTypeHolder> for ByteLengthQueuin
/// <https://streams.spec.whatwg.org/#byte-length-queuing-strategy-size-function>
#[allow(unsafe_code)]
pub unsafe fn byte_length_queuing_strategy_size(
pub(crate) unsafe fn byte_length_queuing_strategy_size(
cx: *mut JSContext,
argc: u32,
vp: *mut JSVal,

View file

@ -20,7 +20,7 @@ use crate::script_runtime::CanGc;
// https://html.spec.whatwg.org/multipage/#canvasgradient
#[dom_struct]
pub struct CanvasGradient {
pub(crate) struct CanvasGradient {
reflector_: Reflector,
style: CanvasGradientStyle,
#[no_trace]
@ -28,7 +28,7 @@ pub struct CanvasGradient {
}
#[derive(Clone, JSTraceable, MallocSizeOf)]
pub enum CanvasGradientStyle {
pub(crate) enum CanvasGradientStyle {
Linear(#[no_trace] LinearGradientStyle),
Radial(#[no_trace] RadialGradientStyle),
}
@ -42,7 +42,7 @@ impl CanvasGradient {
}
}
pub fn new(global: &GlobalScope, style: CanvasGradientStyle) -> DomRoot<CanvasGradient> {
pub(crate) fn new(global: &GlobalScope, style: CanvasGradientStyle) -> DomRoot<CanvasGradient> {
reflect_dom_object(
Box::new(CanvasGradient::new_inherited(style)),
global,
@ -71,7 +71,7 @@ impl CanvasGradientMethods<crate::DomTypeHolder> for CanvasGradient {
}
}
pub trait ToFillOrStrokeStyle {
pub(crate) trait ToFillOrStrokeStyle {
fn to_fill_or_stroke_style(self) -> FillOrStrokeStyle;
}

View file

@ -14,7 +14,7 @@ use crate::script_runtime::CanGc;
// https://html.spec.whatwg.org/multipage/#canvaspattern
#[dom_struct]
pub struct CanvasPattern {
pub(crate) struct CanvasPattern {
reflector_: Reflector,
surface_data: Vec<u8>,
#[no_trace]
@ -47,7 +47,7 @@ impl CanvasPattern {
origin_clean,
}
}
pub fn new(
pub(crate) fn new(
global: &GlobalScope,
surface_data: Vec<u8>,
surface_size: Size2D<u32>,
@ -65,7 +65,7 @@ impl CanvasPattern {
CanGc::note(),
)
}
pub fn origin_is_clean(&self) -> bool {
pub(crate) fn origin_is_clean(&self) -> bool {
self.origin_clean
}
}

View file

@ -30,7 +30,7 @@ use crate::script_runtime::CanGc;
// https://html.spec.whatwg.org/multipage/#canvasrenderingcontext2d
#[dom_struct]
pub struct CanvasRenderingContext2D {
pub(crate) struct CanvasRenderingContext2D {
reflector_: Reflector,
/// For rendering contexts created by an HTML canvas element, this is Some,
/// for ones created by a paint worklet, this is None.
@ -39,7 +39,7 @@ pub struct CanvasRenderingContext2D {
}
impl CanvasRenderingContext2D {
pub fn new_inherited(
pub(crate) fn new_inherited(
global: &GlobalScope,
canvas: Option<&HTMLCanvasElement>,
size: Size2D<u32>,
@ -54,7 +54,7 @@ impl CanvasRenderingContext2D {
}
}
pub fn new(
pub(crate) fn new(
global: &GlobalScope,
canvas: &HTMLCanvasElement,
size: Size2D<u32>,
@ -68,7 +68,7 @@ impl CanvasRenderingContext2D {
}
// https://html.spec.whatwg.org/multipage/#concept-canvas-set-bitmap-dimensions
pub fn set_bitmap_dimensions(&self, size: Size2D<u32>) {
pub(crate) fn set_bitmap_dimensions(&self, size: Size2D<u32>) {
self.reset_to_initial_state();
self.canvas_state
.get_ipc_renderer()
@ -84,36 +84,36 @@ impl CanvasRenderingContext2D {
self.canvas_state.reset_to_initial_state();
}
pub fn set_canvas_bitmap_dimensions(&self, size: Size2D<u64>) {
pub(crate) fn set_canvas_bitmap_dimensions(&self, size: Size2D<u64>) {
self.canvas_state.set_bitmap_dimensions(size);
}
pub fn mark_as_dirty(&self) {
pub(crate) fn mark_as_dirty(&self) {
self.canvas_state.mark_as_dirty(self.canvas.as_deref())
}
pub fn take_missing_image_urls(&self) -> Vec<ServoUrl> {
pub(crate) fn take_missing_image_urls(&self) -> Vec<ServoUrl> {
std::mem::take(&mut self.canvas_state.get_missing_image_urls().borrow_mut())
}
pub fn get_canvas_id(&self) -> CanvasId {
pub(crate) fn get_canvas_id(&self) -> CanvasId {
self.canvas_state.get_canvas_id()
}
pub fn send_canvas_2d_msg(&self, msg: Canvas2dMsg) {
pub(crate) fn send_canvas_2d_msg(&self, msg: Canvas2dMsg) {
self.canvas_state.send_canvas_2d_msg(msg)
}
// TODO: Remove this
pub fn get_ipc_renderer(&self) -> IpcSender<CanvasMsg> {
pub(crate) fn get_ipc_renderer(&self) -> IpcSender<CanvasMsg> {
self.canvas_state.get_ipc_renderer().clone()
}
pub fn origin_is_clean(&self) -> bool {
pub(crate) fn origin_is_clean(&self) -> bool {
self.canvas_state.origin_is_clean()
}
pub fn get_rect(&self, rect: Rect<u32>) -> Vec<u8> {
pub(crate) fn get_rect(&self, rect: Rect<u32>) -> Vec<u8> {
let rect = Rect::new(
Point2D::new(rect.origin.x as u64, rect.origin.y as u64),
Size2D::new(rect.size.width as u64, rect.size.height as u64),
@ -127,7 +127,7 @@ impl CanvasRenderingContext2D {
}
}
pub trait LayoutCanvasRenderingContext2DHelpers {
pub(crate) trait LayoutCanvasRenderingContext2DHelpers {
fn get_ipc_renderer(self) -> IpcSender<CanvasMsg>;
fn get_canvas_id(self) -> CanvasId;
}

View file

@ -12,7 +12,7 @@ use crate::dom::text::Text;
use crate::script_runtime::CanGc;
#[dom_struct]
pub struct CDATASection {
pub(crate) struct CDATASection {
text: Text,
}
@ -23,7 +23,11 @@ impl CDATASection {
}
}
pub fn new(text: DOMString, document: &Document, can_gc: CanGc) -> DomRoot<CDATASection> {
pub(crate) fn new(
text: DOMString,
document: &Document,
can_gc: CanGc,
) -> DomRoot<CDATASection> {
Node::reflect_node(
Box::new(CDATASection::new_inherited(text, document)),
document,

View file

@ -22,13 +22,13 @@ use crate::dom::window::Window;
use crate::script_runtime::CanGc;
#[dom_struct]
pub struct ChannelMergerNode {
pub(crate) struct ChannelMergerNode {
node: AudioNode,
}
impl ChannelMergerNode {
#[allow(crown::unrooted_must_root)]
pub fn new_inherited(
pub(crate) fn new_inherited(
_: &Window,
context: &BaseAudioContext,
options: &ChannelMergerOptions,
@ -57,7 +57,7 @@ impl ChannelMergerNode {
Ok(ChannelMergerNode { node })
}
pub fn new(
pub(crate) fn new(
window: &Window,
context: &BaseAudioContext,
options: &ChannelMergerOptions,

View file

@ -21,13 +21,13 @@ use crate::dom::window::Window;
use crate::script_runtime::CanGc;
#[dom_struct]
pub struct ChannelSplitterNode {
pub(crate) struct ChannelSplitterNode {
node: AudioNode,
}
impl ChannelSplitterNode {
#[allow(crown::unrooted_must_root)]
pub fn new_inherited(
pub(crate) fn new_inherited(
_: &Window,
context: &BaseAudioContext,
options: &ChannelSplitterOptions,
@ -59,7 +59,7 @@ impl ChannelSplitterNode {
Ok(ChannelSplitterNode { node })
}
pub fn new(
pub(crate) fn new(
window: &Window,
context: &BaseAudioContext,
options: &ChannelSplitterOptions,

View file

@ -29,20 +29,20 @@ use crate::script_runtime::CanGc;
// https://dom.spec.whatwg.org/#characterdata
#[dom_struct]
pub struct CharacterData {
pub(crate) struct CharacterData {
node: Node,
data: DomRefCell<DOMString>,
}
impl CharacterData {
pub fn new_inherited(data: DOMString, document: &Document) -> CharacterData {
pub(crate) fn new_inherited(data: DOMString, document: &Document) -> CharacterData {
CharacterData {
node: Node::new_inherited(document),
data: DomRefCell::new(data),
}
}
pub fn clone_with_data(
pub(crate) fn clone_with_data(
&self,
data: DOMString,
document: &Document,
@ -72,12 +72,12 @@ impl CharacterData {
}
#[inline]
pub fn data(&self) -> Ref<DOMString> {
pub(crate) fn data(&self) -> Ref<DOMString> {
self.data.borrow()
}
#[inline]
pub fn append_data(&self, data: &str) {
pub(crate) fn append_data(&self, data: &str) {
self.queue_mutation_record();
self.data.borrow_mut().push_str(data);
self.content_changed();
@ -291,7 +291,7 @@ impl CharacterDataMethods<crate::DomTypeHolder> for CharacterData {
}
}
pub trait LayoutCharacterDataHelpers<'dom> {
pub(crate) trait LayoutCharacterDataHelpers<'dom> {
fn data_for_layout(self) -> &'dom str;
}

View file

@ -17,7 +17,7 @@ use crate::dom::window::Window;
use crate::script_runtime::CanGc;
#[dom_struct]
pub struct Client {
pub(crate) struct Client {
reflector_: Reflector,
active_worker: MutNullableDom<ServiceWorker>,
#[no_trace]
@ -39,7 +39,7 @@ impl Client {
}
}
pub fn new(window: &Window) -> DomRoot<Client> {
pub(crate) fn new(window: &Window) -> DomRoot<Client> {
reflect_dom_object(
Box::new(Client::new_inherited(window.get_url())),
window,
@ -47,16 +47,16 @@ impl Client {
)
}
pub fn creation_url(&self) -> ServoUrl {
pub(crate) fn creation_url(&self) -> ServoUrl {
self.url.clone()
}
pub fn get_controller(&self) -> Option<DomRoot<ServiceWorker>> {
pub(crate) fn get_controller(&self) -> Option<DomRoot<ServiceWorker>> {
self.active_worker.get()
}
#[allow(dead_code)]
pub fn set_controller(&self, worker: &ServiceWorker) {
pub(crate) fn set_controller(&self, worker: &ServiceWorker) {
self.active_worker.set(Some(worker));
}
}

View file

@ -19,7 +19,7 @@ use crate::dom::globalscope::GlobalScope;
use crate::script_runtime::CanGc;
#[dom_struct]
pub struct CloseEvent {
pub(crate) struct CloseEvent {
event: Event,
was_clean: bool,
code: u16,
@ -28,7 +28,7 @@ pub struct CloseEvent {
#[allow(non_snake_case)]
impl CloseEvent {
pub fn new_inherited(was_clean: bool, code: u16, reason: DOMString) -> CloseEvent {
pub(crate) fn new_inherited(was_clean: bool, code: u16, reason: DOMString) -> CloseEvent {
CloseEvent {
event: Event::new_inherited(),
was_clean,
@ -38,7 +38,7 @@ impl CloseEvent {
}
#[allow(clippy::too_many_arguments)]
pub fn new(
pub(crate) fn new(
global: &GlobalScope,
type_: Atom,
bubbles: EventBubbles,

View file

@ -18,7 +18,7 @@ use crate::script_runtime::CanGc;
/// An HTML comment.
#[dom_struct]
pub struct Comment {
pub(crate) struct Comment {
characterdata: CharacterData,
}
@ -29,7 +29,7 @@ impl Comment {
}
}
pub fn new(
pub(crate) fn new(
text: DOMString,
document: &Document,
proto: Option<HandleObject>,

View file

@ -18,20 +18,20 @@ use crate::dom::window::Window;
use crate::script_runtime::CanGc;
#[dom_struct]
pub struct CompositionEvent {
pub(crate) struct CompositionEvent {
uievent: UIEvent,
data: DOMString,
}
impl CompositionEvent {
pub fn new_inherited() -> CompositionEvent {
pub(crate) fn new_inherited() -> CompositionEvent {
CompositionEvent {
uievent: UIEvent::new_inherited(),
data: DOMString::new(),
}
}
pub fn new_uninitialized(window: &Window) -> DomRoot<CompositionEvent> {
pub(crate) fn new_uninitialized(window: &Window) -> DomRoot<CompositionEvent> {
reflect_dom_object(
Box::new(CompositionEvent::new_inherited()),
window,
@ -40,7 +40,7 @@ impl CompositionEvent {
}
#[allow(clippy::too_many_arguments)]
pub fn new(
pub(crate) fn new(
window: &Window,
type_: DOMString,
can_bubble: bool,
@ -81,7 +81,7 @@ impl CompositionEvent {
ev
}
pub fn data(&self) -> &str {
pub(crate) fn data(&self) -> &str {
&self.data
}
}

View file

@ -31,7 +31,7 @@ const MAX_LOG_DEPTH: usize = 10;
const MAX_LOG_CHILDREN: usize = 15;
/// <https://developer.mozilla.org/en-US/docs/Web/API/Console>
pub struct Console;
pub(crate) struct Console;
impl Console {
#[allow(unsafe_code)]
@ -86,7 +86,7 @@ impl Console {
}
// Directly logs a DOMString, without processing the message
pub fn internal_warn(global: &GlobalScope, message: DOMString) {
pub(crate) fn internal_warn(global: &GlobalScope, message: DOMString) {
Console::send_string_message(global, LogLevel::Warn, String::from(message.clone()));
console_message(global, message);
}

View file

@ -24,7 +24,7 @@ use crate::dom::window::Window;
use crate::script_runtime::CanGc;
#[dom_struct]
pub struct ConstantSourceNode {
pub(crate) struct ConstantSourceNode {
source_node: AudioScheduledSourceNode,
offset: Dom<AudioParam>,
}
@ -63,7 +63,7 @@ impl ConstantSourceNode {
})
}
pub fn new(
pub(crate) fn new(
window: &Window,
context: &BaseAudioContext,
options: &ConstantSourceOptions,

View file

@ -20,20 +20,20 @@ use crate::script_runtime::CanGc;
use crate::{native_fn, native_raw_obj_fn};
#[dom_struct]
pub struct CountQueuingStrategy {
pub(crate) struct CountQueuingStrategy {
reflector_: Reflector,
high_water_mark: f64,
}
impl CountQueuingStrategy {
pub fn new_inherited(init: f64) -> Self {
pub(crate) fn new_inherited(init: f64) -> Self {
Self {
reflector_: Reflector::new(),
high_water_mark: init,
}
}
pub fn new(
pub(crate) fn new(
global: &GlobalScope,
proto: Option<HandleObject>,
init: f64,
@ -84,7 +84,11 @@ impl CountQueuingStrategyMethods<crate::DomTypeHolder> for CountQueuingStrategy
/// <https://streams.spec.whatwg.org/#count-queuing-strategy-size-function>
#[allow(unsafe_code)]
pub unsafe fn count_queuing_strategy_size(_cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
pub(crate) unsafe fn count_queuing_strategy_size(
_cx: *mut JSContext,
argc: u32,
vp: *mut JSVal,
) -> bool {
let args = CallArgs::from_vp(vp, argc);
// Step 1.1. Return 1.
args.rval().set(Int32Value(1));
@ -95,7 +99,10 @@ pub unsafe fn count_queuing_strategy_size(_cx: *mut JSContext, argc: u32, vp: *m
/// If the high water mark is not set, return the default value.
///
/// <https://streams.spec.whatwg.org/#validate-and-normalize-high-water-mark>
pub fn extract_high_water_mark(strategy: &QueuingStrategy, default_hwm: f64) -> Result<f64, Error> {
pub(crate) fn extract_high_water_mark(
strategy: &QueuingStrategy,
default_hwm: f64,
) -> Result<f64, Error> {
if strategy.highWaterMark.is_none() {
return Ok(default_hwm);
}
@ -114,7 +121,7 @@ pub fn extract_high_water_mark(strategy: &QueuingStrategy, default_hwm: f64) ->
/// If the size algorithm is not set, return a fallback function which always returns 1.
///
/// <https://streams.spec.whatwg.org/#make-size-algorithm-from-size-function>
pub fn extract_size_algorithm(strategy: &QueuingStrategy) -> Rc<QueuingStrategySize> {
pub(crate) fn extract_size_algorithm(strategy: &QueuingStrategy) -> Rc<QueuingStrategySize> {
if strategy.size.is_none() {
let cx = GlobalScope::get_cx();
let fun_obj = native_raw_obj_fn!(cx, count_queuing_strategy_size, c"size", 0, 0);

View file

@ -221,7 +221,7 @@ fn create_html_element(
result
}
pub fn create_native_html_element(
pub(crate) fn create_native_html_element(
name: QualName,
prefix: Option<Prefix>,
document: &Document,
@ -394,7 +394,7 @@ pub fn create_native_html_element(
}
}
pub fn create_element(
pub(crate) fn create_element(
name: QualName,
is: Option<LocalName>,
document: &Document,

View file

@ -21,7 +21,7 @@ use crate::script_runtime::{CanGc, JSContext};
// https://developer.mozilla.org/en-US/docs/Web/API/Crypto
#[dom_struct]
pub struct Crypto {
pub(crate) struct Crypto {
reflector_: Reflector,
#[no_trace]
rng: DomRefCell<ServoRng>,
@ -37,7 +37,7 @@ impl Crypto {
}
}
pub fn new(global: &GlobalScope) -> DomRoot<Crypto> {
pub(crate) fn new(global: &GlobalScope) -> DomRoot<Crypto> {
reflect_dom_object(Box::new(Crypto::new_inherited()), global, CanGc::note())
}
}

View file

@ -22,7 +22,7 @@ use crate::script_runtime::{CanGc, JSContext};
/// The underlying cryptographic data this key represents
#[allow(dead_code)]
#[derive(MallocSizeOf)]
pub enum Handle {
pub(crate) enum Handle {
Aes128(Vec<u8>),
Aes192(Vec<u8>),
Aes256(Vec<u8>),
@ -33,7 +33,7 @@ pub enum Handle {
/// <https://w3c.github.io/webcrypto/#cryptokey-interface>
#[dom_struct]
pub struct CryptoKey {
pub(crate) struct CryptoKey {
reflector_: Reflector,
/// <https://w3c.github.io/webcrypto/#dom-cryptokey-type>
@ -78,7 +78,7 @@ impl CryptoKey {
}
}
pub fn new(
pub(crate) fn new(
global: &GlobalScope,
key_type: KeyType,
extractable: bool,
@ -104,15 +104,15 @@ impl CryptoKey {
object
}
pub fn algorithm(&self) -> String {
pub(crate) fn algorithm(&self) -> String {
self.algorithm.to_string()
}
pub fn usages(&self) -> &[KeyUsage] {
pub(crate) fn usages(&self) -> &[KeyUsage] {
&self.usages
}
pub fn handle(&self) -> &Handle {
pub(crate) fn handle(&self) -> &Handle {
&self.handle
}
}
@ -145,7 +145,7 @@ impl CryptoKeyMethods<crate::DomTypeHolder> for CryptoKey {
}
impl Handle {
pub fn as_bytes(&self) -> &[u8] {
pub(crate) fn as_bytes(&self) -> &[u8] {
match self {
Self::Aes128(bytes) => bytes,
Self::Aes192(bytes) => bytes,

View file

@ -21,7 +21,7 @@ use crate::dom::worklet::Worklet;
#[dom_struct]
#[allow(clippy::upper_case_acronyms)]
pub struct CSS {
pub(crate) struct CSS {
reflector_: Reflector,
}

View file

@ -16,12 +16,12 @@ use crate::dom::cssstylesheet::CSSStyleSheet;
use crate::dom::csssupportsrule::CSSSupportsRule;
#[dom_struct]
pub struct CSSConditionRule {
pub(crate) struct CSSConditionRule {
cssgroupingrule: CSSGroupingRule,
}
impl CSSConditionRule {
pub fn new_inherited(
pub(crate) fn new_inherited(
parent_stylesheet: &CSSStyleSheet,
rules: Arc<Locked<StyleCssRules>>,
) -> CSSConditionRule {
@ -30,11 +30,11 @@ impl CSSConditionRule {
}
}
pub fn parent_stylesheet(&self) -> &CSSStyleSheet {
pub(crate) fn parent_stylesheet(&self) -> &CSSStyleSheet {
self.cssgroupingrule.parent_stylesheet()
}
pub fn shared_lock(&self) -> &SharedRwLock {
pub(crate) fn shared_lock(&self) -> &SharedRwLock {
self.cssgroupingrule.shared_lock()
}
}

View file

@ -16,7 +16,7 @@ use crate::dom::window::Window;
use crate::script_runtime::CanGc;
#[dom_struct]
pub struct CSSFontFaceRule {
pub(crate) struct CSSFontFaceRule {
cssrule: CSSRule,
#[ignore_malloc_size_of = "Arc"]
#[no_trace]
@ -35,7 +35,7 @@ impl CSSFontFaceRule {
}
#[allow(crown::unrooted_must_root)]
pub fn new(
pub(crate) fn new(
window: &Window,
parent_stylesheet: &CSSStyleSheet,
fontfacerule: Arc<Locked<FontFaceRule>>,

View file

@ -18,7 +18,7 @@ use crate::dom::cssrulelist::{CSSRuleList, RulesSource};
use crate::dom::cssstylesheet::CSSStyleSheet;
#[dom_struct]
pub struct CSSGroupingRule {
pub(crate) struct CSSGroupingRule {
cssrule: CSSRule,
#[ignore_malloc_size_of = "Arc"]
#[no_trace]
@ -27,7 +27,7 @@ pub struct CSSGroupingRule {
}
impl CSSGroupingRule {
pub fn new_inherited(
pub(crate) fn new_inherited(
parent_stylesheet: &CSSStyleSheet,
rules: Arc<Locked<StyleCssRules>>,
) -> CSSGroupingRule {
@ -49,11 +49,11 @@ impl CSSGroupingRule {
})
}
pub fn parent_stylesheet(&self) -> &CSSStyleSheet {
pub(crate) fn parent_stylesheet(&self) -> &CSSStyleSheet {
self.cssrule.parent_stylesheet()
}
pub fn shared_lock(&self) -> &SharedRwLock {
pub(crate) fn shared_lock(&self) -> &SharedRwLock {
self.cssrule.shared_lock()
}
}

View file

@ -19,7 +19,7 @@ use crate::dom::window::Window;
use crate::script_runtime::CanGc;
#[dom_struct]
pub struct CSSImportRule {
pub(crate) struct CSSImportRule {
cssrule: CSSRule,
#[ignore_malloc_size_of = "Arc"]
#[no_trace]
@ -38,7 +38,7 @@ impl CSSImportRule {
}
#[allow(crown::unrooted_must_root)]
pub fn new(
pub(crate) fn new(
window: &Window,
parent_stylesheet: &CSSStyleSheet,
import_rule: Arc<Locked<ImportRule>>,

View file

@ -20,7 +20,7 @@ use crate::dom::window::Window;
use crate::script_runtime::CanGc;
#[dom_struct]
pub struct CSSKeyframeRule {
pub(crate) struct CSSKeyframeRule {
cssrule: CSSRule,
#[ignore_malloc_size_of = "Arc"]
#[no_trace]
@ -41,7 +41,7 @@ impl CSSKeyframeRule {
}
#[allow(crown::unrooted_must_root)]
pub fn new(
pub(crate) fn new(
window: &Window,
parent_stylesheet: &CSSStyleSheet,
keyframerule: Arc<Locked<Keyframe>>,

Some files were not shown because too many files have changed in this diff Show more