serde_evaluate 0.2.2

Extract single scalar field values from Serializable structs without full deserialization.
Documentation
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
use crate::error::EvaluateError;
use crate::serializer::FieldValueExtractorSerializer;
use crate::value::FieldScalarValue;
use serde::Serialize;

// =============================================================================
// Path Validation Helper
// =============================================================================

/// Validates and converts path segments to a Vec<String>.
///
/// Returns an error if the path is empty or any segment is empty.
fn validate_path<S: AsRef<str>>(segments: &[S]) -> Result<Vec<String>, EvaluateError> {
    if segments.is_empty() {
        return Err(EvaluateError::InvalidPath(
            "Path cannot be empty".to_string(),
        ));
    }

    let segments: Vec<String> = segments.iter().map(|s| s.as_ref().to_string()).collect();

    if segments.iter().any(|s| s.is_empty()) {
        return Err(EvaluateError::InvalidPath(
            "Path segments cannot be empty".to_string(),
        ));
    }

    Ok(segments)
}

// =============================================================================
// Scalar Extractors
// =============================================================================

/// Facilitates the extraction of a scalar value from a specified field within a `Serialize`able struct.
///
/// This struct holds the configuration for the extraction, namely the target field name.
/// The primary way to use this is via the associated function [`FieldExtractor::evaluate`].
#[derive(Debug, Clone)]
pub struct FieldExtractor {
    field_name: String,
}

impl FieldExtractor {
    /// Creates a new `FieldExtractor` configured to target the specified field name.
    ///
    /// Accepts any type that can be converted into a `String`, such as `&str`.
    pub fn new<S: Into<String>>(field_name: S) -> Self {
        FieldExtractor {
            field_name: field_name.into(),
        }
    }

    /// Extracts the scalar value of the configured `field_name` from the given `record`.
    ///
    /// This method drives the custom serialization process to capture the field's value.
    ///
    /// # Arguments
    ///
    /// * `record`: A reference to a struct that implements `serde::Serialize`.
    ///
    /// # Errors
    ///
    /// Returns `EvaluateError` if:
    /// * The `field_name` is not found in the `record` ([`EvaluateError::FieldNotFound`]).
    /// * The `field_name`'s value is not a supported scalar type ([`EvaluateError::UnsupportedType`]).
    /// * Any other Serde serialization error occurs.
    pub fn evaluate<T: Serialize>(&self, record: &T) -> Result<FieldScalarValue, EvaluateError> {
        let mut serializer = FieldValueExtractorSerializer::new(&self.field_name);
        // Attempt to serialize the record using our custom serializer.
        record.serialize(&mut serializer)?;

        // After serialization, check if the serializer captured a result.
        serializer
            .into_result()
            .ok_or_else(|| EvaluateError::FieldNotFound {
                field_name: self.field_name.clone(),
            })
    }
}

/// Extracts a potentially nested scalar field value using a pre-defined path.
///
/// This struct allows specifying a path as a sequence of field names.
/// It uses the `FieldValueExtractorSerializer` internally to traverse the structure.
#[derive(Debug, Clone)]
pub struct NestedFieldExtractor {
    /// The sequence of field names representing the path to the target value.
    path_segments: Vec<String>,
}

impl NestedFieldExtractor {
    /// Creates a new `NestedFieldExtractor` from a slice of path segments.
    ///
    /// Each element in the input slice represents a step in the path.
    ///
    /// # Arguments
    ///
    /// * `path_segments`: A slice where each element can be converted into a `&str`
    ///   (e.g., `&str`, `String`).
    ///
    /// # Errors
    ///
    /// Returns `EvaluateError::InvalidPath` if the input slice is empty or if any
    /// segment converts to an empty string.
    pub fn new_from_path<S: AsRef<str>>(path_segments: &[S]) -> Result<Self, EvaluateError> {
        Ok(NestedFieldExtractor {
            path_segments: validate_path(path_segments)?,
        })
    }

