Skip to content

Commit

Permalink
Improve NSRange
Browse files Browse the repository at this point in the history
  • Loading branch information
madsmtm committed Oct 31, 2021
1 parent 5cc31bd commit 7826ca8
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 13 deletions.
2 changes: 1 addition & 1 deletion objc2_foundation/src/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ pub unsafe trait INSArray: INSObject {
}

fn objects_in_range(&self, range: Range<usize>) -> Vec<&Self::Item> {
let range = NSRange::from_range(range);
let range = NSRange::from(range);
let mut vec = Vec::with_capacity(range.length);
unsafe {
let _: () = msg_send![self, getObjects: vec.as_ptr(), range: range];
Expand Down
2 changes: 1 addition & 1 deletion objc2_foundation/src/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ pub unsafe trait INSMutableData: INSData {
}

fn replace_range(&mut self, range: Range<usize>, bytes: &[u8]) {
let range = NSRange::from_range(range);
let range = NSRange::from(range);
let bytes_ptr = bytes.as_ptr() as *const c_void;
unsafe {
let _: () = msg_send![
Expand Down
48 changes: 37 additions & 11 deletions objc2_foundation/src/range.rs
Original file line number Diff line number Diff line change
@@ -1,27 +1,49 @@
use core::ops::Range;

use objc2::{Encode, Encoding};
use objc2::{Encode, Encoding, RefEncode};

#[repr(C)]
#[derive(Clone, Copy)]
// PartialEq is same as NSEqualRanges
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct NSRange {
pub location: usize,
pub length: usize,
}

impl NSRange {
pub fn from_range(range: Range<usize>) -> NSRange {
assert!(range.end >= range.start);
NSRange {
// impl NSRange {
// pub fn contains(&self, index: usize) -> bool {
// // Same as NSLocationInRange
// <Self as RangeBounds<usize>>::contains(self, &index)
// }
// }

// impl RangeBounds<usize> for NSRange {
// fn start_bound(&self) -> Bound<&usize> {
// Bound::Included(&self.location)
// }
// fn end_bound(&self) -> Bound<&usize> {
// Bound::Excluded(&(self.location + self.length))
// }
// }

impl From<Range<usize>> for NSRange {
fn from(range: Range<usize>) -> Self {
let length = range
.end
.checked_sub(range.start)
.expect("Range end < start");
Self {
location: range.start,
length: range.end - range.start,
length,
}
}
}

pub fn as_range(&self) -> Range<usize> {
Range {
start: self.location,
end: self.location + self.length,
impl From<NSRange> for Range<usize> {
fn from(nsrange: NSRange) -> Self {
Self {
start: nsrange.location,
end: nsrange.location + nsrange.length,
}
}
}
Expand All @@ -30,3 +52,7 @@ unsafe impl Encode for NSRange {
const ENCODING: Encoding<'static> =
Encoding::Struct("_NSRange", &[usize::ENCODING, usize::ENCODING]);
}

unsafe impl RefEncode for NSRange {
const ENCODING_REF: Encoding<'static> = Encoding::Pointer(&Self::ENCODING);
}

0 comments on commit 7826ca8

Please sign in to comment.