1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
use std::fmt;

use bitflags::bitflags;
use polars_utils::IdxSize;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

pub use self::env::MetadataEnv;
use super::PolarsDataType;
use crate::series::IsSorted;

#[macro_use]
mod env;
mod collect;

macro_rules! mdenv_may_bail {
    (get: $field:literal, $value:expr $(=> $default:expr)?) => {{
        if MetadataEnv::disabled() {
            return $($default)?;
        }
        if MetadataEnv::log() {
            mdlog!("Get: '{}' <- {:?}", $field, $value);
        }
        $value
    }};
    (set: $field:literal, $value:expr) => {
        if MetadataEnv::disabled() {
            return;
        }
        if MetadataEnv::log() {
            mdlog!("Set: '{}' <- {:?}", $field, $value);
        }
    };
    (init: $field:literal, $value:expr ; $default:expr) => {{
        if MetadataEnv::enabled() {
            if MetadataEnv::log() {
                mdlog!("Ini: '{}' <- {:?}", $field, $value);
            }
            $value
        } else {
            $default
        }
    }};
}

bitflags! {
    #[derive(Default, Debug, Clone, Copy, PartialEq)]
    pub struct MetadataProperties: u32 {
        const SORTED = 0x01;
        const FAST_EXPLODE_LIST = 0x02;
        const MIN_VALUE = 0x04;
        const MAX_VALUE = 0x08;
        const DISTINCT_COUNT = 0x10;
    }
}

pub struct Metadata<T: PolarsDataType> {
    flags: MetadataFlags,

    min_value: Option<T::OwnedPhysical>,
    max_value: Option<T::OwnedPhysical>,

    /// Number of unique non-null values
    distinct_count: Option<IdxSize>,
}

pub trait MetadataCollectable<T>: Sized {
    fn collect_cheap_metadata(&mut self) {}

    #[inline(always)]
    fn with_cheap_metadata(mut self) -> Self {
        self.collect_cheap_metadata();
        self
    }
}

bitflags! {
    #[derive(Default, Debug, Clone, Copy, PartialEq)]
    #[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(transparent))]
    pub struct MetadataFlags: u8 {
        const SORTED_ASC = 0x01;
        const SORTED_DSC = 0x02;
        const FAST_EXPLODE_LIST = 0x04;
    }
}

impl MetadataFlags {
    pub fn set_sorted_flag(&mut self, sorted: IsSorted) {
        mdenv_may_bail!(set: "sorted", sorted);
        match sorted {
            IsSorted::Not => {
                self.remove(MetadataFlags::SORTED_ASC | MetadataFlags::SORTED_DSC);
            },
            IsSorted::Ascending => {
                self.remove(MetadataFlags::SORTED_DSC);
                self.insert(MetadataFlags::SORTED_ASC)
            },
            IsSorted::Descending => {
                self.remove(MetadataFlags::SORTED_ASC);
                self.insert(MetadataFlags::SORTED_DSC)
            },
        }
    }

    pub fn get_sorted_flag(&self) -> IsSorted {
        let sorted = if self.contains(MetadataFlags::SORTED_ASC) {
            IsSorted::Ascending
        } else if self.contains(MetadataFlags::SORTED_DSC) {
            IsSorted::Descending
        } else {
            IsSorted::Not
        };

        mdenv_may_bail!(get: "sorted", sorted => IsSorted::Not)
    }

    pub fn set_fast_explode_list(&mut self, fast_explode_list: bool) {
        mdenv_may_bail!(set: "fast_explode_list", fast_explode_list);
        self.insert(Self::FAST_EXPLODE_LIST)
    }

    pub fn get_fast_explode_list(&self) -> bool {
        let value = self.contains(MetadataFlags::FAST_EXPLODE_LIST);
        mdenv_may_bail!(get: "fast_explode_list", value => false)
    }
}

impl<T: PolarsDataType> Default for Metadata<T> {
    fn default() -> Self {
        Self::DEFAULT
    }
}

impl<T: PolarsDataType> Clone for Metadata<T> {
    fn clone(&self) -> Self {
        Self {
            flags: self.flags,
            min_value: self.min_value.clone(),
            max_value: self.max_value.clone(),
            distinct_count: self.distinct_count,
        }
    }
}

impl<T: PolarsDataType> fmt::Debug for Metadata<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Metadata")
            .field("flags", &self.flags)
            .field("min_value", &self.min_value)
            .field("max_value", &self.max_value)
            .field("distinct_count", &self.distinct_count)
            .finish()
    }
}

pub enum MetadataMerge<T: PolarsDataType> {
    Keep,
    Conflict,
    New(Metadata<T>),
}

impl<T: PolarsDataType> Metadata<T> {
    pub const DEFAULT: Metadata<T> = Self {
        flags: MetadataFlags::empty(),

        min_value: None,
        max_value: None,

        distinct_count: None,
    };