    /// Evaluates the extractor against the given serializable value using the configured path.
    ///
    /// This triggers the serialization process, traversing the nested structure according
    /// to `path_segments` and intercepting the target field's value.
    ///
    /// # Arguments
    ///
    /// * `value` - A reference to a value that implements `serde::Serialize`.
    ///
    /// # Returns
    ///
    /// * `Ok(FieldScalarValue)` if the field at the specified path is found and is a supported scalar type.
    /// * `Err(EvaluateError)` if the path is invalid, an intermediate field is not a struct,
    ///   the final field is not found or has an unsupported type, or a serialization error occurs.
    pub fn evaluate<T: Serialize>(&self, value: &T) -> Result<FieldScalarValue, EvaluateError> {
        // Clone the path segments because new_nested takes ownership, but evaluate only has &self.
        let mut serializer = FieldValueExtractorSerializer::new_nested(self.path_segments.clone());

        // Attempt to serialize the record using our custom serializer.
        value.serialize(&mut serializer)?;

        // After serialization, check if the serializer captured a result.
        serializer
            .into_result()
            .ok_or_else(|| EvaluateError::NestedFieldNotFound {
                path: self.path_segments.clone(),
                failed_at_index: None, // Index unknown at this point
            })
    }
}

// =============================================================================
// Composite Extractor
// =============================================================================

/// Extracts multiple independent scalar fields from a single `Serialize`able record,
/// returning them as an ordered `Vec<FieldScalarValue>`.
///
/// This is useful for building composite index keys where multiple field values
/// are combined into a single ordered key.
///
/// # Example
///
/// ```rust
/// use serde::Serialize;
/// use serde_evaluate::{CompositeFieldExtractor, FieldScalarValue, EvaluateError};
///
/// #[derive(Serialize)]
/// struct Record {
///     last_name: String,
///     first_name: String,
///     age: u32,
/// }
///
/// fn main() -> Result<(), EvaluateError> {
///     let record = Record {
///         last_name: "Smith".to_string(),
///         first_name: "John".to_string(),
///         age: 30,
///     };
///
///     let extractor = CompositeFieldExtractor::new(&["last_name", "first_name", "age"])?;
///     let values = extractor.evaluate(&record)?;
///
///     assert_eq!(values, vec![
///         FieldScalarValue::String("Smith".to_string()),
///         FieldScalarValue::String("John".to_string()),
///         FieldScalarValue::U32(30),
///     ]);
///     Ok(())
/// }
/// ```
#[derive(Debug, Clone)]
pub struct CompositeFieldExtractor {
    extractors: Vec<NestedFieldExtractor>,
}

impl CompositeFieldExtractor {
    /// Creates a new `CompositeFieldExtractor` for top-level field names.
    ///
    /// Each field name is treated as a single-segment path.
    ///
    /// # Errors
    ///
    /// Returns `EvaluateError::InvalidPath` if the list is empty or any name is empty.
    pub fn new<S: AsRef<str>>(field_names: &[S]) -> Result<Self, EvaluateError> {
        if field_names.is_empty() {
            return Err(EvaluateError::InvalidPath(
                "Composite extractor requires at least one field".to_string(),
            ));
        }

        let extractors = field_names
            .iter()
            .map(|name| NestedFieldExtractor::new_from_path(&[name.as_ref()]))
            .collect::<Result<Vec<_>, _>>()?;

        Ok(CompositeFieldExtractor { extractors })
    }

