Skip to main content

skia_safe/core/
region.rs

1//! Describes the set of pixels used to clip [`crate::Canvas`]. [`Region`] is compact, efficiently
2//! storing a single integer rectangle, or a run length encoded array of rectangles. [`Region`] may
3//! reduce the current [`crate::Canvas`] clip, or may be drawn as one or more integer rectangles.
4//! The [`Region`] iterator returns the scan lines or rectangles contained by it, optionally
5//! intersecting a bounding rectangle.
6
7use std::{fmt, iter, marker::PhantomData, mem, ptr};
8
9use crate::{Contains, IPoint, IRect, IVector, Path, PathBuilder, QuickReject, prelude::*};
10use skia_bindings::{
11    self as sb, SkRegion, SkRegion_Cliperator, SkRegion_Iterator, SkRegion_RunHead,
12    SkRegion_Spanerator,
13};
14
15pub type Region = Handle<SkRegion>;
16unsafe_send_sync!(Region);
17
18impl NativeDrop for SkRegion {
19    /// Releases ownership of any shared data and deletes data if the region is sole owner.
20    ///
21    /// Example (C++): <https://fiddle.skia.org/c/@Region_destructor>
22    fn drop(&mut self) {
23        unsafe { sb::C_SkRegion_destruct(self) }
24    }
25}
26
27impl NativeClone for SkRegion {
28    /// Constructs a copy of an existing region. Makes two regions identical by value. Internally,
29    /// the region and the returned result share pointer values. The underlying rectangle array is
30    /// copied when modified.
31    ///
32    /// Creating a region copy is very efficient and never allocates memory. Regions are always
33    /// copied by value from the interface; the underlying shared pointers are not exposed.
34    ///
35    /// Example (C++): <https://fiddle.skia.org/c/@Region_copy_const_SkRegion>
36    /// Example (C++): <https://fiddle.skia.org/c/@Region_copy_operator>
37    fn clone(&self) -> Self {
38        unsafe { SkRegion::new1(self) }
39    }
40}
41
42impl NativePartialEq for SkRegion {
43    /// Compares the region and `rhs`; returns true if they enclose exactly the same area.
44    ///
45    /// Example (C++): <https://fiddle.skia.org/c/@Region_equal1_operator>
46    fn eq(&self, rhs: &Self) -> bool {
47        unsafe { sb::C_SkRegion_Equals(self, rhs) }
48    }
49}
50
51impl fmt::Debug for Region {
52    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53        f.debug_struct("Region")
54            .field("is_empty", &self.is_empty())
55            .field("is_rect", &self.is_rect())
56            .field("is_complex", &self.is_complex())
57            .field("bounds", &self.bounds())
58            .finish()
59    }
60}
61
62/// The logical operations that can be performed when combining two regions.
63pub use skia_bindings::SkRegion_Op as RegionOp;
64variant_name!(RegionOp::ReverseDifference);
65
66impl Region {
67    /// Constructs an empty region. The region is set to empty bounds at (0, 0) with zero width and
68    /// height.
69    ///
70    /// Example (C++): <https://fiddle.skia.org/c/@Region_empty_constructor>
71    pub fn new() -> Region {
72        Self::from_native_c(unsafe { SkRegion::new() })
73    }
74
75    /// Constructs a rectangular region matching the bounds of `rect`.
76    ///
77    /// - `rect` bounds of the constructed region
78    ///
79    /// Example (C++): <https://fiddle.skia.org/c/@Region_copy_const_SkIRect>
80    pub fn from_rect(rect: impl AsRef<IRect>) -> Region {
81        Self::from_native_c(unsafe { SkRegion::new2(rect.as_ref().native()) })
82    }
83
84    /// Sets the region to `src`, and returns true if `src` bounds is not empty. This makes the
85    /// region and `src` identical by value. Internally, the region and `src` share pointer values.
86    /// The underlying rectangle array is copied when modified.
87    ///
88    /// Creating a region copy is very efficient and never allocates memory. Regions are always
89    /// copied by value from the interface; the underlying shared pointers are not exposed.
90    ///
91    /// - `src` region to copy
92    pub fn set(&mut self, src: &Region) -> bool {
93        unsafe { sb::C_SkRegion_set(self.native_mut(), src.native()) }
94    }
95
96    /// Exchanges the rectangle array of the region and `other`. `swap` internally exchanges
97    /// pointers, so it is lightweight and does not allocate memory.
98    ///
99    /// `swap` usage has largely been replaced by assignment. Paths do not copy their content on
100    /// assignment until they are written to, making assignment as efficient as `swap`.
101    ///
102    /// - `other` region to swap with
103    ///
104    /// Example (C++): <https://fiddle.skia.org/c/@Region_swap>
105    pub fn swap(&mut self, other: &mut Region) {
106        unsafe { self.native_mut().swap(other.native_mut()) }
107    }
108
109    const EMPTY_RUN_HEAD_PTR: *mut SkRegion_RunHead = -1 as _;
110    const RECT_RUN_HEAD_PTR: *mut SkRegion_RunHead = ptr::null_mut();
111
112    /// Returns true if the region is empty. An empty region has bounds width or height less than
113    /// or equal to zero. The default constructor constructs an empty region; `set_empty` and
114    /// `set_rect` with dimensionless data make the region empty.
115    pub fn is_empty(&self) -> bool {
116        ptr::eq(self.native().fRunHead, Self::EMPTY_RUN_HEAD_PTR)
117    }
118
119    /// Returns true if the region is one [`IRect`] with positive dimensions.
120    pub fn is_rect(&self) -> bool {
121        ptr::eq(self.native().fRunHead, Self::RECT_RUN_HEAD_PTR)
122    }
123
124    /// Returns true if the region is described by more than one rectangle.
125    pub fn is_complex(&self) -> bool {
126        !self.is_empty() && !self.is_rect()
127    }
128
129    /// Returns the minimum and maximum axes values of the rectangle array. Returns (0, 0, 0, 0) if
130    /// the region is empty.
131    pub fn bounds(&self) -> &IRect {
132        IRect::from_native_ref(&self.native().fBounds)
133    }
134
135    /// Returns a value that increases with the number of elements in the region. Returns zero if
136    /// the region is empty. Returns one if the region equals an [`IRect`]; otherwise, returns a
137    /// value greater than one indicating that the region is complex.
138    ///
139    /// Call to compare regions for relative complexity.
140    ///
141    /// Example (C++): <https://fiddle.skia.org/c/@Region_computeRegionComplexity>
142    pub fn compute_region_complexity(&self) -> usize {
143        unsafe { self.native().computeRegionComplexity().try_into().unwrap() }
144    }
145
146    /// Appends the outline of the region to the path builder. Returns true if the region is not
147    /// empty; otherwise, returns false, and leaves the path unmodified.
148    ///
149    /// - `path` path to append to
150    ///
151    /// Example (C++): <https://fiddle.skia.org/c/@Region_getBoundaryPath>
152    pub fn add_boundary_path(&self, path: &mut PathBuilder) -> bool {
153        unsafe { self.native().addBoundaryPath(path.native_mut()) }
154    }
155
156    #[deprecated(since = "0.91.0", note = "Use boundary_path()")]
157    pub fn get_boundary_path(&self, path: &mut Path) -> bool {
158        unsafe { sb::C_SkRegion_getBoundaryPath(self.native(), path.native_mut()) };
159        !path.is_empty()
160    }
161
162    /// Returns the boundary of the region as a path, or `None` if the region is empty.
163    pub fn boundary_path(&self) -> Option<Path> {
164        let mut path = Path::default();
165        unsafe { sb::C_SkRegion_getBoundaryPath(self.native(), path.native_mut()) };
166        (!path.is_empty()).then_some(path)
167    }
168
169    /// Constructs an empty region. The region is set to empty bounds at (0, 0) with zero width and
170    /// height. Always returns false.
171    ///
172    /// Example (C++): <https://fiddle.skia.org/c/@Region_setEmpty>
173    pub fn set_empty(&mut self) -> bool {
174        unsafe { self.native_mut().setEmpty() }
175    }
176
177    /// Constructs a rectangular region matching the bounds of `rect`. If `rect` is empty,
178    /// constructs an empty region and returns false.
179    ///
180    /// - `rect` bounds of the constructed region
181    ///
182    /// Example (C++): <https://fiddle.skia.org/c/@Region_setRect>
183    pub fn set_rect(&mut self, rect: impl AsRef<IRect>) -> bool {
184        unsafe { self.native_mut().setRect(rect.as_ref().native()) }
185    }
186
187    /// Constructs a region as the union of the rectangles in `rects`. If `rects` is empty,
188    /// constructs an empty region. Returns false if the constructed region is empty.
189    ///
190    /// May be faster than repeated calls to `op`.
191    ///
192    /// - `rects` array of rectangles
193    ///
194    /// Example (C++): <https://fiddle.skia.org/c/@Region_setRects>
195    pub fn set_rects(&mut self, rects: &[IRect]) -> bool {
196        unsafe {
197            sb::C_SkRegion_setRects(
198                self.native_mut(),
199                rects.native().as_ptr(),
200                rects.len().try_into().unwrap(),
201            )
202        }
203    }
204
205    /// Sets the region to a copy of `region`. Creating a region copy is very efficient and never
206    /// allocates memory. Regions are always copied by value from the interface; the underlying
207    /// shared pointers are not exposed.
208    ///
209    /// - `region` region to copy by value
210    ///
211    /// Example (C++): <https://fiddle.skia.org/c/@Region_setRegion>
212    pub fn set_region(&mut self, region: &Region) -> bool {
213        unsafe { self.native_mut().setRegion(region.native()) }
214    }
215
216    /// Constructs a region to match the outline of `path` within `clip`. Returns false if the
217    /// constructed region is empty.
218    ///
219    /// The constructed region draws the same pixels as `path` through `clip` when anti-aliasing is
220    /// disabled.
221    ///
222    /// - `path` path providing outline
223    /// - `clip` region containing path
224    ///
225    /// Example (C++): <https://fiddle.skia.org/c/@Region_setPath>
226    pub fn set_path(&mut self, path: &Path, clip: &Region) -> bool {
227        unsafe { self.native_mut().setPath(path.native(), clip.native()) }
228    }
229
230    // There is also a trait for intersects() below.
231
232    /// Returns true if the region intersects `rect`. Returns false if either `rect` or the region
233    /// is empty, or they do not intersect.
234    ///
235    /// - `rect` rectangle to intersect
236    ///
237    /// Example (C++): <https://fiddle.skia.org/c/@Region_intersects>
238    pub fn intersects_rect(&self, rect: impl AsRef<IRect>) -> bool {
239        unsafe { self.native().intersects(rect.as_ref().native()) }
240    }
241
242    /// Returns true if the region intersects `other`. Returns false if either `other` or the region
243    /// is empty, or they do not intersect.
244    ///
245    /// - `other` region to intersect
246    ///
247    /// Example (C++): <https://fiddle.skia.org/c/@Region_intersects_2>
248    pub fn intersects_region(&self, other: &Region) -> bool {
249        unsafe { self.native().intersects1(other.native()) }
250    }
251
252    // contains() trait below.
253
254    /// Returns true if the point (`point.x`, `point.y`) is inside the region. Returns false if the
255    /// region is empty.
256    ///
257    /// - `point` test point
258    ///
259    /// Example (C++): <https://fiddle.skia.org/c/@Region_contains>
260    pub fn contains_point(&self, point: IPoint) -> bool {
261        unsafe { self.native().contains(point.x, point.y) }
262    }
263
264    /// Returns true if `rect` is completely inside the region. Returns false if the region or
265    /// `rect` is empty.
266    ///
267    /// - `rect` rectangle to contain
268    ///
269    /// Example (C++): <https://fiddle.skia.org/c/@Region_contains_2>
270    pub fn contains_rect(&self, rect: impl AsRef<IRect>) -> bool {
271        unsafe { self.native().contains1(rect.as_ref().native()) }
272    }
273
274    /// Returns true if `other` is completely inside the region. Returns false if the region or
275    /// `other` is empty.
276    ///
277    /// - `other` region to contain
278    ///
279    /// Example (C++): <https://fiddle.skia.org/c/@Region_contains_3>
280    pub fn contains_region(&self, other: &Region) -> bool {
281        unsafe { self.native().contains2(other.native()) }
282    }
283
284    /// Returns true if the region is a single rectangle and contains `r`. May return false even
285    /// though the region contains `r`.
286    ///
287    /// - `r` rectangle to contain
288    pub fn quick_contains(&self, r: impl AsRef<IRect>) -> bool {
289        let r = r.as_ref();
290        unsafe { sb::C_SkRegion_quickContains(self.native(), r.native()) }
291    }
292
293    // See also the quick_reject() trait below.
294
295    /// Returns true if the region does not intersect `rect`. Returns true if `rect` is empty or the
296    /// region is empty. May return false even though the region does not intersect `rect`.
297    ///
298    /// - `rect` rectangle to intersect
299    pub fn quick_reject_rect(&self, rect: impl AsRef<IRect>) -> bool {
300        let rect = rect.as_ref();
301        self.is_empty() || rect.is_empty() || !IRect::intersects(self.bounds(), rect)
302    }
303
304    /// Returns true if the region does not intersect `rgn`. Returns true if `rgn` is empty or the
305    /// region is empty. May return false even though the region does not intersect `rgn`.
306    ///
307    /// - `rgn` region to intersect
308    pub fn quick_reject_region(&self, rgn: &Region) -> bool {
309        self.is_empty() || rgn.is_empty() || !IRect::intersects(self.bounds(), rgn.bounds())
310    }
311
312    /// Offsets the region by the vector (`d.x`, `d.y`). Has no effect if the region is empty.
313    ///
314    /// - `d` offset vector
315    ///
316    /// Example (C++): <https://fiddle.skia.org/c/@Region_translate_2>
317    pub fn translate(&mut self, d: impl Into<IVector>) {
318        let d = d.into();
319        let self_ptr = self.native_mut() as *mut _;
320        unsafe { self.native().translate(d.x, d.y, self_ptr) }
321    }
322
323    /// Returns a copy of the region offset by the vector (`d.x`, `d.y`).
324    ///
325    /// - `d` offset vector
326    #[must_use]
327    pub fn translated(&self, d: impl Into<IVector>) -> Self {
328        let mut r = self.clone();
329        r.translate(d);
330        r
331    }
332
333    /// Replaces the region with the result of the region `op` `rect`. Returns true if the replaced
334    /// region is not empty.
335    ///
336    /// - `rect` rectangle operand
337    /// - `op` logical operation
338    pub fn op_rect(&mut self, rect: impl AsRef<IRect>, op: RegionOp) -> bool {
339        let self_ptr = self.native_mut() as *const _;
340        unsafe { self.native_mut().op1(self_ptr, rect.as_ref().native(), op) }
341    }
342
343    /// Replaces the region with the result of the region `op` `region`. Returns true if the
344    /// replaced region is not empty.
345    ///
346    /// - `region` region operand
347    /// - `op` logical operation
348    ///
349    /// Example (C++): <https://fiddle.skia.org/c/@Region_op_6>
350    pub fn op_region(&mut self, region: &Region, op: RegionOp) -> bool {
351        let self_ptr = self.native_mut() as *const _;
352        unsafe { self.native_mut().op2(self_ptr, region.native(), op) }
353    }
354
355    /// Replaces the region with the result of `rect` `op` `region`. Returns true if the replaced
356    /// region is not empty.
357    ///
358    /// - `rect` rectangle operand
359    /// - `region` region operand
360    /// - `op` logical operation
361    ///
362    /// Example (C++): <https://fiddle.skia.org/c/@Region_op_4>
363    pub fn op_rect_region(
364        &mut self,
365        rect: impl AsRef<IRect>,
366        region: &Region,
367        op: RegionOp,
368    ) -> bool {
369        unsafe {
370            self.native_mut()
371                .op(rect.as_ref().native(), region.native(), op)
372        }
373    }
374
375    /// Replaces the region with the result of `region` `op` `rect`. Returns true if the replaced
376    /// region is not empty.
377    ///
378    /// - `region` region operand
379    /// - `rect` rectangle operand
380    /// - `op` logical operation
381    ///
382    /// Example (C++): <https://fiddle.skia.org/c/@Region_op_5>
383    pub fn op_region_rect(
384        &mut self,
385        region: &Region,
386        rect: impl AsRef<IRect>,
387        op: RegionOp,
388    ) -> bool {
389        unsafe {
390            self.native_mut()
391                .op1(region.native(), rect.as_ref().native(), op)
392        }
393    }
394
395    /// Writes the region to `buf`, and returns the number of bytes written.
396    ///
397    /// - `buf` storage for binary data
398    ///
399    /// Example (C++): <https://fiddle.skia.org/c/@Region_writeToMemory>
400    pub fn write_to_memory(&self, buf: &mut Vec<u8>) {
401        unsafe {
402            let size = self.native().writeToMemory(ptr::null_mut());
403            buf.resize(size, 0);
404            let written = self.native().writeToMemory(buf.as_mut_ptr() as _);
405            debug_assert!(written == size);
406        }
407    }
408
409    /// Constructs the region from `buf` of size `buf.len()`. Returns the bytes read. The returned
410    /// value will be a multiple of four or zero if the length was too small.
411    ///
412    /// - `buf` storage for binary data
413    ///
414    /// Example (C++): <https://fiddle.skia.org/c/@Region_readFromMemory>
415    pub fn read_from_memory(&mut self, buf: &[u8]) -> usize {
416        unsafe {
417            self.native_mut()
418                .readFromMemory(buf.as_ptr() as _, buf.len())
419        }
420    }
421}
422
423//
424// combine overloads (static)
425//
426
427pub trait Combine<A, B>: Sized {
428    fn combine(a: &A, op: RegionOp, b: &B) -> Self;
429
430    fn difference(a: &A, b: &B) -> Self {
431        Self::combine(a, RegionOp::Difference, b)
432    }
433
434    fn intersect(a: &A, b: &B) -> Self {
435        Self::combine(a, RegionOp::Intersect, b)
436    }
437
438    fn xor(a: &A, b: &B) -> Self {
439        Self::combine(a, RegionOp::XOR, b)
440    }
441
442    fn union(a: &A, b: &B) -> Self {
443        Self::combine(a, RegionOp::Union, b)
444    }
445
446    fn reverse_difference(a: &A, b: &B) -> Self {
447        Self::combine(a, RegionOp::ReverseDifference, b)
448    }
449
450    fn replace(a: &A, b: &B) -> Self {
451        Self::combine(a, RegionOp::Replace, b)
452    }
453}
454
455impl Combine<IRect, Region> for Handle<SkRegion> {
456    fn combine(rect: &IRect, op: RegionOp, region: &Region) -> Self {
457        let mut r = Region::new();
458        r.op_rect_region(rect, region, op);
459        r
460    }
461}
462
463impl Combine<Region, IRect> for Handle<SkRegion> {
464    fn combine(region: &Region, op: RegionOp, rect: &IRect) -> Self {
465        let mut r = Region::new();
466        r.op_region_rect(region, rect, op);
467        r
468    }
469}
470
471impl Combine<Region, Region> for Handle<SkRegion> {
472    fn combine(a: &Region, op: RegionOp, b: &Region) -> Self {
473        let mut a = a.clone();
474        a.op_region(b, op);
475        a
476    }
477}
478
479//
480// intersects overloads
481//
482
483pub trait Intersects<T> {
484    fn intersects(&self, other: &T) -> bool;
485}
486
487impl Intersects<IRect> for Region {
488    fn intersects(&self, rect: &IRect) -> bool {
489        self.intersects_rect(rect)
490    }
491}
492
493impl Intersects<Region> for Region {
494    fn intersects(&self, other: &Region) -> bool {
495        self.intersects_region(other)
496    }
497}
498
499//
500// contains overloads
501//
502
503impl Contains<IPoint> for Region {
504    fn contains(&self, point: IPoint) -> bool {
505        self.contains_point(point)
506    }
507}
508
509impl Contains<&IRect> for Region {
510    fn contains(&self, rect: &IRect) -> bool {
511        self.contains_rect(rect)
512    }
513}
514
515impl Contains<&Region> for Region {
516    fn contains(&self, other: &Region) -> bool {
517        self.contains_region(other)
518    }
519}
520
521//
522// quick_reject overloads
523//
524
525impl QuickReject<IRect> for Region {
526    fn quick_reject(&self, rect: &IRect) -> bool {
527        self.quick_reject_rect(rect)
528    }
529}
530
531impl QuickReject<Region> for Region {
532    fn quick_reject(&self, other: &Region) -> bool {
533        self.quick_reject_region(other)
534    }
535}
536
537#[derive(Clone)]
538#[repr(transparent)]
539/// Goes through the region one rectangle at a time. For each "strip" of one or more contiguous
540/// Y values (scanlines) in ascending order, the iterator returns each rectangle in that strip
541/// (from left to right) before advancing to the next strip (which may or may not have a gap).
542pub struct Iterator<'a>(SkRegion_Iterator, PhantomData<&'a Region>);
543
544native_transmutable!(SkRegion_Iterator, Iterator<'_>);
545
546impl fmt::Debug for Iterator<'_> {
547    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
548        f.debug_struct("Iterator")
549            .field("is_done", &self.is_done())
550            .field("rect", self.rect())
551            .finish()
552    }
553}
554
555impl<'a> Iterator<'a> {
556    /// Initializes an iterator with an empty region. [`Self::is_done()`] on the iterator returns
557    /// true. Call [`Self::reset()`] to initialize the iterator at a later time.
558    pub fn new_empty() -> Self {
559        Iterator::construct(|iterator| unsafe {
560            sb::C_SkRegion_Iterator_Construct(iterator);
561        })
562    }
563
564    /// Sets the iterator to return elements of the region's rectangle array.
565    ///
566    /// - `region` region to iterate
567    ///
568    /// Example (C++): <https://fiddle.skia.org/c/@Region_Iterator_copy_const_SkRegion>
569    pub fn new(region: &'a Region) -> Iterator<'a> {
570        Iterator::from_native_c(unsafe { SkRegion_Iterator::new(region.native()) })
571    }
572
573    /// Moves the iterator to the start of the region. Returns true if the region was set;
574    /// otherwise, returns false.
575    ///
576    /// Example (C++): <https://fiddle.skia.org/c/@Region_Iterator_rewind>
577    pub fn rewind(&mut self) -> bool {
578        unsafe { self.native_mut().rewind() }
579    }
580
581    /// Resets the iterator, using the new region.
582    ///
583    /// - `region` region to iterate
584    ///
585    /// Example (C++): <https://fiddle.skia.org/c/@Region_Iterator_reset>
586    pub fn reset(mut self, region: &Region) -> Iterator {
587        unsafe {
588            self.native_mut().reset(region.native());
589            mem::transmute(self)
590        }
591    }
592
593    /// Returns true if the iterator is pointing to the final rectangle in the region.
594    pub fn is_done(&self) -> bool {
595        self.native().fDone
596    }
597
598    /// Advances the iterator to the next rectangle in the region if it is not done. This moves to
599    /// the next rectangle to the right within the current horizontal strip. If the end of the strip
600    /// is reached, it automatically advances to the first rectangle in the next strip, skipping any
601    /// vertical gaps.
602    ///
603    /// Example (C++): <https://fiddle.skia.org/c/@Region_Iterator_next>
604    pub fn next(&mut self) {
605        unsafe {
606            self.native_mut().next();
607        }
608    }
609
610    /// Returns the rectangle element in the region. Does not return predictable results if the
611    /// region is empty.
612    pub fn rect(&self) -> &IRect {
613        IRect::from_native_ref(&self.native().fRect)
614    }
615
616    /// Returns the region if set; otherwise, returns `None`.
617    pub fn rgn(&self) -> Option<&Region> {
618        unsafe {
619            let r = sb::C_SkRegion_Iterator_rgn(self.native()).into_non_null()?;
620            Some(Region::from_native_ref(r.as_ref()))
621        }
622    }
623}
624
625impl iter::Iterator for Iterator<'_> {
626    type Item = IRect;
627
628    fn next(&mut self) -> Option<Self::Item> {
629        if self.is_done() {
630            return None;
631        }
632        let r = *self.rect();
633        Iterator::next(self);
634        Some(r)
635    }
636}
637
638#[test]
639fn test_iterator() {
640    let r1 = IRect::new(10, 10, 12, 14);
641    let r2 = IRect::new(100, 100, 120, 140);
642    let mut r = Region::new();
643    r.set_rects(&[r1, r2]);
644    let rects: Vec<IRect> = Iterator::new(&r).collect();
645    assert_eq!(rects.len(), 2);
646    assert_eq!(rects[0], r1);
647    assert_eq!(rects[1], r2);
648}
649
650#[derive(Clone)]
651#[repr(transparent)]
652/// Returns the sequence of rectangles, sorted along the y-axis, then the x-axis, that make up the
653/// region intersected with the specified clip rectangle.
654pub struct Cliperator<'a>(SkRegion_Cliperator, PhantomData<&'a Region>);
655
656native_transmutable!(SkRegion_Cliperator, Cliperator<'_>);
657
658impl Drop for Cliperator<'_> {
659    fn drop(&mut self) {
660        unsafe { sb::C_SkRegion_Cliperator_destruct(self.native_mut()) }
661    }
662}
663
664impl fmt::Debug for Cliperator<'_> {
665    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
666        f.debug_struct("Cliperator")
667            .field("is_done", &self.is_done())
668            .field("rect", &self.rect())
669            .finish()
670    }
671}
672
673impl<'a> Cliperator<'a> {
674    /// Sets the cliperator to return elements of the region's rectangle array within `clip`.
675    ///
676    /// - `region` region to iterate
677    /// - `clip` bounds of iteration
678    ///
679    /// Example (C++): <https://fiddle.skia.org/c/@Region_Cliperator_const_SkRegion_const_SkIRect>
680    pub fn new(region: &'a Region, clip: impl AsRef<IRect>) -> Cliperator<'a> {
681        Cliperator::from_native_c(unsafe {
682            SkRegion_Cliperator::new(region.native(), clip.as_ref().native())
683        })
684    }
685
686    /// Returns true if the cliperator is pointing to the final rectangle in the region.
687    pub fn is_done(&self) -> bool {
688        self.native().fDone
689    }
690
691    /// Advances the iterator to the next rectangle in the region contained by the clip.
692    ///
693    /// Example (C++): <https://fiddle.skia.org/c/@Region_Cliperator_next>
694    pub fn next(&mut self) {
695        unsafe { self.native_mut().next() }
696    }
697
698    /// Returns the rectangle element in the region, intersected with the clip passed to
699    /// [`Self::new()`]. Does not return predictable results if the region is empty.
700    pub fn rect(&self) -> &IRect {
701        IRect::from_native_ref(&self.native().fRect)
702    }
703}
704
705impl iter::Iterator for Cliperator<'_> {
706    type Item = IRect;
707    fn next(&mut self) -> Option<Self::Item> {
708        if self.is_done() {
709            return None;
710        }
711        let rect = *self.rect();
712        self.next();
713        Some(rect)
714    }
715}
716
717#[derive(Clone)]
718#[repr(transparent)]
719/// Returns the line segment ends within the region that intersect a horizontal line.
720pub struct Spanerator<'a>(SkRegion_Spanerator, PhantomData<&'a Region>);
721
722native_transmutable!(SkRegion_Spanerator, Spanerator<'_>);
723
724impl Drop for Spanerator<'_> {
725    fn drop(&mut self) {
726        unsafe { sb::C_SkRegion_Spanerator_destruct(self.native_mut()) }
727    }
728}
729
730impl fmt::Debug for Spanerator<'_> {
731    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
732        f.debug_struct("Spanerator").finish()
733    }
734}
735
736impl<'a> Spanerator<'a> {
737    /// Sets the spanerator to return line segments in the region on the scan line.
738    ///
739    /// - `region` region to iterate
740    /// - `y` horizontal line to intersect
741    /// - `left` bounds of iteration
742    /// - `right` bounds of iteration
743    ///
744    /// Example (C++): <https://fiddle.skia.org/c/@Region_Spanerator_const_SkRegion_int_int_int>
745    pub fn new(region: &'a Region, y: i32, left: i32, right: i32) -> Spanerator<'a> {
746        Spanerator::from_native_c(unsafe {
747            SkRegion_Spanerator::new(region.native(), y, left, right)
748        })
749    }
750}
751
752impl iter::Iterator for Spanerator<'_> {
753    type Item = (i32, i32);
754
755    /// Advances the iterator to the next span intersecting the region within the line segment
756    /// provided in the constructor. Returns the `(left, right)` span if an interval was found.
757    ///
758    /// Example (C++): <https://fiddle.skia.org/c/@Region_Spanerator_next>
759    fn next(&mut self) -> Option<Self::Item> {
760        unsafe {
761            let mut left = 0;
762            let mut right = 0;
763            self.native_mut()
764                .next(&mut left, &mut right)
765                .then_some((left, right))
766        }
767    }
768}
769
770#[test]
771fn new_clone_drop() {
772    let region = Region::new();
773    #[allow(clippy::redundant_clone)]
774    let _cloned = region.clone();
775}
776
777#[test]
778fn can_compare() {
779    let r1 = Region::new();
780    #[allow(clippy::redundant_clone)]
781    let r2 = r1.clone();
782    assert!(r1 == r2);
783}