    // Builder Pattern Methods
    pub fn sorted(mut self, is_sorted: IsSorted) -> Self {
        self.flags.set_sorted_flag(is_sorted);
        self
    }
    pub fn fast_explode_list(mut self, fast_explode_list: bool) -> Self {
        self.flags.set_fast_explode_list(fast_explode_list);
        self
    }
    pub fn flags(mut self, flags: MetadataFlags) -> Self {
        self.set_flags(flags);
        self
    }
    pub fn min_value(mut self, min_value: T::OwnedPhysical) -> Self {
        self.set_min_value(Some(min_value));
        self
    }
    pub fn max_value(mut self, max_value: T::OwnedPhysical) -> Self {
        self.set_max_value(Some(max_value));
        self
    }
    pub fn distinct_count(mut self, distinct_count: IdxSize) -> Self {
        self.set_distinct_count(Some(distinct_count));
        self
    }
    pub fn sorted_opt(self, is_sorted: Option<IsSorted>) -> Self {
        if let Some(is_sorted) = is_sorted {
            self.sorted(is_sorted)
        } else {
            self
        }
    }
    pub fn fast_explode_list_opt(self, fast_explode_list: Option<bool>) -> Self {
        if let Some(fast_explode_list) = fast_explode_list {
            self.fast_explode_list(fast_explode_list)
        } else {
            self
        }
    }
    pub fn flags_opt(mut self, flags: Option<MetadataFlags>) -> Self {
        self.set_flags(flags.unwrap_or(MetadataFlags::empty()));
        self
    }
    pub fn min_value_opt(mut self, min_value: Option<T::OwnedPhysical>) -> Self {
        self.set_min_value(min_value);
        self
    }
    pub fn max_value_opt(mut self, max_value: Option<T::OwnedPhysical>) -> Self {
        self.set_max_value(max_value);
        self
    }
    pub fn distinct_count_opt(mut self, distinct_count: Option<IdxSize>) -> Self {
        self.set_distinct_count(distinct_count);
        self
    }

    /// Create a [`Metadata`] with only the properties set in `props`.
    pub fn filter_props_cast<O: PolarsDataType>(&self, props: MetadataProperties) -> Metadata<O> {
        if props.is_empty() {
            return Metadata::DEFAULT;
        }

        debug_assert!(!props.contains(P::MIN_VALUE));
        debug_assert!(!props.contains(P::MAX_VALUE));

        use {MetadataFlags as F, MetadataProperties as P};

        let sorted = if props.contains(P::SORTED) {
            self.flags & (F::SORTED_ASC | F::SORTED_DSC)
        } else {
            F::empty()
        };
        let fast_explode_list = if props.contains(P::FAST_EXPLODE_LIST) {
            self.flags & F::FAST_EXPLODE_LIST
        } else {
            F::empty()
        };

        Metadata {
            flags: sorted | fast_explode_list,
            min_value: None,
            max_value: None,
            distinct_count: self
                .distinct_count
                .as_ref()
                .cloned()
                .filter(|_| props.contains(P::DISTINCT_COUNT)),
        }
    }

    /// Create a [`Metadata`] with only the properties set in `props`.
    pub fn filter_props(&self, props: MetadataProperties) -> Self {
        if props.is_empty() {
            return Metadata::DEFAULT;
        }

        use {MetadataFlags as F, MetadataProperties as P};

        let sorted = if props.contains(P::SORTED) {
            self.flags & (F::SORTED_ASC | F::SORTED_DSC)
        } else {
            F::empty()
        };
        let fast_explode_list = if props.contains(P::FAST_EXPLODE_LIST) {
            self.flags & F::FAST_EXPLODE_LIST
        } else {
            F::empty()
        };

        let min_value = self
            .min_value
            .as_ref()
            .cloned()
            .filter(|_| props.contains(P::MIN_VALUE));
        let max_value = self
            .max_value
            .as_ref()
            .cloned()
            .filter(|_| props.contains(P::MAX_VALUE));
        let distinct_count = self
            .distinct_count
            .as_ref()
            .cloned()
            .filter(|_| props.contains(P::DISTINCT_COUNT));

        Self {
            flags: mdenv_may_bail!(init: "flags", sorted | fast_explode_list ; MetadataFlags::empty()),
            min_value: mdenv_may_bail!(init: "min_value", min_value ; None),
            max_value: mdenv_may_bail!(init: "max_value", max_value ; None),
            distinct_count: mdenv_may_bail!(init: "distinct_count", distinct_count ; None),
        }
    }