    /// Creates a new `CompositeFieldExtractor` from a slice of field paths.
    ///
    /// Each inner slice represents the path segments to a field, supporting
    /// both top-level (single-segment) and nested (multi-segment) paths.
    ///
    /// # Example
    ///
    /// ```rust
    /// use serde::Serialize;
    /// use serde_evaluate::{CompositeFieldExtractor, FieldScalarValue, EvaluateError};
    ///
    /// #[derive(Serialize)]
    /// struct Record {
    ///     name: String,
    ///     address: Address,
    /// }
    ///
    /// #[derive(Serialize)]
    /// struct Address {
    ///     zip: String,
    /// }
    ///
    /// fn main() -> Result<(), EvaluateError> {
    ///     let record = Record {
    ///         name: "Alice".to_string(),
    ///         address: Address { zip: "90210".to_string() },
    ///     };
    ///
    ///     let extractor = CompositeFieldExtractor::new_from_paths(&[
    ///         &["name"],
    ///         &["address", "zip"],
    ///     ])?;
    ///     let values = extractor.evaluate(&record)?;
    ///
    ///     assert_eq!(values, vec![
    ///         FieldScalarValue::String("Alice".to_string()),
    ///         FieldScalarValue::String("90210".to_string()),
    ///     ]);
    ///     Ok(())
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns `EvaluateError::InvalidPath` if the list is empty, any path is empty,
    /// or any path segment is empty.
    pub fn new_from_paths<S: AsRef<str>>(paths: &[&[S]]) -> Result<Self, EvaluateError> {
        if paths.is_empty() {
            return Err(EvaluateError::InvalidPath(
                "Composite extractor requires at least one field".to_string(),
            ));
        }

        let extractors = paths
            .iter()
            .map(|path| NestedFieldExtractor::new_from_path(path))
            .collect::<Result<Vec<_>, _>>()?;

        Ok(CompositeFieldExtractor { extractors })
    }

    /// Extracts scalar values for all configured fields from the given record.
    ///
    /// Returns values in the same order as the fields were specified during construction.
    /// Fails fast on the first extraction error.
    ///
    /// # Arguments
    ///
    /// * `record`: A reference to a value that implements `serde::Serialize`.
    ///
    /// # Errors
    ///
    /// Returns the first `EvaluateError` encountered during extraction.
    pub fn evaluate<T: Serialize>(
        &self,
        record: &T,
    ) -> Result<Vec<FieldScalarValue>, EvaluateError> {
        self.extractors
            .iter()
            .map(|extractor| extractor.evaluate(record))
            .collect()
    }
}

// =============================================================================
// List Extractors (FanOut-style)
// =============================================================================

/// Extracts a list of scalar values from a `Vec<T>` field where T is a scalar type.
///
/// This enables FanOut-style extraction where each element of a list is returned
/// separately, useful for indexing scenarios where each element needs to be
/// processed individually.
///
/// # Example
///
/// ```rust
/// use serde::Serialize;
/// use serde_evaluate::{ListFieldExtractor, FieldScalarValue, EvaluateError};
///
/// #[derive(Serialize)]
/// struct Record {
///     id: u32,
///     tags: Vec<String>,
/// }
///
/// fn main() -> Result<(), EvaluateError> {
///     let record = Record {
///         id: 1,
///         tags: vec!["rust".to_string(), "serde".to_string()],
///     };
///
///     let extractor = ListFieldExtractor::new("tags");
///     let values = extractor.evaluate(&record)?;
///
///     assert_eq!(values, vec![
///         FieldScalarValue::String("rust".to_string()),
///         FieldScalarValue::String("serde".to_string()),
///     ]);
///     Ok(())
/// }
/// ```
#[derive(Debug, Clone)]
pub struct ListFieldExtractor {
    field_name: String,
}

impl ListFieldExtractor {
    /// Creates a new `ListFieldExtractor` configured to target the specified field name.
    ///
    /// Accepts any type that can be converted into a `String`, such as `&str`.
    pub fn new<S: Into<String>>(field_name: S) -> Self {
        ListFieldExtractor {
            field_name: field_name.into(),
        }
    }

