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
use crate::error::{GeozeroError, Result};
use std::collections::HashMap;
use std::fmt;
use std::hash::BuildHasher;

/// Feature property value.
#[derive(PartialEq, Debug)]
pub enum ColumnValue<'a> {
    Byte(i8),
    UByte(u8),
    Bool(bool),
    Short(i16),
    UShort(u16),
    Int(i32),
    UInt(u32),
    Long(i64),
    ULong(u64),
    Float(f32),
    Double(f64),
    String(&'a str),
    /// A JSON-formatted string
    Json(&'a str),
    /// A datetime stored as an ISO8601-formatted string
    DateTime(&'a str),
    Binary(&'a [u8]),
}

/// Feature property processing trait.
///
/// # Usage example:
///
/// ```rust
/// use geozero::{PropertyProcessor, ColumnValue, error::Result};
///
/// struct PropertyPrinter;
///
/// impl PropertyProcessor for PropertyPrinter {
///     fn property(&mut self, i: usize, n: &str, v: &ColumnValue) -> Result<bool> {
///         println!("column idx: {i} name: {n} value: {v:?}");
///         Ok(false) // don't abort
///     }
/// }
/// ```
#[allow(unused_variables)]
pub trait PropertyProcessor {
    /// Process property value. Abort processing, if return value is true.
    ///
    /// - `idx`: the positional index of the property.
    /// - `name` is the name of the column
    /// - `value` is the value of this field
    ///
    /// ## Notes:
    ///
    /// - It is not guaranteed that `idx` is consistent across rows, nor is it
    ///   guaranteed that the set of names in each row is the same. Some input formats, like
    ///   GeoJSON, are schema-less and properties may change in every row. For this reason, it is
    ///   suggested to use the `name` parameter for matching across rows.
    /// - It is not guaranteed that the data type of `name` is consistent across rows. For a given
    ///   `name`, it may be numeric in one row and string in the next.
    fn property(&mut self, idx: usize, name: &str, value: &ColumnValue) -> Result<bool> {
        Ok(true)
    }
}

impl fmt::Display for ColumnValue<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ColumnValue::Byte(v) => write!(f, "{v}"),
            ColumnValue::UByte(v) => write!(f, "{v}"),
            ColumnValue::Bool(v) => write!(f, "{v}"),
            ColumnValue::Short(v) => write!(f, "{v}"),
            ColumnValue::UShort(v) => write!(f, "{v}"),
            ColumnValue::Int(v) => write!(f, "{v}"),
            ColumnValue::UInt(v) => write!(f, "{v}"),
            ColumnValue::Long(v) => write!(f, "{v}"),
            ColumnValue::ULong(v) => write!(f, "{v}"),
            ColumnValue::Float(v) => write!(f, "{v}"),
            ColumnValue::Double(v) => write!(f, "{v}"),
            ColumnValue::String(v) | ColumnValue::Json(v) | ColumnValue::DateTime(v) => {
                write!(f, "{v}")
            }
            ColumnValue::Binary(_v) => write!(f, "[BINARY]"),
        }
    }
}

#[doc(hidden)]
pub struct PropertyReader<'a, T: PropertyReadType> {
    pub name: &'a str,
    pub value: Result<T>,
}

#[doc(hidden)]
pub struct PropertyReaderIdx<T: PropertyReadType> {
    pub idx: usize,
    pub value: Result<T>,
}

/// Get property value as Rust type.
pub trait PropertyReadType<T = Self>
where
    T: PropertyReadType,
{
    /// Get property value as Rust type.
    fn get_value(v: &ColumnValue) -> Result<T>;
}

impl<T: PropertyReadType> PropertyProcessor for PropertyReader<'_, T> {
    fn property(&mut self, _i: usize, name: &str, v: &ColumnValue) -> Result<bool> {
        if name == self.name {
            self.value = T::get_value(v);
            Ok(true) // finish
        } else {
            Ok(false)
        }
    }
}

impl<T: PropertyReadType> PropertyProcessor for PropertyReaderIdx<T> {
    fn property(&mut self, i: usize, _name: &str, v: &ColumnValue) -> Result<bool> {
        if i == self.idx {
            self.value = T::get_value(v);
            Ok(true) // finish
        } else {
            Ok(false)
        }
    }
}

macro_rules! impl_scalar_property_reader {
    ( $t:ty, $e:path ) => {
        impl From<&ColumnValue<'_>> for Result<$t> {
            fn from(v: &ColumnValue) -> Result<$t> {
                if let $e(v) = v {
                    Ok(*v)
                } else {
                    Err(GeozeroError::ColumnType(stringify!($e).to_string(), format!("{v:?}")))
                }
            }
        }
        impl PropertyReadType for $t {
            fn get_value(v: &ColumnValue) -> Result<$t> {
                v.into()
            }
        }
    };
}

impl_scalar_property_reader!(i8, ColumnValue::Byte);
impl_scalar_property_reader!(u8, ColumnValue::UByte);
impl_scalar_property_reader!(bool, ColumnValue::Bool);
impl_scalar_property_reader!(i16, ColumnValue::Short);
impl_scalar_property_reader!(u16, ColumnValue::UShort);
impl_scalar_property_reader!(i32, ColumnValue::Int);
impl_scalar_property_reader!(u32, ColumnValue::UInt);
impl_scalar_property_reader!(i64, ColumnValue::Long);
impl_scalar_property_reader!(u64, ColumnValue::ULong);
impl_scalar_property_reader!(f32, ColumnValue::Float);
impl_scalar_property_reader!(f64, ColumnValue::Double);

impl From<&ColumnValue<'_>> for Result<String> {
    fn from(v: &ColumnValue) -> Result<String> {
        Ok(v.to_string())
    }
}

impl PropertyReadType for String {
    fn get_value(v: &ColumnValue) -> Result<String> {
        v.into()
    }
}

impl<S: BuildHasher> PropertyProcessor for HashMap<String, String, S> {
    fn property(&mut self, _idx: usize, colname: &str, colval: &ColumnValue) -> Result<bool> {
        self.insert(colname.to_string(), colval.to_string());
        Ok(false)
    }
}

#[test]
fn convert_column_value() {
    let v = &ColumnValue::Int(42);
    assert_eq!(Result::<i32>::from(v).unwrap(), 42);
    assert_eq!(
        Result::<i64>::from(v).unwrap_err().to_string(),
        "expected a `ColumnValue::Long` value but found `Int(42)`"
    );
    assert_eq!(Result::<String>::from(v).unwrap(), "42".to_string());

    let v = &ColumnValue::String("Yes");
    assert_eq!(Result::<String>::from(v).unwrap(), "Yes".to_string());
    assert_eq!(
        Result::<i32>::from(v).unwrap_err().to_string(),
        r#"expected a `ColumnValue::Int` value but found `String("Yes")`"#
    );
}