DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Mercurial (1aeaa33a64f9)

VCS Links

Line Code
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 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
use core::fmt;
use core::mem;
use core::ops::{Deref, DerefMut};
use core::ptr;


cfg_if! {
    if #[cfg(feature = "nightly")] {
        // This trick allows use to support rustc 1.12.1, which does not support the
        // #[repr(align(n))] syntax. Using the attribute makes the parser fail over.
        // It is, however, okay to use it within a macro, since it would be parsed
        // in a later stage, but that never occurs due to the cfg_if.
        // TODO(Vtec234): remove this crap when we drop support for 1.12.
        macro_rules! nightly_inner {
            () => (
                #[derive(Clone)]
                #[repr(align(64))]
                pub(crate) struct Inner<T> {
                    value: T,
                }
            )
        }
        nightly_inner!();

        impl<T> Inner<T> {
            pub(crate) fn new(t: T) -> Inner<T> {
                Self {
                    value: t
                }
            }
        }

        impl<T> Deref for Inner<T> {
            type Target = T;

            fn deref(&self) -> &T {
                &self.value
            }
        }

        impl<T> DerefMut for Inner<T> {
            fn deref_mut(&mut self) -> &mut T {
                &mut self.value
            }
        }
    } else {
        use core::marker::PhantomData;

        struct Inner<T> {
            bytes: [u8; 64],

            /// `[T; 0]` ensures alignment is at least that of `T`.
            /// `PhantomData<T>` signals that `CachePadded<T>` contains a `T`.
            _marker: ([T; 0], PhantomData<T>),
        }

        impl<T> Inner<T> {
            fn new(t: T) -> Inner<T> {
                assert!(mem::size_of::<T>() <= mem::size_of::<Self>());
                assert!(mem::align_of::<T>() <= mem::align_of::<Self>());

                unsafe {
                    let mut inner: Self = mem::uninitialized();
                    let p: *mut T = &mut *inner;
                    ptr::write(p, t);
                    inner
                }
            }
        }

        impl<T> Deref for Inner<T> {
            type Target = T;

            fn deref(&self) -> &T {
                unsafe { &*(self.bytes.as_ptr() as *const T) }
            }
        }

        impl<T> DerefMut for Inner<T> {
            fn deref_mut(&mut self) -> &mut T {
                unsafe { &mut *(self.bytes.as_ptr() as *mut T) }
            }
        }

        impl<T> Drop for CachePadded<T> {
            fn drop(&mut self) {
                let p: *mut T = self.deref_mut();
                unsafe {
                    ptr::drop_in_place(p);
                }
            }
        }

        impl<T: Clone> Clone for Inner<T> {
            fn clone(&self) -> Inner<T> {
                let val = self.deref().clone();
                Self::new(val)
            }
        }
    }
}

/// Pads `T` to the length of a cache line.
///
/// Sometimes concurrent programming requires a piece of data to be padded out to the size of a
/// cacheline to avoid "false sharing": cache lines being invalidated due to unrelated concurrent
/// activity. Use this type when you want to *avoid* cache locality.
///
/// At the moment, cache lines are assumed to be 64 bytes on all architectures.
///
/// # Size and alignment
///
/// By default, the size of `CachePadded<T>` is 64 bytes. If `T` is larger than that, then
/// `CachePadded::<T>::new` will panic. Alignment of `CachePadded<T>` is the same as that of `T`.
///
/// However, if the `nightly` feature is enabled, arbitrarily large types `T` can be stored inside
/// a `CachePadded<T>`. The size will then be a multiple of 64 at least the size of `T`, and the
/// alignment will be the maximum of 64 and the alignment of `T`.
pub struct CachePadded<T> {
    inner: Inner<T>,
}

unsafe impl<T: Send> Send for CachePadded<T> {}
unsafe impl<T: Sync> Sync for CachePadded<T> {}

