Source code

Revision control

Other Tools

1
/* This Source Code Form is subject to the terms of the Mozilla Public
2
* License, v. 2.0. If a copy of the MPL was not distributed with this
3
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5
//! A type to represent a namespace.
6
7
use crate::gecko_bindings::structs::nsAtom;
8
use crate::string_cache::{Atom, WeakAtom};
9
use precomputed_hash::PrecomputedHash;
10
use std::borrow::Borrow;
11
use std::fmt;
12
use std::ops::Deref;
13
14
/// In Gecko namespaces are just regular atoms, so this is a simple macro to
15
/// forward one macro to the other.
16
#[macro_export]
17
macro_rules! ns {
18
() => {
19
$crate::string_cache::Namespace(atom!(""))
20
};
21
($s:tt) => {
22
$crate::string_cache::Namespace(atom!($s))
23
};
24
}
25
26
/// A Gecko namespace is just a wrapped atom.
27
#[derive(Clone, Debug, Default, Eq, Hash, MallocSizeOf, PartialEq, ToShmem)]
28
pub struct Namespace(pub Atom);
29
30
impl PrecomputedHash for Namespace {
31
#[inline]
32
fn precomputed_hash(&self) -> u32 {
33
self.0.precomputed_hash()
34
}
35
}
36
37
/// A Gecko WeakNamespace is a wrapped WeakAtom.
38
#[derive(Hash)]
39
pub struct WeakNamespace(WeakAtom);
40
41
impl Deref for WeakNamespace {
42
type Target = WeakAtom;
43
44
#[inline]
45
fn deref(&self) -> &WeakAtom {
46
&self.0
47
}
48
}
49
50
impl Deref for Namespace {
51
type Target = WeakNamespace;
52
53
#[inline]
54
fn deref(&self) -> &WeakNamespace {
55
let weak: *const WeakAtom = &*self.0;
56
unsafe { &*(weak as *const WeakNamespace) }
57
}
58
}
59
60
impl<'a> From<&'a str> for Namespace {
61
fn from(s: &'a str) -> Self {
62
Namespace(Atom::from(s))
63
}
64
}
65
66
impl fmt::Display for Namespace {
67
fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
68
self.0.fmt(w)
69
}
70
}
71
72
impl Borrow<WeakNamespace> for Namespace {
73
#[inline]
74
fn borrow(&self) -> &WeakNamespace {
75
self
76
}
77
}
78
79
impl WeakNamespace {
80
/// Trivially construct a WeakNamespace.
81
#[inline]
82
pub unsafe fn new<'a>(atom: *mut nsAtom) -> &'a Self {
83
&*(atom as *const WeakNamespace)
84
}
85
86
/// Clone this WeakNamespace to obtain a strong reference to the same
87
/// underlying namespace.
88
#[inline]
89
pub fn clone(&self) -> Namespace {
90
Namespace(self.0.clone())
91
}
92
}
93
94
impl Eq for WeakNamespace {}
95
impl PartialEq for WeakNamespace {
96
#[inline]
97
fn eq(&self, other: &Self) -> bool {
98
let weak: *const WeakNamespace = self;
99
let other: *const WeakNamespace = other;
100
weak == other
101
}
102
}