stylo: Use Deref<Target=[T]> for nsTArray instead of Index<u32>

Makes things a lot nicer :)
This commit is contained in:
Emilio Cobos Álvarez 2016-06-02 18:25:32 +02:00
parent 8220eaab9b
commit c6340c4840
No known key found for this signature in database
GPG key ID: 056B727BB9C1027C
2 changed files with 16 additions and 30 deletions

View file

@ -3,20 +3,27 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::mem; use std::mem;
use std::ops::{Index, IndexMut}; use std::ops::{Deref, DerefMut};
use std::slice;
use structs::{nsTArray, nsTArrayHeader}; use structs::{nsTArray, nsTArrayHeader};
impl<T> Index<u32> for nsTArray<T> { impl<T> Deref for nsTArray<T> {
type Output = T; type Target = [T];
fn index<'a>(&'a self, index: u32) -> &'a T { fn deref<'a>(&'a self) -> &'a [T] {
unsafe { mem::transmute(self.ptr_at(index)) } unsafe {
slice::from_raw_parts(self.slice_begin(),
self.header().mLength as usize)
}
} }
} }
impl<T> IndexMut<u32> for nsTArray<T> { impl<T> DerefMut for nsTArray<T> {
fn index_mut<'a>(&'a mut self, index: u32) -> &'a mut T { fn deref_mut<'a>(&'a mut self) -> &'a mut [T] {
unsafe { mem::transmute(self.ptr_at_mut(index)) } unsafe {
slice::from_raw_parts_mut(self.slice_begin(),
self.header().mLength as usize)
}
} }
} }
@ -27,30 +34,9 @@ impl<T> nsTArray<T> {
unsafe { mem::transmute(self.mBuffer) } unsafe { mem::transmute(self.mBuffer) }
} }
#[inline]
pub fn len(&self) -> u32 {
self.header().mLength
}
#[inline] #[inline]
unsafe fn slice_begin(&self) -> *mut T { unsafe fn slice_begin(&self) -> *mut T {
debug_assert!(!self.mBuffer.is_null()); debug_assert!(!self.mBuffer.is_null());
(self.mBuffer as *const nsTArrayHeader).offset(1) as *mut _ (self.mBuffer as *const nsTArrayHeader).offset(1) as *mut _
} }
#[inline]
fn ptr_at_mut(&mut self, index: u32) -> *mut T {
debug_assert!(index <= self.len());
unsafe {
self.slice_begin().offset(index as isize)
}
}
#[inline]
fn ptr_at(&self, index: u32) -> *const T {
debug_assert!(index <= self.len());
unsafe {
self.slice_begin().offset(index as isize)
}
}
} }

View file

@ -805,7 +805,7 @@ fn static_assert() {
}; };
let mut stop = unsafe { let mut stop = unsafe {
&mut (*gecko_gradient).mStops[index as u32] &mut (*gecko_gradient).mStops[index]
}; };
stop.mColor = color; stop.mColor = color;