aboutsummaryrefslogtreecommitdiffstats
path: root/components/style/shared_lock.rs
blob: c92ab9efccf2fb13b61e513bd9c72c10a4d33655 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//! Different objects protected by the same lock

use parking_lot::RwLock;
use std::cell::UnsafeCell;
use std::fmt;
use std::sync::Arc;

/// A shared read/write lock that can protect multiple objects.
#[derive(Clone)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct SharedRwLock {
    #[cfg_attr(feature = "servo", ignore_heap_size_of = "Arc")]
    arc: Arc<RwLock<()>>,
}

impl fmt::Debug for SharedRwLock {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("SharedRwLock")
    }
}

impl SharedRwLock {
    /// Create a new shared lock
    pub fn new() -> Self {
        SharedRwLock {
            arc: Arc::new(RwLock::new(()))
        }
    }

    /// Wrap the given data to make its access protected by this lock.
    pub fn wrap<T>(&self, data: T) -> Locked<T> {
        Locked {
            shared_lock: self.clone(),
            data: UnsafeCell::new(data),
        }
    }

    /// Obtain the lock for reading
    pub fn read(&self) -> SharedRwLockReadGuard {
        self.arc.raw_read();
        SharedRwLockReadGuard {
            shared_lock: self
        }
    }

    /// Obtain the lock for writing
    pub fn write(&self) -> SharedRwLockWriteGuard {
        self.arc.raw_write();
        SharedRwLockWriteGuard {
            shared_lock: self
        }
    }
}

/// Data protect by a shared lock.
pub struct Locked<T> {
    shared_lock: SharedRwLock,
    data: UnsafeCell<T>,
}

// Unsafe: the data inside `UnsafeCell` is only accessed in `read_with` and `write_with`,
// where guards ensure synchronization.
unsafe impl<T: Send> Send for Locked<T> {}
unsafe impl<T: Send + Sync> Sync for Locked<T> {}

impl<T: fmt::Debug> fmt::Debug for Locked<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let guard = self.shared_lock.read();
        self.read_with(&guard).fmt(f)
    }
}

impl<T> Locked<T> {
    fn same_lock_as(&self, lock: &SharedRwLock) -> bool {
        ::arc_ptr_eq(&self.shared_lock.arc, &lock.arc)
    }

    /// Access the data for reading.
    pub fn read_with<'a>(&'a self, guard: &'a SharedRwLockReadGuard) -> &'a T {
        assert!(self.same_lock_as(&guard.shared_lock),
                "Locked::read_with called with a guard from an unrelated SharedRwLock");
        let ptr = self.data.get();

        // Unsafe:
        //
        // * The guard guarantees that the lock is taken for reading,
        //   and we’ve checked that it’s the correct lock.
        // * The returned reference borrows *both* the data and the guard,
        //   so that it can outlive neither.
        unsafe {
            &*ptr
        }
    }

    /// Access the data for writing.
    pub fn write_with<'a>(&'a self, guard: &'a mut SharedRwLockWriteGuard) -> &'a mut T {
        assert!(self.same_lock_as(&guard.shared_lock),
                "Locked::write_with called with a guard from an unrelated SharedRwLock");
        let ptr = self.data.get();

        // Unsafe:
        //
        // * The guard guarantees that the lock is taken for writing,
        //   and we’ve checked that it’s the correct lock.
        // * The returned reference borrows *both* the data and the guard,
        //   so that it can outlive neither.
        // * We require a mutable borrow of the guard,
        //   so that one write guard can only be used once at a time.
        unsafe {
            &mut *ptr
        }
    }
}

/// Proof that a shared lock was obtained for reading.
pub struct SharedRwLockReadGuard<'a> {
    shared_lock: &'a SharedRwLock,
}

/// Proof that a shared lock was obtained for writing.
pub struct SharedRwLockWriteGuard<'a> {
    shared_lock: &'a SharedRwLock,
}

impl<'a> Drop for SharedRwLockReadGuard<'a> {
    fn drop(&mut self) {
        // Unsafe: self.lock is private to this module, only ever set after `raw_read()`,
        // and never copied or cloned (see `compile_time_assert` below).
        unsafe {
            self.shared_lock.arc.raw_unlock_read()
        }
    }
}

impl<'a> Drop for SharedRwLockWriteGuard<'a> {
    fn drop(&mut self) {
        // Unsafe: self.lock is private to this module, only ever set after `raw_write()`,
        // and never copied or cloned (see `compile_time_assert` below).
        unsafe {
            self.shared_lock.arc.raw_unlock_write()
        }
    }
}

#[allow(dead_code)]
mod compile_time_assert {
    use super::{SharedRwLockReadGuard, SharedRwLockWriteGuard};

    trait Marker1 {}
    impl<T: Clone> Marker1 for T {}
    impl<'a> Marker1 for SharedRwLockReadGuard<'a> {}  // Assert SharedRwLockReadGuard: !Clone
    impl<'a> Marker1 for SharedRwLockWriteGuard<'a> {}  // Assert SharedRwLockWriteGuard: !Clone

    trait Marker2 {}
    impl<T: Copy> Marker2 for T {}
    impl<'a> Marker2 for SharedRwLockReadGuard<'a> {}  // Assert SharedRwLockReadGuard: !Copy
    impl<'a> Marker2 for SharedRwLockWriteGuard<'a> {}  // Assert SharedRwLockWriteGuard: !Copy
}

/// Like ToCss, but with a lock guard given by the caller.
pub trait ToCssWithGuard {
    /// Serialize `self` in CSS syntax, writing to `dest`, using the given lock guard.
    fn to_css<W>(&self, guard: &SharedRwLockReadGuard, dest: &mut W) -> fmt::Result
    where W: fmt::Write;

    /// Serialize `self` in CSS syntax using the given lock guard and return a string.
    ///
    /// (This is a convenience wrapper for `to_css` and probably should not be overridden.)
    #[inline]
    fn to_css_string(&self, guard: &SharedRwLockReadGuard) -> String {
        let mut s = String::new();
        self.to_css(guard, &mut s).unwrap();
        s
    }
}

/// Guards for a document
#[derive(Clone)]
pub struct ReadGuards<'a> {
    /// For author-origin stylesheets
    pub author: &'a SharedRwLockReadGuard<'a>,

    /// For user-agent-origin and user-origin stylesheets
    pub ua_or_user: &'a SharedRwLockReadGuard<'a>,
}

impl<'a> ReadGuards<'a> {
    /// Same guard for all origins
    pub fn same(guard: &'a SharedRwLockReadGuard<'a>) -> Self {
        ReadGuards {
            author: guard,
            ua_or_user: guard,
        }
    }
}