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