Skip to main content

datafusion_common/
heap_size.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Estimating the heap-allocated memory owned by a value.
6//!
7//! The [`DFHeapSize`] trait reports the number of bytes a value owns on the
8//! heap, **excluding** the stack size of the value itself.
9//!
10//! Implementations need to use [`DFHeapSizeCtx`] that is pushed through every
11//! nested call. The context records which allocations have already been measured
12//! so they are only counted once.
13//!
14//! # Example
15//!
16//! ```
17//! use datafusion_common::heap_size::{DFHeapSize, DFHeapSizeCtx};
18//! use std::sync::Arc;
19//!
20//! let shared: Arc<String> = Arc::new("hello".to_string());
21//! let alias = Arc::clone(&shared);
22//!
23//! let mut ctx = DFHeapSizeCtx::default();
24//! // The shared allocation is counted once even when reached twice.
25//! let total = shared.heap_size(&mut ctx) + alias.heap_size(&mut ctx);
26//! assert_eq!(total, shared.heap_size(&mut DFHeapSizeCtx::default()));
27//! ```
28
29use crate::stats::Precision;
30use crate::{ColumnStatistics, ScalarValue, Statistics, TableReference};
31use arrow::array::{
32    Array, FixedSizeListArray, LargeListArray, LargeListViewArray, ListArray,
33    ListViewArray, MapArray, StructArray,
34};
35use arrow::datatypes::{
36    DataType, Field, Fields, IntervalDayTime, IntervalMonthDayNano, IntervalUnit,
37    Metadata, TimeUnit, UnionFields, UnionMode, i256,
38};
39use chrono::{DateTime, Utc};
40use half::f16;
41use hashbrown::HashSet;
42use std::collections::{BTreeMap, HashMap};
43use std::fmt::Debug;
44use std::sync::Arc;
45
46/// Trait for computing how many bytes a value has allocated on the heap.
47///
48/// Implementations need to use [`DFHeapSizeCtx`] that is pushed through every
49/// nested call. The context records which allocations have already been measured
50/// so they are only counted once.
51///
52pub trait DFHeapSize {
53    /// Return the number of bytes this value has allocated on the heap,
54    /// including heap memory owned transitively by nested values.
55    ///
56    /// Note that the size of the type itself is not included in the result --
57    /// instead, that size is added by the caller (e.g. container).
58    fn heap_size(&self, ctx: &mut DFHeapSizeCtx) -> usize;
59}
60
61#[derive(Default)]
62pub struct DFHeapSizeCtx {
63    seen: HashSet<usize>,
64}
65
66impl DFHeapSizeCtx {
67    fn count_allocation_once(&mut self, ptr: usize) -> bool {
68        self.seen.insert(ptr)
69    }
70}
71
72impl DFHeapSize for Statistics {
73    fn heap_size(&self, ctx: &mut DFHeapSizeCtx) -> usize {
74        self.num_rows.heap_size(ctx)
75            + self.total_byte_size.heap_size(ctx)
76            + self.column_statistics.heap_size(ctx)
77    }
78}
79
80impl DFHeapSize for TableReference {
81    fn heap_size(&self, ctx: &mut DFHeapSizeCtx) -> usize {
82        match self {
83            TableReference::Bare { table } => table.heap_size(ctx),
84            TableReference::Partial { schema, table } => {
85                schema.heap_size(ctx) + table.heap_size(ctx)
86            }
87            TableReference::Full {
88                catalog,
89                schema,
90                table,
91            } => catalog.heap_size(ctx) + schema.heap_size(ctx) + table.heap_size(ctx),
92        }
93    }
94}
95
96impl<T: Debug + Clone + PartialEq + Eq + PartialOrd + DFHeapSize> DFHeapSize
97    for Precision<T>
98{
99    fn heap_size(&self, ctx: &mut DFHeapSizeCtx) -> usize {
100        self.get_value().map_or_else(|| 0, |v| v.heap_size(ctx))
101    }
102}
103
104impl DFHeapSize for ColumnStatistics {
105    fn heap_size(&self, ctx: &mut DFHeapSizeCtx) -> usize {
106        self.null_count.heap_size(ctx)
107            + self.max_value.heap_size(ctx)
108            + self.min_value.heap_size(ctx)
109            + self.sum_value.heap_size(ctx)
110            + self.distinct_count.heap_size(ctx)
111            + self.byte_size.heap_size(ctx)
112    }
113}
114
115impl DFHeapSize for ScalarValue {
116    fn heap_size(&self, ctx: &mut DFHeapSizeCtx) -> usize {
117        use crate::scalar::ScalarValue::*;
118        match self {
119            Null => 0,
120            Boolean(b) => b.heap_size(ctx),
121            Float16(f) => f.heap_size(ctx),
122            Float32(f) => f.heap_size(ctx),
123            Float64(f) => f.heap_size(ctx),
124            Decimal32(a, b, c) => a.heap_size(ctx) + b.heap_size(ctx) + c.heap_size(ctx),
125            Decimal64(a, b, c) => a.heap_size(ctx) + b.heap_size(ctx) + c.heap_size(ctx),
126            Decimal128(a, b, c) => a.heap_size(ctx) + b.heap_size(ctx) + c.heap_size(ctx),
127            Decimal256(a, b, c) => a.heap_size(ctx) + b.heap_size(ctx) + c.heap_size(ctx),
128            Int8(i) => i.heap_size(ctx),
129            Int16(i) => i.heap_size(ctx),
130            Int32(i) => i.heap_size(ctx),
131            Int64(i) => i.heap_size(ctx),
132            UInt8(u) => u.heap_size(ctx),
133            UInt16(u) => u.heap_size(ctx),
134            UInt32(u) => u.heap_size(ctx),
135            UInt64(u) => u.heap_size(ctx),
136            Utf8(u) => u.heap_size(ctx),
137            Utf8View(u) => u.heap_size(ctx),
138            LargeUtf8(l) => l.heap_size(ctx),
139            Binary(b) => b.heap_size(ctx),
140            BinaryView(b) => b.heap_size(ctx),
141            FixedSizeBinary(a, b) => a.heap_size(ctx) + b.heap_size(ctx),
142            LargeBinary(l) => l.heap_size(ctx),
143            FixedSizeList(f) => f.heap_size(ctx),
144            List(l) => l.heap_size(ctx),
145            LargeList(l) => l.heap_size(ctx),
146            Struct(s) => s.heap_size(ctx),
147            Map(m) => m.heap_size(ctx),
148            Date32(d) => d.heap_size(ctx),
149            Date64(d) => d.heap_size(ctx),
150            Time32Second(t) => t.heap_size(ctx),
151            Time32Millisecond(t) => t.heap_size(ctx),
152            Time64Microsecond(t) => t.heap_size(ctx),
153            Time64Nanosecond(t) => t.heap_size(ctx),
154            TimestampSecond(a, b) => a.heap_size(ctx) + b.heap_size(ctx),
155            TimestampMillisecond(a, b) => a.heap_size(ctx) + b.heap_size(ctx),
156            TimestampMicrosecond(a, b) => a.heap_size(ctx) + b.heap_size(ctx),
157            TimestampNanosecond(a, b) => a.heap_size(ctx) + b.heap_size(ctx),
158            IntervalYearMonth(i) => i.heap_size(ctx),
159            IntervalDayTime(i) => i.heap_size(ctx),
160            IntervalMonthDayNano(i) => i.heap_size(ctx),
161            DurationSecond(d) => d.heap_size(ctx),
162            DurationMillisecond(d) => d.heap_size(ctx),
163            DurationMicrosecond(d) => d.heap_size(ctx),
164            DurationNanosecond(d) => d.heap_size(ctx),
165            Union(a, b, c) => a.heap_size(ctx) + b.heap_size(ctx) + c.heap_size(ctx),
166            Dictionary(a, b) => a.heap_size(ctx) + b.heap_size(ctx),
167            RunEndEncoded(a, b, c) => {
168                a.heap_size(ctx) + b.heap_size(ctx) + c.heap_size(ctx)
169            }
170            ListView(a) => a.heap_size(ctx),
171            LargeListView(a) => a.heap_size(ctx),
172        }
173    }
174}
175
176impl DFHeapSize for DataType {
177    fn heap_size(&self, ctx: &mut DFHeapSizeCtx) -> usize {
178        use DataType::*;
179        match self {
180            Null => 0,
181            Boolean => 0,
182            Int8 => 0,
183            Int16 => 0,
184            Int32 => 0,
185            Int64 => 0,
186            UInt8 => 0,
187            UInt16 => 0,
188            UInt32 => 0,
189            UInt64 => 0,
190            Float16 => 0,
191            Float32 => 0,
192            Float64 => 0,
193            Timestamp(t, s) => t.heap_size(ctx) + s.heap_size(ctx),
194            Date32 => 0,
195            Date64 => 0,
196            Time32(t) => t.heap_size(ctx),
197            Time64(t) => t.heap_size(ctx),
198            Duration(t) => t.heap_size(ctx),
199            Interval(i) => i.heap_size(ctx),
200            Binary => 0,
201            FixedSizeBinary(i) => i.heap_size(ctx),
202            LargeBinary => 0,
203            BinaryView => 0,
204            Utf8 => 0,
205            LargeUtf8 => 0,
206            Utf8View => 0,
207            List(v) => v.heap_size(ctx),
208            ListView(v) => v.heap_size(ctx),
209            FixedSizeList(f, i) => f.heap_size(ctx) + i.heap_size(ctx),
210            LargeList(l) => l.heap_size(ctx),
211            LargeListView(l) => l.heap_size(ctx),
212            Struct(s) => s.heap_size(ctx),
213            Union(u, m) => u.heap_size(ctx) + m.heap_size(ctx),
214            Dictionary(a, b) => a.heap_size(ctx) + b.heap_size(ctx),
215            Decimal32(p, s) => p.heap_size(ctx) + s.heap_size(ctx),
216            Decimal64(p, s) => p.heap_size(ctx) + s.heap_size(ctx),
217            Decimal128(p, s) => p.heap_size(ctx) + s.heap_size(ctx),
218            Decimal256(p, s) => p.heap_size(ctx) + s.heap_size(ctx),
219            Map(m, b) => m.heap_size(ctx) + b.heap_size(ctx),
220            RunEndEncoded(a, b) => a.heap_size(ctx) + b.heap_size(ctx),
221        }
222    }
223}
224
225impl<T: DFHeapSize> DFHeapSize for Vec<T> {
226    fn heap_size(&self, ctx: &mut DFHeapSizeCtx) -> usize {
227        let item_size = size_of::<T>();
228        // account for the contents of the Vec
229        (self.capacity() * item_size) +
230            // add any heap allocations by contents
231            self.iter().map(|t| t.heap_size(ctx)).sum::<usize>()
232    }
233}
234
235impl<K: DFHeapSize, V: DFHeapSize> DFHeapSize for HashMap<K, V> {
236    fn heap_size(&self, ctx: &mut DFHeapSizeCtx) -> usize {
237        let capacity = self.capacity();
238        if capacity == 0 {
239            return 0;
240        }
241
242        // HashMap doesn't provide a way to get its heap size, so this is an approximation based on
243        // the behavior of hashbrown::HashMap as at version 0.16.0, and may become inaccurate
244        // if the implementation changes.
245        let key_val_size = size_of::<(K, V)>();
246        // Overhead for the control tags group, which may be smaller depending on architecture
247        let group_size = 16;
248        // 1 byte of metadata stored per bucket.
249        let metadata_size = 1;
250
251        // Compute the number of buckets for the capacity. Based on hashbrown's capacity_to_buckets
252        let buckets = if capacity < 15 {
253            let min_cap = match key_val_size {
254                0..=1 => 14,
255                2..=3 => 7,
256                _ => 3,
257            };
258            let cap = min_cap.max(capacity);
259            if cap < 4 {
260                4
261            } else if cap < 8 {
262                8
263            } else {
264                16
265            }
266        } else {
267            (capacity.saturating_mul(8) / 7).next_power_of_two()
268        };
269
270        group_size
271            + (buckets * (key_val_size + metadata_size))
272            + self.keys().map(|k| k.heap_size(ctx)).sum::<usize>()
273            + self.values().map(|v| v.heap_size(ctx)).sum::<usize>()
274    }
275}
276
277fn arc_ptr<T>(arc: &Arc<T>) -> usize {
278    Arc::as_ptr(arc) as usize
279}
280
281/// For unsized types, `Arc::as_ptr` returns the data address + metadata - we only need the thin address
282/// Casting through `*const i32` gets us the thin pointer
283fn arc_unsized_ptr<T: ?Sized>(arc: &Arc<T>) -> usize {
284    Arc::as_ptr(arc).cast::<i32>() as usize
285}
286
287impl<T: DFHeapSize> DFHeapSize for Arc<T> {
288    fn heap_size(&self, ctx: &mut DFHeapSizeCtx) -> usize {
289        let ptr = arc_ptr(self);
290
291        if !ctx.count_allocation_once(ptr) {
292            return 0;
293        }
294
295        // Arc stores weak and strong counts on the heap alongside an instance of T
296        2 * size_of::<usize>() + size_of::<T>() + self.as_ref().heap_size(ctx)
297    }
298}
299
300impl DFHeapSize for Arc<str> {
301    fn heap_size(&self, ctx: &mut DFHeapSizeCtx) -> usize {
302        let ptr = arc_unsized_ptr(self);
303
304        if !ctx.count_allocation_once(ptr) {
305            return 0;
306        }
307
308        // Arc stores weak and strong counts on the heap alongside an instance of T
309        2 * size_of::<usize>() + self.as_ref().heap_size(ctx)
310    }
311}
312
313impl DFHeapSize for Arc<dyn DFHeapSize> {
314    fn heap_size(&self, ctx: &mut DFHeapSizeCtx) -> usize {
315        let ptr = arc_unsized_ptr(self);
316
317        if !ctx.count_allocation_once(ptr) {
318            return 0;
319        }
320
321        // Arc stores weak and strong counts on the heap alongside an instance of T
322        2 * size_of::<usize>() + size_of_val(self.as_ref()) + self.as_ref().heap_size(ctx)
323    }
324}
325
326impl DFHeapSize for Fields {
327    fn heap_size(&self, ctx: &mut DFHeapSizeCtx) -> usize {
328        self.into_iter().map(|f| f.heap_size(ctx)).sum::<usize>()
329    }
330}
331
332impl<T: DFHeapSize> DFHeapSize for Box<T> {
333    fn heap_size(&self, ctx: &mut DFHeapSizeCtx) -> usize {
334        size_of::<T>() + self.as_ref().heap_size(ctx)
335    }
336}
337
338impl<T: DFHeapSize> DFHeapSize for Option<T> {
339    fn heap_size(&self, ctx: &mut DFHeapSizeCtx) -> usize {
340        self.as_ref().map(|inner| inner.heap_size(ctx)).unwrap_or(0)
341    }
342}
343
344impl<A, B> DFHeapSize for (A, B)
345where
346    A: DFHeapSize,
347    B: DFHeapSize,
348{
349    fn heap_size(&self, ctx: &mut DFHeapSizeCtx) -> usize {
350        self.0.heap_size(ctx) + self.1.heap_size(ctx)
351    }
352}
353
354impl<A, B, C> DFHeapSize for (A, B, C)
355where
356    A: DFHeapSize,
357    B: DFHeapSize,
358    C: DFHeapSize,
359{
360    fn heap_size(&self, ctx: &mut DFHeapSizeCtx) -> usize {
361        self.0.heap_size(ctx) + self.1.heap_size(ctx) + self.2.heap_size(ctx)
362    }
363}
364
365impl DFHeapSize for String {
366    fn heap_size(&self, _: &mut DFHeapSizeCtx) -> usize {
367        self.capacity()
368    }
369}
370
371impl DFHeapSize for str {
372    fn heap_size(&self, _: &mut DFHeapSizeCtx) -> usize {
373        // Internal accounting helper for owners like Arc<str>
374        self.len()
375    }
376}
377
378impl DFHeapSize for UnionFields {
379    fn heap_size(&self, ctx: &mut DFHeapSizeCtx) -> usize {
380        self.iter()
381            .map(|f| f.0.heap_size(ctx) + f.1.heap_size(ctx))
382            .sum()
383    }
384}
385
386impl<K: DFHeapSize, V: DFHeapSize> DFHeapSize for BTreeMap<K, V> {
387    fn heap_size(&self, ctx: &mut DFHeapSizeCtx) -> usize {
388        // BTreeMap does not provide a way to get its heap size, so this
389        // approximates it as the entries' sizes, ignoring node overhead.
390        self.iter()
391            .map(|(k, v)| size_of::<(K, V)>() + k.heap_size(ctx) + v.heap_size(ctx))
392            .sum()
393    }
394}
395
396impl DFHeapSize for Metadata {
397    fn heap_size(&self, ctx: &mut DFHeapSizeCtx) -> usize {
398        // `as_arc` returns `None` when the metadata is empty; the `Arc` impl
399        // dedupes instances that share the same allocation.
400        self.as_arc().map_or(0, |map| map.heap_size(ctx))
401    }
402}
403
404impl DFHeapSize for Field {
405    fn heap_size(&self, ctx: &mut DFHeapSizeCtx) -> usize {
406        self.name().heap_size(ctx)
407            + self.data_type().heap_size(ctx)
408            + self.is_nullable().heap_size(ctx)
409            + self.dict_is_ordered().heap_size(ctx)
410            + self.metadata().heap_size(ctx)
411    }
412}
413
414impl DFHeapSize for IntervalMonthDayNano {
415    fn heap_size(&self, ctx: &mut DFHeapSizeCtx) -> usize {
416        self.days.heap_size(ctx)
417            + self.months.heap_size(ctx)
418            + self.nanoseconds.heap_size(ctx)
419    }
420}
421
422impl DFHeapSize for IntervalDayTime {
423    fn heap_size(&self, ctx: &mut DFHeapSizeCtx) -> usize {
424        self.days.heap_size(ctx) + self.milliseconds.heap_size(ctx)
425    }
426}
427
428/// Implement [`DFHeapSize`] for types that own no heap allocations.
429macro_rules! impl_zero_heap_size {
430    ($($t:ty),+ $(,)?) => {
431        $(
432            impl DFHeapSize for $t {
433                fn heap_size(&self, _: &mut DFHeapSizeCtx) -> usize {
434                    0 // no heap allocations
435                }
436            }
437        )+
438    };
439}
440
441impl_zero_heap_size!(
442    bool,
443    u8,
444    u16,
445    u32,
446    u64,
447    usize,
448    i8,
449    i16,
450    i32,
451    i64,
452    i128,
453    i256,
454    f16,
455    f32,
456    f64,
457    UnionMode,
458    TimeUnit,
459    IntervalUnit,
460    DateTime<Utc>,
461);
462
463/// Implement [`DFHeapSize`] for Arrow arrays types.
464macro_rules! impl_array_heap_size {
465    ($($t:ty),+ $(,)?) => {
466        $(
467            impl DFHeapSize for $t {
468                fn heap_size(&self, _: &mut DFHeapSizeCtx) -> usize {
469                    self.get_array_memory_size()
470                }
471            }
472        )+
473    };
474}
475
476impl_array_heap_size!(
477    StructArray,
478    LargeListArray,
479    LargeListViewArray,
480    ListArray,
481    ListViewArray,
482    FixedSizeListArray,
483    MapArray,
484);
485
486#[cfg(test)]
487mod tests {
488    use super::*;
489
490    fn size<T: DFHeapSize + ?Sized>(v: &T) -> usize {
491        v.heap_size(&mut DFHeapSizeCtx::default())
492    }
493
494    #[test]
495    fn test_heap_size_arc_avoid_double_accounting() {
496        let a1 = Arc::new(vec![1, 2, 3]);
497        let mut ctx = DFHeapSizeCtx::default();
498        let heap_size = a1.heap_size(&mut ctx);
499
500        let a2 = Arc::clone(&a1);
501        let a3 = Arc::clone(&a1);
502        let a4 = Arc::clone(&a3);
503
504        let mut ctx = DFHeapSizeCtx::default();
505        let heap_size_with_clones = a1.heap_size(&mut ctx)
506            + a2.heap_size(&mut ctx)
507            + a3.heap_size(&mut ctx)
508            + a4.heap_size(&mut ctx);
509
510        assert_eq!(heap_size, heap_size_with_clones);
511    }
512
513    #[test]
514    fn test_heap_size_arc_str_avoid_double_accounting() {
515        let a1: Arc<str> = Arc::from("Hello");
516        let mut ctx = DFHeapSizeCtx::default();
517        let heap_size = a1.heap_size(&mut ctx);
518
519        let a2 = Arc::clone(&a1);
520        let a3 = Arc::clone(&a1);
521        let a4 = Arc::clone(&a3);
522
523        let mut ctx = DFHeapSizeCtx::default();
524        let heap_size_with_clones = a1.heap_size(&mut ctx)
525            + a2.heap_size(&mut ctx)
526            + a3.heap_size(&mut ctx)
527            + a4.heap_size(&mut ctx);
528
529        assert_eq!(heap_size, heap_size_with_clones);
530    }
531
532    #[test]
533    fn test_arc_dyn() {
534        let a1: Arc<dyn DFHeapSize> = Arc::new(String::from("hello"));
535        let baseline = size(&a1);
536
537        let a2 = Arc::clone(&a1);
538        let mut ctx = DFHeapSizeCtx::default();
539        let with_clones = a1.heap_size(&mut ctx) + a2.heap_size(&mut ctx);
540        assert_eq!(baseline, with_clones);
541    }
542
543    #[test]
544    fn test_primitives() {
545        assert_eq!(size(&true), 0);
546        assert_eq!(size(&0u8), 0);
547        assert_eq!(size(&0u16), 0);
548        assert_eq!(size(&0u32), 0);
549        assert_eq!(size(&0u64), 0);
550        assert_eq!(size(&0usize), 0);
551        assert_eq!(size(&0i8), 0);
552        assert_eq!(size(&0i16), 0);
553        assert_eq!(size(&0i32), 0);
554        assert_eq!(size(&0i64), 0);
555        assert_eq!(size(&0i128), 0);
556        assert_eq!(size(&i256::ZERO), 0);
557        assert_eq!(size(&0f32), 0);
558        assert_eq!(size(&0f64), 0);
559        assert_eq!(size(&f16::from_f32(0.0)), 0);
560    }
561
562    #[test]
563    fn test_heap_size_union_mode() {
564        assert_eq!(size(&UnionMode::Sparse), 0);
565        assert_eq!(size(&UnionMode::Dense), 0);
566    }
567
568    #[test]
569    fn test_heap_size_time_units() {
570        assert_eq!(size(&TimeUnit::Second), 0);
571        assert_eq!(size(&IntervalUnit::YearMonth), 0);
572        assert_eq!(size(&DateTime::<Utc>::UNIX_EPOCH), 0);
573        assert_eq!(size(&Utc::now()), 0);
574    }
575
576    #[test]
577    fn test_string() {
578        let mut s = String::with_capacity(32);
579        s.push_str("hello");
580        assert_eq!(size(&s), 32);
581
582        let empty = String::new();
583        assert_eq!(size(&empty), 0);
584    }
585
586    #[test]
587    fn test_owned_str() {
588        let a: Arc<str> = Arc::from("Hello");
589        assert!(size(&a) > 0);
590    }
591
592    #[test]
593    fn test_option() {
594        let some: Option<String> = Some(String::from("hi"));
595        assert_eq!(size(&some), some.as_ref().unwrap().capacity());
596
597        let none: Option<String> = None;
598        assert_eq!(size(&none), 0);
599    }
600
601    #[test]
602    fn test_vec() {
603        let v: Vec<i32> = vec![1, 2, 3];
604        assert!(size(&v) > 0);
605
606        let strings = vec![String::from("ab"), String::from("cdef")];
607        assert!(size(&strings) > 0);
608
609        let empty: Vec<i32> = Vec::new();
610        assert_eq!(size(&empty), 0);
611    }
612
613    #[test]
614    fn test_box() {
615        let b: Box<i32> = Box::new(42);
616        assert!(size(&b) > 0);
617
618        let b: Box<String> = Box::new(String::from("hello"));
619        assert!(size(&b) > 0);
620    }
621
622    #[test]
623    fn test_tuple() {
624        let zero = (1i32, 2i64);
625        assert_eq!(size(&zero), 0);
626
627        let t = (String::from("hello"), String::from("world"));
628        assert!(size(&t) > 0);
629    }
630
631    #[test]
632    fn test_hashmap() {
633        let m: HashMap<i32, i32> = HashMap::new();
634        assert_eq!(size(&m), 0);
635
636        let mut m: HashMap<String, String> = HashMap::new();
637        m.insert("key".into(), "value".into());
638
639        assert!(size(&m) > 0);
640    }
641
642    #[test]
643    fn test_precision() {
644        let exact: Precision<usize> = Precision::Exact(42);
645        assert_eq!(size(&exact), 0);
646
647        let inexact: Precision<usize> = Precision::Inexact(99);
648        assert_eq!(size(&inexact), 0);
649
650        let absent: Precision<usize> = Precision::Absent;
651        assert_eq!(size(&absent), 0);
652    }
653
654    #[test]
655    fn test_scalar_values() {
656        assert_eq!(size(&ScalarValue::Null), 0);
657        assert_eq!(size(&ScalarValue::Int32(Some(42))), 0);
658        assert_eq!(size(&ScalarValue::Boolean(Some(true))), 0);
659        assert_eq!(size(&ScalarValue::Float64(None)), 0);
660
661        let sv = ScalarValue::Utf8(Some(String::from("hello")));
662        assert_eq!(size(&sv), "hello".len());
663
664        let sv = ScalarValue::Utf8(None);
665        assert_eq!(size(&sv), 0);
666    }
667
668    #[test]
669    fn test_data_type_primitives() {
670        assert_eq!(size(&DataType::Int32), 0);
671        assert_eq!(size(&DataType::Utf8), 0);
672        assert_eq!(size(&DataType::Boolean), 0);
673        assert_eq!(size(&DataType::Null), 0);
674    }
675
676    #[test]
677    fn test_data_type_with_field() {
678        let list = DataType::List(Arc::new(Field::new("item", DataType::Int32, true)));
679        assert!(size(&list) > 0);
680    }
681
682    #[test]
683    fn test_table_references() {
684        let tr = TableReference::bare("users");
685        // Arc<str> overhead (two usize counts) plus the bytes of "users".
686        assert!(size(&tr) > 0);
687        let tr = TableReference::full("cat", "schema", "users");
688        assert!(size(&tr) > 0);
689    }
690
691    #[test]
692    fn test_column_statistics() {
693        let mut col = ColumnStatistics::new_unknown();
694        col.max_value = Precision::Exact(ScalarValue::Utf8(Some("hello".into())));
695        col.min_value = Precision::Exact(ScalarValue::Utf8(Some("ab".into())));
696        assert_eq!(size(&col), "hello".len() + "ab".len());
697
698        let mut col = ColumnStatistics::new_unknown();
699        col.max_value = Precision::Exact(ScalarValue::Utf8(Some("hello".into())));
700        let stats = Statistics {
701            num_rows: Precision::Exact(10),
702            total_byte_size: Precision::Absent,
703            column_statistics: vec![col],
704        };
705        assert!(size(&stats) > 0);
706    }
707
708    #[test]
709    fn test_field() {
710        let field = Field::new("temperature", DataType::Float64, true);
711        assert!(size(&field) > 0);
712    }
713
714    #[test]
715    fn test_list_array() {
716        use arrow::array::types::Int32Type;
717
718        let array = ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
719            Some(vec![Some(1), Some(2), Some(3)]),
720            Some(vec![Some(4)]),
721        ]);
722        assert_eq!(size(&array), array.get_array_memory_size());
723        assert!(size(&array) > 0);
724
725        let large =
726            LargeListArray::from_iter_primitive::<Int32Type, _, _>(vec![Some(vec![
727                Some(1),
728                Some(2),
729            ])]);
730        assert_eq!(size(&large), large.get_array_memory_size());
731        assert!(size(&large) > 0);
732    }
733
734    #[test]
735    fn test_struct_array() {
736        use arrow::array::Int32Array;
737
738        let array = StructArray::from(vec![(
739            Arc::new(Field::new("a", DataType::Int32, true)),
740            Arc::new(Int32Array::from(vec![1, 2, 3])) as _,
741        )]);
742        assert_eq!(size(&array), array.get_array_memory_size());
743        assert!(size(&array) > 0);
744    }
745
746    #[test]
747    fn test_fixed_size_list_array() {
748        use arrow::array::Int32Array;
749
750        let values = Arc::new(Int32Array::from(vec![1, 2, 3, 4]));
751        let field = Arc::new(Field::new("item", DataType::Int32, true));
752        let array = FixedSizeListArray::new(field, 2, values, None);
753        assert_eq!(size(&array), array.get_array_memory_size());
754        assert!(size(&array) > 0);
755    }
756
757    #[test]
758    fn test_map_array() {
759        use arrow::array::{Int32Builder, MapBuilder, StringBuilder};
760
761        let mut builder =
762            MapBuilder::new(None, StringBuilder::new(), Int32Builder::new());
763        builder.keys().append_value("key");
764        builder.values().append_value(1);
765        builder.append(true).unwrap();
766        let array = builder.finish();
767        assert_eq!(size(&array), array.get_array_memory_size());
768        assert!(size(&array) > 0);
769    }
770}