impl<T> CachePadded<T> {
    /// Pads a value to the length of a cache line.
    ///
    /// # Panics
    ///
    /// If `nightly` is not enabled and `T` is larger than 64 bytes, this function will panic.
    pub fn new(t: T) -> CachePadded<T> {
        CachePadded::<T> { inner: Inner::new(t) }
    }
}

impl<T> Deref for CachePadded<T> {
    type Target = T;

    fn deref(&self) -> &T {
        self.inner.deref()
    }
}

impl<T> DerefMut for CachePadded<T> {
    fn deref_mut(&mut self) -> &mut T {
        self.inner.deref_mut()
    }
}

impl<T: Default> Default for CachePadded<T> {
    fn default() -> Self {
        Self::new(Default::default())
    }
}

impl<T: Clone> Clone for CachePadded<T> {
    fn clone(&self) -> Self {
        CachePadded { inner: self.inner.clone() }
    }
}

impl<T: fmt::Debug> fmt::Debug for CachePadded<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let inner: &T = &*self;
        write!(f, "CachePadded {{ {:?} }}", inner)
    }
}

impl<T> From<T> for CachePadded<T> {
    fn from(t: T) -> Self {
        CachePadded::new(t)
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use std::cell::Cell;

    #[test]
    fn store_u64() {
        let x: CachePadded<u64> = CachePadded::new(17);
        assert_eq!(*x, 17);
    }

    #[test]
    fn store_pair() {
        let x: CachePadded<(u64, u64)> = CachePadded::new((17, 37));
        assert_eq!(x.0, 17);
        assert_eq!(x.1, 37);
    }

    #[test]
    fn distance() {
        let arr = [CachePadded::new(17u8), CachePadded::new(37u8)];
        let a = &*arr[0] as *const u8;
        let b = &*arr[1] as *const u8;
        assert!(unsafe { a.offset(64) } <= b);
    }

    #[test]
    fn different_sizes() {
        CachePadded::new(17u8);
        CachePadded::new(17u16);
        CachePadded::new(17u32);
        CachePadded::new([17u64; 0]);
        CachePadded::new([17u64; 1]);
        CachePadded::new([17u64; 2]);
        CachePadded::new([17u64; 3]);
        CachePadded::new([17u64; 4]);
        CachePadded::new([17u64; 5]);
        CachePadded::new([17u64; 6]);
        CachePadded::new([17u64; 7]);
        CachePadded::new([17u64; 8]);
    }

    cfg_if! {
        if #[cfg(feature = "nightly")] {
            #[test]
            fn large() {
                let a = [17u64; 9];
                let b = CachePadded::new(a);
                assert!(mem::size_of_val(&a) <= mem::size_of_val(&b));
            }
        } else {
            #[test]
            #[should_panic]
            fn large() {
                CachePadded::new([17u64; 9]);
            }
        }
    }

    #[test]
    fn debug() {
        assert_eq!(
            format!("{:?}", CachePadded::new(17u64)),
            "CachePadded { 17 }"
        );
    }

    #[test]
    fn drops() {
        let count = Cell::new(0);

        struct Foo<'a>(&'a Cell<usize>);

        impl<'a> Drop for Foo<'a> {
            fn drop(&mut self) {
                self.0.set(self.0.get() + 1);
            }
        }

        let a = CachePadded::new(Foo(&count));
        let b = CachePadded::new(Foo(&count));

        assert_eq!(count.get(), 0);
        drop(a);
        assert_eq!(count.get(), 1);
        drop(b);
        assert_eq!(count.get(), 2);
    }

    #[test]
    fn clone() {
        let a = CachePadded::new(17);
        let b = a.clone();
        assert_eq!(*a, *b);
    }

    #[test]
    fn runs_custom_clone() {
        let count = Cell::new(0);

        struct Foo<'a>(&'a Cell<usize>);

        impl<'a> Clone for Foo<'a> {
            fn clone(&self) -> Foo<'a> {
                self.0.set(self.0.get() + 1);
                Foo::<'a>(self.0)
            }
        }

        let a = CachePadded::new(Foo(&count));
        a.clone();

        assert_eq!(count.get(), 1);
    }
}