rust_macios/foundation/
ns_range.rs

1use std::ops::Range;
2
3use objc::Encoding;
4
5use crate::objective_c_runtime;
6
7use super::{NSString, UInt};
8
9/// A structure used to describe a portion of a series, such as characters in a string or objects in an array.
10#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
11#[repr(C)]
12pub struct NSRange {
13    /// The number of items in the range (can be 0). For type compatibility with the rest of the system, LONG_MAX is the maximum value you should use for length.
14    pub location: UInt,
15    /// The start index (0 is the first, as in C arrays). For type compatibility with the rest of the system, LONG_MAX is the maximum value you should use for location.
16    pub length: UInt,
17}
18
19unsafe impl objective_c_runtime::Encode for NSRange {
20    fn encode() -> objc::Encoding {
21        unsafe { Encoding::from_str("{location=I, length=I}") }
22    }
23}
24
25extern "C" {
26    /// Creates a new NSRange from the specified values.
27    pub fn NSMakeRange(loc: UInt, len: UInt) -> NSRange;
28
29    /// Returns the sum of the location and length of the range.
30    pub fn NSMaxRange(range: NSRange) -> UInt;
31
32    /// Returns the intersection of the specified ranges.
33    pub fn NSIntersectionRange(range1: NSRange, range2: NSRange) -> NSRange;
34
35    /// Returns the union of the specified ranges.
36    pub fn NSUnionRange(range1: NSRange, range2: NSRange) -> NSRange;
37
38    /// Returns a Boolean value that indicates whether a specified position is in a given range.
39    pub fn NSLocationInRange(loc: UInt, range: NSRange) -> bool;
40
41    /// Returns a Boolean value that indicates whether two given ranges are equal.
42    pub fn NSEqualRanges(range1: NSRange, range2: NSRange) -> bool;
43
44    /// Returns a range from a textual representation.
45    pub fn NSRangeFromString(aString: NSString) -> NSRange;
46
47    /// Returns a string representation of a range.
48    pub fn NSStringFromRange(range: NSRange) -> NSString;
49}
50
51impl From<Range<usize>> for NSRange {
52    fn from(range: Range<usize>) -> Self {
53        NSRange {
54            location: range.start as UInt,
55            length: (range.end - range.start) as UInt,
56        }
57    }
58}
59
60impl From<NSRange> for Range<usize> {
61    fn from(range: NSRange) -> Self {
62        range.location as usize..(range.location + range.length) as usize
63    }
64}