re_log_types/
example_components.rs

1//! Example components to be used for tests and docs
2
3use std::sync::Arc;
4
5use re_arrow_util::ArrowArrayDowncastRef as _;
6use re_byte_size::SizeBytes;
7use re_types_core::{
8    Component, ComponentDescriptor, ComponentName, DeserializationError, Loggable,
9    SerializedComponentBatch,
10};
11
12// ----------------------------------------------------------------------------
13
14#[derive(Debug, Default)]
15pub struct MyPoints {
16    pub points: Option<SerializedComponentBatch>,
17    pub colors: Option<SerializedComponentBatch>,
18    pub labels: Option<SerializedComponentBatch>,
19}
20
21impl MyPoints {
22    pub const NUM_COMPONENTS: usize = 5;
23}
24
25impl MyPoints {
26    pub fn new(points: impl IntoIterator<Item = impl Into<MyPoint>>) -> Self {
27        Self {
28            points: re_types_core::try_serialize_field(Self::descriptor_points(), points),
29            ..Self::default()
30        }
31    }
32
33    pub fn descriptor_points() -> ComponentDescriptor {
34        ComponentDescriptor {
35            archetype_name: Some("example.MyPoints".into()),
36            archetype_field_name: Some("points".into()),
37            component_name: MyPoint::name(),
38        }
39    }
40
41    pub fn descriptor_colors() -> ComponentDescriptor {
42        ComponentDescriptor {
43            archetype_name: Some("example.MyPoints".into()),
44            archetype_field_name: Some("colors".into()),
45            component_name: MyColor::name(),
46        }
47    }
48
49    pub fn descriptor_labels() -> ComponentDescriptor {
50        ComponentDescriptor {
51            archetype_name: Some("example.MyPoints".into()),
52            archetype_field_name: Some("labels".into()),
53            component_name: MyLabel::name(),
54        }
55    }
56
57    pub fn descriptor_indicator() -> ComponentDescriptor {
58        ComponentDescriptor {
59            archetype_name: Some("example.MyPoints".into()),
60            component_name: "rerun.components.MyPointsIndicator".into(),
61            archetype_field_name: None,
62        }
63    }
64
65    pub fn update_fields() -> Self {
66        Self::default()
67    }
68
69    pub fn clear_fields() -> Self {
70        Self {
71            points: Some(SerializedComponentBatch::new(
72                MyPoint::arrow_empty(),
73                Self::descriptor_points(),
74            )),
75            colors: Some(SerializedComponentBatch::new(
76                MyColor::arrow_empty(),
77                Self::descriptor_colors(),
78            )),
79            labels: Some(SerializedComponentBatch::new(
80                MyLabel::arrow_empty(),
81                Self::descriptor_labels(),
82            )),
83        }
84    }
85
86    #[inline]
87    pub fn with_labels(mut self, labels: impl IntoIterator<Item = impl Into<MyLabel>>) -> Self {
88        self.labels = re_types_core::try_serialize_field(Self::descriptor_labels(), labels);
89        self
90    }
91
92    #[inline]
93    pub fn with_colors(mut self, colors: impl IntoIterator<Item = impl Into<MyColor>>) -> Self {
94        self.colors = re_types_core::try_serialize_field(Self::descriptor_colors(), colors);
95        self
96    }
97}
98
99impl re_types_core::Archetype for MyPoints {
100    type Indicator = re_types_core::GenericIndicatorComponent<Self>;
101
102    fn indicator() -> SerializedComponentBatch {
103        use re_types_core::ComponentBatch as _;
104        // These is no such thing as failing to serialized an indicator.
105        #[allow(clippy::unwrap_used)]
106        Self::Indicator::DEFAULT
107            .serialized(Self::descriptor_indicator())
108            .unwrap()
109    }
110
111    fn name() -> re_types_core::ArchetypeName {
112        "example.MyPoints".into()
113    }
114
115    fn display_name() -> &'static str {
116        "MyPoints"
117    }
118
119    fn required_components() -> ::std::borrow::Cow<'static, [re_types_core::ComponentDescriptor]> {
120        vec![Self::descriptor_points()].into()
121    }
122
123    fn recommended_components() -> std::borrow::Cow<'static, [re_types_core::ComponentDescriptor]> {
124        vec![
125            Self::descriptor_indicator(),
126            Self::descriptor_colors(),
127            Self::descriptor_labels(),
128        ]
129        .into()
130    }
131}
132
133impl ::re_types_core::AsComponents for MyPoints {
134    #[inline]
135    fn as_serialized_batches(&self) -> Vec<SerializedComponentBatch> {
136        use ::re_types_core::Archetype as _;
137        [
138            Some(Self::indicator()),
139            self.colors.clone(),
140            self.labels.clone(),
141            self.points.clone(),
142        ]
143        .into_iter()
144        .flatten()
145        .collect()
146    }
147}
148
149// ----------------------------------------------------------------------------
150
151#[derive(Clone, Copy, Debug, Default, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
152#[repr(C)]
153pub struct MyPoint {
154    pub x: f32,
155    pub y: f32,
156}
157
158impl MyPoint {
159    #[allow(clippy::should_implement_trait)]
160    #[inline]
161    pub fn from_iter(it: impl IntoIterator<Item = u32>) -> Vec<Self> {
162        it.into_iter()
163            .map(|i| Self::new(i as f32, i as f32))
164            .collect()
165    }
166}
167
168impl MyPoint {
169    #[inline]
170    pub fn new(x: f32, y: f32) -> Self {
171        Self { x, y }
172    }
173}
174
175re_types_core::macros::impl_into_cow!(MyPoint);
176
177impl SizeBytes for MyPoint {
178    #[inline]
179    fn heap_size_bytes(&self) -> u64 {
180        let Self { x: _, y: _ } = self;
181        0
182    }
183}
184
185impl Loggable for MyPoint {
186    fn arrow_datatype() -> arrow::datatypes::DataType {
187        use arrow::datatypes::DataType::Float32;
188        arrow::datatypes::DataType::Struct(arrow::datatypes::Fields::from(vec![
189            arrow::datatypes::Field::new("x", Float32, false),
190            arrow::datatypes::Field::new("y", Float32, false),
191        ]))
192    }
193
194    fn to_arrow_opt<'a>(
195        data: impl IntoIterator<Item = Option<impl Into<std::borrow::Cow<'a, Self>>>>,
196    ) -> re_types_core::SerializationResult<arrow::array::ArrayRef>
197    where
198        Self: 'a,
199    {
200        use arrow::datatypes::DataType::Float32;
201
202        let (xs, ys): (Vec<_>, Vec<_>) = data
203            .into_iter()
204            .map(Option::unwrap)
205            .map(Into::into)
206            .map(|p| (p.x, p.y))
207            .unzip();
208
209        let x_array = Arc::new(arrow::array::Float32Array::from(xs));
210        let y_array = Arc::new(arrow::array::Float32Array::from(ys));
211
212        Ok(Arc::new(arrow::array::StructArray::new(
213            arrow::datatypes::Fields::from(vec![
214                arrow::datatypes::Field::new("x", Float32, false),
215                arrow::datatypes::Field::new("y", Float32, false),
216            ]),
217            vec![x_array, y_array],
218            None,
219        )))
220    }
221
222    fn from_arrow_opt(
223        data: &dyn arrow::array::Array,
224    ) -> re_types_core::DeserializationResult<Vec<Option<Self>>> {
225        let array = data
226            .downcast_array_ref::<arrow::array::StructArray>()
227            .ok_or(DeserializationError::downcast_error::<
228                arrow::array::StructArray,
229            >())?;
230
231        let x_array = array.columns()[0].as_ref();
232        let y_array = array.columns()[1].as_ref();
233
234        let xs = x_array
235            .downcast_array_ref::<arrow::array::Float32Array>()
236            .ok_or(DeserializationError::downcast_error::<
237                arrow::array::Float32Array,
238            >())?;
239        let ys = y_array
240            .downcast_array_ref::<arrow::array::Float32Array>()
241            .ok_or(DeserializationError::downcast_error::<
242                arrow::array::Float32Array,
243            >())?;
244
245        Ok(xs
246            .iter()
247            .zip(ys.iter())
248            .map(|(x, y)| {
249                if let (Some(x), Some(y)) = (x, y) {
250                    Some(Self { x, y })
251                } else {
252                    None
253                }
254            })
255            .collect())
256    }
257}
258
259impl Component for MyPoint {
260    fn name() -> ComponentName {
261        "example.MyPoint".into()
262    }
263}
264
265// ----------------------------------------------------------------------------
266
267#[derive(Clone, Copy, Debug, Default, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
268#[repr(C)]
269pub struct MyPoint64 {
270    pub x: f64,
271    pub y: f64,
272}
273
274impl MyPoint64 {
275    #[allow(clippy::should_implement_trait)]
276    #[inline]
277    pub fn from_iter(it: impl IntoIterator<Item = u64>) -> Vec<Self> {
278        it.into_iter()
279            .map(|i| Self::new(i as f64, i as f64))
280            .collect()
281    }
282
283    #[inline]
284    pub fn partial_descriptor() -> ComponentDescriptor {
285        ComponentDescriptor::new(Self::name())
286    }
287}
288
289impl MyPoint64 {
290    #[inline]
291    pub fn new(x: f64, y: f64) -> Self {
292        Self { x, y }
293    }
294}
295
296re_types_core::macros::impl_into_cow!(MyPoint64);
297
298impl SizeBytes for MyPoint64 {
299    #[inline]
300    fn heap_size_bytes(&self) -> u64 {
301        let Self { x: _, y: _ } = self;
302        0
303    }
304}
305
306impl Loggable for MyPoint64 {
307    fn arrow_datatype() -> arrow::datatypes::DataType {
308        use arrow::datatypes::DataType::Float64;
309        arrow::datatypes::DataType::Struct(arrow::datatypes::Fields::from(vec![
310            arrow::datatypes::Field::new("x", Float64, false),
311            arrow::datatypes::Field::new("y", Float64, false),
312        ]))
313    }
314
315    fn to_arrow_opt<'a>(
316        data: impl IntoIterator<Item = Option<impl Into<std::borrow::Cow<'a, Self>>>>,
317    ) -> re_types_core::SerializationResult<arrow::array::ArrayRef>
318    where
319        Self: 'a,
320    {
321        use arrow::datatypes::DataType::Float64;
322
323        let (xs, ys): (Vec<_>, Vec<_>) = data
324            .into_iter()
325            .map(Option::unwrap)
326            .map(Into::into)
327            .map(|p| (p.x, p.y))
328            .unzip();
329
330        let x_array = Arc::new(arrow::array::Float64Array::from(xs));
331        let y_array = Arc::new(arrow::array::Float64Array::from(ys));
332
333        Ok(Arc::new(arrow::array::StructArray::new(
334            arrow::datatypes::Fields::from(vec![
335                arrow::datatypes::Field::new("x", Float64, false),
336                arrow::datatypes::Field::new("y", Float64, false),
337            ]),
338            vec![x_array, y_array],
339            None,
340        )))
341    }
342
343    fn from_arrow_opt(
344        data: &dyn arrow::array::Array,
345    ) -> re_types_core::DeserializationResult<Vec<Option<Self>>> {
346        let array = data
347            .downcast_array_ref::<arrow::array::StructArray>()
348            .ok_or(DeserializationError::downcast_error::<
349                arrow::array::StructArray,
350            >())?;
351
352        let x_array = array.columns()[0].as_ref();
353        let y_array = array.columns()[1].as_ref();
354
355        let xs = x_array
356            .downcast_array_ref::<arrow::array::Float64Array>()
357            .ok_or(DeserializationError::downcast_error::<
358                arrow::array::Float64Array,
359            >())?;
360        let ys = y_array
361            .downcast_array_ref::<arrow::array::Float64Array>()
362            .ok_or(DeserializationError::downcast_error::<
363                arrow::array::Float64Array,
364            >())?;
365
366        Ok(xs
367            .iter()
368            .zip(ys.iter())
369            .map(|(x, y)| {
370                if let (Some(x), Some(y)) = (x, y) {
371                    Some(Self { x, y })
372                } else {
373                    None
374                }
375            })
376            .collect())
377    }
378}
379
380impl Component for MyPoint64 {
381    fn name() -> ComponentName {
382        "example.MyPoint64".into()
383    }
384}
385
386// ----------------------------------------------------------------------------
387
388#[derive(Clone, Copy, Debug, PartialEq, Eq, bytemuck::Pod, bytemuck::Zeroable)]
389#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
390#[repr(transparent)]
391pub struct MyColor(pub u32);
392
393impl MyColor {
394    #[allow(clippy::should_implement_trait)]
395    #[inline]
396    pub fn from_iter(it: impl IntoIterator<Item = u32>) -> Vec<Self> {
397        it.into_iter().map(Self).collect()
398    }
399}
400
401impl MyColor {
402    #[inline]
403    pub fn from_rgb(r: u8, g: u8, b: u8) -> Self {
404        Self(u32::from_le_bytes([r, g, b, 255]))
405    }
406}
407
408impl From<u32> for MyColor {
409    #[inline]
410    fn from(value: u32) -> Self {
411        Self(value)
412    }
413}
414
415re_types_core::macros::impl_into_cow!(MyColor);
416
417impl SizeBytes for MyColor {
418    #[inline]
419    fn heap_size_bytes(&self) -> u64 {
420        let Self(_) = self;
421        0
422    }
423}
424
425impl Loggable for MyColor {
426    fn arrow_datatype() -> arrow::datatypes::DataType {
427        arrow::datatypes::DataType::UInt32
428    }
429
430    fn to_arrow_opt<'a>(
431        data: impl IntoIterator<Item = Option<impl Into<std::borrow::Cow<'a, Self>>>>,
432    ) -> re_types_core::SerializationResult<arrow::array::ArrayRef>
433    where
434        Self: 'a,
435    {
436        use re_types_core::datatypes::UInt32;
437        UInt32::to_arrow_opt(
438            data.into_iter()
439                .map(|opt| opt.map(Into::into).map(|c| UInt32(c.0))),
440        )
441    }
442
443    fn from_arrow_opt(
444        data: &dyn arrow::array::Array,
445    ) -> re_types_core::DeserializationResult<Vec<Option<Self>>> {
446        use re_types_core::datatypes::UInt32;
447        Ok(UInt32::from_arrow_opt(data)?
448            .into_iter()
449            .map(|opt| opt.map(|v| Self(v.0)))
450            .collect())
451    }
452}
453
454impl Component for MyColor {
455    fn name() -> ComponentName {
456        "example.MyColor".into()
457    }
458}
459
460// ----------------------------------------------------------------------------
461
462#[derive(Debug, Clone, PartialEq, Eq)]
463#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
464pub struct MyLabel(pub String);
465
466re_types_core::macros::impl_into_cow!(MyLabel);
467
468impl SizeBytes for MyLabel {
469    #[inline]
470    fn heap_size_bytes(&self) -> u64 {
471        let Self(s) = self;
472        s.heap_size_bytes()
473    }
474}
475
476impl Loggable for MyLabel {
477    fn arrow_datatype() -> arrow::datatypes::DataType {
478        re_types_core::datatypes::Utf8::arrow_datatype()
479    }
480
481    fn to_arrow_opt<'a>(
482        data: impl IntoIterator<Item = Option<impl Into<std::borrow::Cow<'a, Self>>>>,
483    ) -> re_types_core::SerializationResult<arrow::array::ArrayRef>
484    where
485        Self: 'a,
486    {
487        use re_types_core::datatypes::Utf8;
488        Utf8::to_arrow_opt(
489            data.into_iter()
490                .map(|opt| opt.map(Into::into).map(|l| Utf8(l.0.clone().into()))),
491        )
492    }
493
494    fn from_arrow_opt(
495        data: &dyn arrow::array::Array,
496    ) -> re_types_core::DeserializationResult<Vec<Option<Self>>> {
497        use re_types_core::datatypes::Utf8;
498        Ok(Utf8::from_arrow_opt(data)?
499            .into_iter()
500            .map(|opt| opt.map(|v| Self(v.0.to_string())))
501            .collect())
502    }
503}
504
505impl Component for MyLabel {
506    fn name() -> ComponentName {
507        "example.MyLabel".into()
508    }
509}
510
511// ----------------------------------------------------------------------------
512
513#[derive(Clone, Copy, Debug, PartialEq, Eq, bytemuck::Pod, bytemuck::Zeroable)]
514#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
515#[repr(transparent)]
516pub struct MyIndex(pub u64);
517
518impl MyIndex {
519    #[allow(clippy::should_implement_trait)]
520    #[inline]
521    pub fn from_iter(it: impl IntoIterator<Item = u64>) -> Vec<Self> {
522        it.into_iter().map(Self).collect()
523    }
524
525    #[inline]
526    pub fn partial_descriptor() -> ComponentDescriptor {
527        ComponentDescriptor::new(Self::name())
528    }
529}
530
531re_types_core::macros::impl_into_cow!(MyIndex);
532
533impl SizeBytes for MyIndex {
534    #[inline]
535    fn heap_size_bytes(&self) -> u64 {
536        let Self(_) = self;
537        0
538    }
539}
540
541impl Loggable for MyIndex {
542    fn arrow_datatype() -> arrow::datatypes::DataType {
543        arrow::datatypes::DataType::UInt64
544    }
545
546    fn to_arrow_opt<'a>(
547        data: impl IntoIterator<Item = Option<impl Into<std::borrow::Cow<'a, Self>>>>,
548    ) -> re_types_core::SerializationResult<arrow::array::ArrayRef>
549    where
550        Self: 'a,
551    {
552        use re_types_core::datatypes::UInt64;
553        UInt64::to_arrow_opt(
554            data.into_iter()
555                .map(|opt| opt.map(Into::into).map(|c| UInt64(c.0))),
556        )
557    }
558
559    fn from_arrow_opt(
560        data: &dyn arrow::array::Array,
561    ) -> re_types_core::DeserializationResult<Vec<Option<Self>>> {
562        use re_types_core::datatypes::UInt64;
563        Ok(UInt64::from_arrow_opt(data)?
564            .into_iter()
565            .map(|opt| opt.map(|v| Self(v.0)))
566            .collect())
567    }
568}
569
570impl Component for MyIndex {
571    fn name() -> re_types_core::ComponentName {
572        "example.MyIndex".into()
573    }
574}