    /// Merge the maximum information from both [`Metadata`]s into one [`Metadata`].
    ///
    /// It returns
    /// - [`MetadataMerge::Keep`] if the `self` already contains all the information
    /// - [`MetadataMerge::New(md)`][MetadataMerge::New] if we have learned new information
    /// - [`MetadataMerge::Conflict`] if the two structures contain conflicting metadata
    pub fn merge(&self, other: Self) -> MetadataMerge<T> {
        if MetadataEnv::disabled() || other.is_empty() {
            return MetadataMerge::Keep;
        }

        let sorted_conflicts = matches!(
            (self.is_sorted(), other.is_sorted()),
            (IsSorted::Ascending, IsSorted::Descending)
                | (IsSorted::Descending, IsSorted::Ascending)
        );

        let is_conflict = sorted_conflicts
            || matches!((self.get_min_value(), other.get_min_value()), (Some(x), Some(y)) if x != y)
            || matches!((self.get_max_value(), other.get_max_value()), (Some(x), Some(y)) if x != y)
            || matches!((self.get_distinct_count(), other.get_distinct_count()), (Some(x), Some(y)) if x != y);

        if is_conflict {
            return MetadataMerge::Conflict;
        }

        let is_new = (!self.get_fast_explode_list() && other.get_fast_explode_list())
            || (self.is_sorted() == IsSorted::Not && other.is_sorted() != IsSorted::Not)
            || matches!(
                (self.get_min_value(), other.get_min_value()),
                (None, Some(_))
            )
            || matches!(
                (self.get_max_value(), other.get_max_value()),
                (None, Some(_))
            )
            || matches!(
                (self.get_distinct_count(), other.get_distinct_count()),
                (None, Some(_))
            );

        if !is_new {
            return MetadataMerge::Keep;
        }

        let min_value = self.min_value.as_ref().cloned().or(other.min_value);
        let max_value = self.max_value.as_ref().cloned().or(other.max_value);
        let distinct_count = self.distinct_count.or(other.distinct_count);

        MetadataMerge::New(Metadata {
            flags: mdenv_may_bail!(init: "flags", self.flags | other.flags ; MetadataFlags::empty()),
            min_value: mdenv_may_bail!(init: "min_value", min_value ; None),
            max_value: mdenv_may_bail!(init: "max_value", max_value ; None),
            distinct_count: mdenv_may_bail!(init: "distinct_count", distinct_count ; None),
        })
    }

    pub fn is_empty(&self) -> bool {
        self.flags.is_empty()
            && self.min_value.is_none()
            && self.max_value.is_none()
            && self.distinct_count.is_none()
    }

    pub fn is_sorted_ascending(&self) -> bool {
        self.flags.get_sorted_flag() == IsSorted::Ascending
    }

    pub fn set_sorted_ascending(&mut self, value: bool) {
        self.flags.set_sorted_flag(if value {
            IsSorted::Ascending
        } else {
            IsSorted::Not
        });
    }

    pub fn is_sorted_descending(&self) -> bool {
        self.flags.get_sorted_flag() == IsSorted::Descending
    }

    pub fn set_sorted_descending(&mut self, value: bool) {
        self.flags.set_sorted_flag(if value {
            IsSorted::Descending
        } else {
            IsSorted::Not
        });
    }

    pub fn get_fast_explode_list(&self) -> bool {
        self.flags.get_fast_explode_list()
    }

    pub fn set_fast_explode_list(&mut self, value: bool) {
        self.flags.set_fast_explode_list(value);
    }

    pub fn is_sorted(&self) -> IsSorted {
        self.flags.get_sorted_flag()
    }

    pub fn set_sorted_flag(&mut self, is_sorted: IsSorted) {
        self.flags.set_sorted_flag(is_sorted)
    }

    pub fn set_min_value(&mut self, min_value: Option<T::OwnedPhysical>) {
        mdenv_may_bail!(set: "min_value", min_value);
        self.min_value = min_value;
    }
    pub fn set_max_value(&mut self, max_value: Option<T::OwnedPhysical>) {
        mdenv_may_bail!(set: "max_value", max_value);
        self.max_value = max_value;
    }
    pub fn set_distinct_count(&mut self, distinct_count: Option<IdxSize>) {
        mdenv_may_bail!(set: "distinct_count", distinct_count);
        self.distinct_count = distinct_count;
    }

    pub fn set_flags(&mut self, flags: MetadataFlags) {
        mdenv_may_bail!(set: "flags", flags);
        self.flags = flags;
    }

    pub fn get_min_value(&self) -> Option<&T::OwnedPhysical> {
        let min_value = self.min_value.as_ref();
        mdenv_may_bail!(get: "min_value", min_value => None)
    }
    pub fn get_max_value(&self) -> Option<&T::OwnedPhysical> {
        let max_value = self.max_value.as_ref();
        mdenv_may_bail!(get: "max_value", max_value => None)
    }
    pub fn get_distinct_count(&self) -> Option<IdxSize> {
        let distinct_count = self.distinct_count;
        mdenv_may_bail!(get: "distinct_count", distinct_count => None)
    }
    pub fn get_flags(&self) -> MetadataFlags {
        let flags = self.flags;
        mdenv_may_bail!(get: "flags", flags => MetadataFlags::empty())
    }
}