1use std::fmt;
4
5use crate::ffi;
6use gdk::RGBA;
7use glib::translate::*;
8
9glib::wrapper! {
10 #[doc(alias = "GskColorStop")]
11 pub struct ColorStop(BoxedInline<ffi::GskColorStop>);
12}
13
14impl ColorStop {
15 #[inline]
16 pub fn new(offset: f32, color: RGBA) -> Self {
17 assert_initialized_main_thread!();
18 unsafe {
19 Self::unsafe_from(ffi::GskColorStop {
20 offset,
21 color: *color.to_glib_none().0,
22 })
23 }
24 }
25
26 pub fn builder() -> ColorStopBuilder {
34 ColorStopBuilder::default()
35 }
36
37 #[inline]
38 pub fn offset(&self) -> f32 {
39 self.inner.offset
40 }
41
42 #[inline]
43 pub fn color(&self) -> &RGBA {
44 unsafe { &*(&self.inner.color as *const gdk::ffi::GdkRGBA as *const RGBA) }
45 }
46}
47
48impl fmt::Debug for ColorStop {
49 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
50 f.debug_struct("ColorStop")
51 .field("offset", &self.offset())
52 .field("color", &self.color())
53 .finish()
54 }
55}
56
57#[derive(Clone, Default)]
58#[must_use = "The builder must be built to be used"]
63pub struct ColorStopBuilder(Vec<ColorStop>);
64
65impl ColorStopBuilder {
66 pub fn new() -> Self {
69 Self::default()
70 }
71
72 pub fn at(mut self, offset: f32, color: RGBA) -> Self {
73 self.0.push(ColorStop::new(offset, color));
74 self
75 }
76
77 #[must_use = "Building the object from the builder is usually expensive and is not expected to have side effects"]
80 pub fn build(self) -> Vec<ColorStop> {
81 self.0
82 }
83}
84
85#[test]
86fn color_stop_builder() {
87 let t1 = ColorStop::builder()
88 .at(0.0, gdk::RGBA::RED)
89 .at(0.333, gdk::RGBA::RED)
90 .at(0.667, gdk::RGBA::BLUE)
91 .at(1.0, gdk::RGBA::RED)
92 .build();
93
94 let t2 = &[
95 ColorStop::new(0.0, gdk::RGBA::RED),
96 ColorStop::new(0.333, gdk::RGBA::RED),
97 ColorStop::new(0.667, gdk::RGBA::BLUE),
98 ColorStop::new(1.0, gdk::RGBA::RED),
99 ];
100
101 assert_eq!(t1.len(), t2.len(), "Arrays don't have the same length");
102 assert!(
103 &t1.iter()
104 .zip(t2.iter())
105 .all(|(a, b)| a.offset() == b.offset() && a.color() == b.color()),
106 "Arrays are not equal"
107 );
108}