    /// Extracts all scalar elements from a `Vec<T>` field.
    ///
    /// # Arguments
    ///
    /// * `record`: A reference to a struct that implements `serde::Serialize`.
    ///
    /// # Returns
    ///
    /// * `Ok(Vec<FieldScalarValue>)` containing each element as a scalar value.
    /// * `Ok(vec![])` for empty lists or `Option<Vec<T>>` with `None`.
    ///
    /// # Errors
    ///
    /// Returns `EvaluateError` if:
    /// * The `field_name` is not found in the `record` ([`EvaluateError::FieldNotFound`]).
    /// * The list elements are not scalar types ([`EvaluateError::UnsupportedType`]).
    pub fn evaluate<T: Serialize>(
        &self,
        record: &T,
    ) -> Result<Vec<FieldScalarValue>, EvaluateError> {
        let mut serializer = FieldValueExtractorSerializer::new_list(&self.field_name);
        record.serialize(&mut serializer)?;

        serializer
            .into_list_result()
            .ok_or_else(|| EvaluateError::FieldNotFound {
                field_name: self.field_name.clone(),
            })
    }
}

/// Extracts a list of scalar values from a nested `Vec<T>` field using a path.
///
/// This enables FanOut-style extraction for lists within nested structures.
///
/// # Example
///
/// ```rust
/// use serde::Serialize;
/// use serde_evaluate::{NestedListFieldExtractor, FieldScalarValue, EvaluateError};
///
/// #[derive(Serialize)]
/// struct Record {
///     metadata: Metadata,
/// }
///
/// #[derive(Serialize)]
/// struct Metadata {
///     labels: Vec<String>,
/// }
///
/// fn main() -> Result<(), EvaluateError> {
///     let record = Record {
///         metadata: Metadata {
///             labels: vec!["label1".to_string(), "label2".to_string()],
///         },
///     };
///
///     let extractor = NestedListFieldExtractor::new_from_path(&["metadata", "labels"])?;
///     let values = extractor.evaluate(&record)?;
///
///     assert_eq!(values, vec![
///         FieldScalarValue::String("label1".to_string()),
///         FieldScalarValue::String("label2".to_string()),
///     ]);
///     Ok(())
/// }
/// ```
#[derive(Debug, Clone)]
pub struct NestedListFieldExtractor {
    path_segments: Vec<String>,
}

impl NestedListFieldExtractor {
    /// Creates a new `NestedListFieldExtractor` from a slice of path segments.
    ///
    /// Each element in the input slice represents a step in the path.
    ///
    /// # Arguments
    ///
    /// * `path_segments`: A slice where each element can be converted into a `&str`
    ///   (e.g., `&str`, `String`).
    ///
    /// # Errors
    ///
    /// Returns `EvaluateError::InvalidPath` if the input slice is empty or if any
    /// segment converts to an empty string.
    pub fn new_from_path<S: AsRef<str>>(path_segments: &[S]) -> Result<Self, EvaluateError> {
        Ok(NestedListFieldExtractor {
            path_segments: validate_path(path_segments)?,
        })
    }

    /// Extracts all scalar elements from a nested `Vec<T>` field.
    ///
    /// # Arguments
    ///
    /// * `value` - A reference to a value that implements `serde::Serialize`.
    ///
    /// # Returns
    ///
    /// * `Ok(Vec<FieldScalarValue>)` containing each element as a scalar value.
    /// * `Ok(vec![])` for empty lists or `Option<Vec<T>>` with `None`.
    ///
    /// # Errors
    ///
    /// Returns `EvaluateError` if:
    /// * The path is not found ([`EvaluateError::NestedFieldNotFound`]).
    /// * The list elements are not scalar types ([`EvaluateError::UnsupportedType`]).
    pub fn evaluate<T: Serialize>(
        &self,
        value: &T,
    ) -> Result<Vec<FieldScalarValue>, EvaluateError> {
        let mut serializer =
            FieldValueExtractorSerializer::new_nested_list(self.path_segments.clone());
        value.serialize(&mut serializer)?;

        serializer
            .into_list_result()
            .ok_or_else(|| EvaluateError::NestedFieldNotFound {
                path: self.path_segments.clone(),
                failed_at_index: None, // Index unknown at this point
            })
    }
}