ndjson-stream 0.1.0

A library to read NDJSON-formatted data in a streaming manner.
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
use crate::as_bytes::AsBytes;
use crate::config::NdjsonConfig;
use crate::engine::NdjsonEngine;
use crate::fallible::{FallibleNdjsonError, FallibleNdjsonResult};

use std::convert::Infallible;
use std::iter::Fuse;

use serde::Deserialize;

use serde_json::error::Result as JsonResult;

struct MapResultInfallible<I> {
    inner: I
}

impl<I> MapResultInfallible<I> {
    fn new(inner: I) -> MapResultInfallible<I> {
        MapResultInfallible {
            inner
        }
    }
}

impl<I> Iterator for MapResultInfallible<I>
where
    I: Iterator
{
    type Item = Result<I::Item, Infallible>;

    fn next(&mut self) -> Option<Result<I::Item, Infallible>> {
        self.inner.next().map(Ok)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

/// Wraps an iterator of data blocks, i.e. types implementing [AsBytes], and offers an [Iterator]
/// implementation over parsed NDJSON-records according to [Deserialize]. See [from_iter] and
/// [from_iter_with_config] for more details.
pub struct NdjsonIter<T, I> {
    inner: FallibleNdjsonIter<T, MapResultInfallible<I>>
}

impl<T, I> NdjsonIter<T, I>
where
    I: Iterator
{

    /// Creates a new NDJSON-iterator wrapping the given `bytes_iterator` with default
    /// [NdjsonConfig].
    pub fn new(bytes_iterator: I) -> NdjsonIter<T, I> {
        let inner_bytes_iterator = MapResultInfallible::new(bytes_iterator);

        NdjsonIter {
            inner: FallibleNdjsonIter::new(inner_bytes_iterator)
        }
    }

    /// Creates a new NDJSON-iterator wrapping the given `bytes_iterator` with the given
    /// [NdjsonConfig] to control its behavior. See [NdjsonConfig] for more details.
    pub fn with_config(bytes_iterator: I, config: NdjsonConfig) -> NdjsonIter<T, I> {
        let inner_bytes_iterator = MapResultInfallible::new(bytes_iterator);

        NdjsonIter {
            inner: FallibleNdjsonIter::with_config(inner_bytes_iterator, config)
        }
    }
}

impl<T, I> Iterator for NdjsonIter<T, I>
where
    for<'deserialize> T: Deserialize<'deserialize>,
    I: Iterator,
    I::Item: AsBytes
{
    type Item = JsonResult<T>;

    fn next(&mut self) -> Option<JsonResult<T>> {
        Some(self.inner.next()?.map_err(FallibleNdjsonError::unwrap_json_error))
    }
}

/// Wraps an iterator of data blocks, i.e. types implementing [AsBytes], obtained by
/// [IntoIterator::into_iter] on `into_iter` and offers an [Iterator] implementation over parsed
/// NDJSON-records according to [Deserialize]. The parser is configured with the default
/// [NdjsonConfig].
///
/// # Example
///
/// ```
/// let data_blocks = vec![
///     "123\n",
///     "456\n789\n"
/// ];
///
/// let mut ndjson_iter = ndjson_stream::from_iter::<u32, _>(data_blocks);
///
/// assert!(matches!(ndjson_iter.next(), Some(Ok(123))));
/// assert!(matches!(ndjson_iter.next(), Some(Ok(456))));
/// assert!(matches!(ndjson_iter.next(), Some(Ok(789))));
/// assert!(ndjson_iter.next().is_none());
/// ```
pub fn from_iter<T, I>(into_iter: I) -> NdjsonIter<T, I::IntoIter>
where
    I: IntoIterator
{
    NdjsonIter::new(into_iter.into_iter())
}

/// Wraps an iterator of data blocks, i.e. types implementing [AsBytes], obtained by
/// [IntoIterator::into_iter] on `into_iter` and offers an [Iterator] implementation over parsed
/// NDJSON-records according to [Deserialize]. The parser is configured with the given
/// [NdjsonConfig].
///
/// # Example
///
/// ```
/// use ndjson_stream::config::{EmptyLineHandling, NdjsonConfig};
///
/// let data_blocks = vec![
///     "123\n",
///     "456\n   \n789\n"
/// ];
/// let config = NdjsonConfig::default().with_empty_line_handling(EmptyLineHandling::IgnoreBlank);
///
/// let mut ndjson_iter = ndjson_stream::from_iter_with_config::<u32, _>(data_blocks, config);
///
/// assert!(matches!(ndjson_iter.next(), Some(Ok(123))));
/// assert!(matches!(ndjson_iter.next(), Some(Ok(456))));
/// assert!(matches!(ndjson_iter.next(), Some(Ok(789))));
/// assert!(ndjson_iter.next().is_none());
/// ```
pub fn from_iter_with_config<T, I>(into_iter: I, config: NdjsonConfig) -> NdjsonIter<T, I::IntoIter>
where
    I: IntoIterator
{
    NdjsonIter::with_config(into_iter.into_iter(), config)
}

/// Wraps an iterator over [Result]s of data blocks, i.e. types implementing [AsBytes], and offers
/// an [Iterator] implementation over parsed NDJSON-records according to [Deserialize], forwarding
/// potential errors returned by the wrapped iterator. See [from_fallible_iter] and
/// [from_fallible_iter_with_config] for more details.
pub struct FallibleNdjsonIter<T, I> {
    engine: NdjsonEngine<T>,
    bytes_iterator: Fuse<I>
}

impl<T, I> FallibleNdjsonIter<T, I>
where
    I: Iterator
{

    /// Creates a new fallible NDJSON-iterator wrapping the given `bytes_iterator` with default
    /// [NdjsonConfig].
    pub fn new(bytes_iterator: I) -> FallibleNdjsonIter<T, I> {
        FallibleNdjsonIter {
            engine: NdjsonEngine::new(),
            bytes_iterator: bytes_iterator.fuse()
        }
    }

    /// Creates a new fallible NDJSON-iterator wrapping the given `bytes_iterator` with the given
    /// [NdjsonConfig] to control its behavior. See [NdjsonConfig] for more details.
    pub fn with_config(bytes_iterator: I, config: NdjsonConfig) -> FallibleNdjsonIter<T, I> {
        FallibleNdjsonIter {
            engine: NdjsonEngine::with_config(config),
            bytes_iterator: bytes_iterator.fuse()
        }
    }
}

impl<T, I, B, E> Iterator for FallibleNdjsonIter<T, I>
where
    for<'deserialize> T: Deserialize<'deserialize>,
    I: Iterator<Item = Result<B, E>>,
    B: AsBytes
{
    type Item = FallibleNdjsonResult<T, E>;

    fn next(&mut self) -> Option<FallibleNdjsonResult<T, E>> {
        loop {
            if let Some(result) = self.engine.pop() {
                return match result {
                    Ok(value) => Some(Ok(value)),
                    Err(error) => Some(Err(FallibleNdjsonError::JsonError(error)))
                }
            }

            match self.bytes_iterator.next() {
                Some(Ok(bytes)) => self.engine.input(bytes),
                Some(Err(error)) => return Some(Err(FallibleNdjsonError::InputError(error))),
                None => {
                    self.engine.finalize();
                    return self.engine.pop()
                        .map(|res| res.map_err(FallibleNdjsonError::JsonError));
                }
            }
        }
    }
}

/// Wraps an iterator of [Result]s of data blocks, i.e. types implementing [AsBytes], obtained by
/// [IntoIterator::into_iter] on `into_iter` and offers an [Iterator] implementation over parsed
/// NDJSON-records according to [Deserialize]. Errors in the wrapped iterator are forwarded via
/// [FallibleNdjsonError::InputError], while parsing errors are indicated via
/// [FallibleNdjsonError::JsonError]. The parser is configured with the default [NdjsonConfig].
///
/// # Example
///
/// ```
/// use ndjson_stream::fallible::FallibleNdjsonError;
///
/// let data_block_results = vec![
///     Ok("123\n"),
///     Err("some error"),
///     Ok("456\n789\n")
/// ];
///
/// let mut ndjson_iter = ndjson_stream::from_fallible_iter::<u32, _>(data_block_results);
///
/// assert!(matches!(ndjson_iter.next(), Some(Ok(123))));
/// assert!(matches!(ndjson_iter.next(), Some(Err(FallibleNdjsonError::InputError("some error")))));
/// assert!(matches!(ndjson_iter.next(), Some(Ok(456))));
/// assert!(matches!(ndjson_iter.next(), Some(Ok(789))));
/// assert!(ndjson_iter.next().is_none());
/// ```
pub fn from_fallible_iter<T, I>(into_iter: I) -> FallibleNdjsonIter<T, I::IntoIter>
where
    I: IntoIterator
{
    FallibleNdjsonIter::new(into_iter.into_iter())
}

/// Wraps an iterator of [Result]s of data blocks, i.e. types implementing [AsBytes], obtained by
/// [IntoIterator::into_iter] on `into_iter` and offers an [Iterator] implementation over parsed
/// NDJSON-records according to [Deserialize]. Errors in the wrapped iterator are forwarded via
/// [FallibleNdjsonError::InputError], while parsing errors are indicated via
/// [FallibleNdjsonError::JsonError]. The parser is configured with the given [NdjsonConfig].
///
/// # Example
///
/// ```
/// use ndjson_stream::config::{EmptyLineHandling, NdjsonConfig};
/// use ndjson_stream::fallible::FallibleNdjsonError;
///
/// let data_block_results = vec![
///     Ok("123\n"),
///     Err("some error"),
///     Ok("456\n   \n789\n")
/// ];
/// let config = NdjsonConfig::default().with_empty_line_handling(EmptyLineHandling::IgnoreBlank);
///
/// let mut ndjson_iter =
///     ndjson_stream::from_fallible_iter_with_config::<u32, _>(data_block_results, config);
///
/// assert!(matches!(ndjson_iter.next(), Some(Ok(123))));
/// assert!(matches!(ndjson_iter.next(), Some(Err(FallibleNdjsonError::InputError("some error")))));
/// assert!(matches!(ndjson_iter.next(), Some(Ok(456))));
/// assert!(matches!(ndjson_iter.next(), Some(Ok(789))));
/// assert!(ndjson_iter.next().is_none());
/// ```
pub fn from_fallible_iter_with_config<T, I>(into_iter: I, config: NdjsonConfig)
    -> FallibleNdjsonIter<T, I::IntoIter>
where
    I: IntoIterator
{
    FallibleNdjsonIter::with_config(into_iter.into_iter(), config)
}

#[cfg(test)]
mod tests {

    use super::*;

    use kernal::prelude::*;

    use std::iter;

    use crate::config::EmptyLineHandling;
    use crate::test_util::{FallibleNdjsonResultAssertions, SingleThenPanicIter, TestStruct};

    fn collect<I>(into_iter: I) -> Vec<JsonResult<TestStruct>>
    where
        I: IntoIterator,
        I::Item: AsBytes
    {
        from_iter(into_iter).collect::<Vec<_>>()
    }

    #[test]
    fn empty_iter_results_in_empty_results() {
        assert_that!(collect::<_>(iter::empty::<&[u8]>())).is_empty();
    }

    #[test]
    fn singleton_iter_with_single_json_line() {
        let iter = iter::once("{\"key\":1,\"value\":2}\n");

        assert_that!(collect(iter)).satisfies_exactly_in_given_order(dyn_assertions!(
            |it| assert_that!(it).contains_value(TestStruct { key: 1, value: 2 })

        ));
    }

    #[test]
    fn multiple_iter_items_compose_single_json_line() {
        let vec = vec!["{\"key\"", ":12,", "\"value\"", ":34}\n"];

        assert_that!(collect(vec)).satisfies_exactly_in_given_order(dyn_assertions!(
            |it| assert_that!(it).contains_value(TestStruct { key: 12, value: 34 })

        ));
    }

    #[test]
    fn wrapped_iter_not_queried_while_sufficient_data_remains() {
        let iter = SingleThenPanicIter {
            data: Some("{\"key\":1,\"value\":2}\n{\"key\":3,\"value\":4}\n".to_owned())
        };
        let mut ndjson_iter = NdjsonIter::<TestStruct, _>::new(iter);

        assert_that!(ndjson_iter.next()).is_some();
        assert_that!(ndjson_iter.next()).is_some();
    }

    #[test]
    fn iter_with_parse_always_config_respects_config() {
        let iter = iter::once("{\"key\":1,\"value\":2}\n\n");
        let config = NdjsonConfig::default()
            .with_empty_line_handling(EmptyLineHandling::ParseAlways);
        let mut ndjson_iter: NdjsonIter<TestStruct, _> = from_iter_with_config(iter, config);

        assert_that!(ndjson_iter.next()).to_value().is_ok();
        assert_that!(ndjson_iter.next()).to_value().is_err();
    }

    #[test]
    fn iter_with_ignore_empty_config_respects_config() {
        let iter = iter::once("{\"key\":1,\"value\":2}\n\n");
        let config = NdjsonConfig::default()
            .with_empty_line_handling(EmptyLineHandling::IgnoreEmpty);
        let mut ndjson_iter: NdjsonIter<TestStruct, _> = from_iter_with_config(iter, config);

        assert_that!(ndjson_iter.next()).to_value().is_ok();
        assert_that!(ndjson_iter.next()).is_none();
    }

    #[test]
    fn iter_with_parse_rest_handles_valid_finalization() {
        let iter = iter::once("{\"key\":1,\"value\":2}");
        let config = NdjsonConfig::default().with_parse_rest(true);
        let mut ndjson_iter: NdjsonIter<TestStruct, _> = from_iter_with_config(iter, config);

        assert_that!(ndjson_iter.next()).to_value().contains_value(TestStruct { key: 1, value: 2 });
        assert_that!(ndjson_iter.next()).is_none();
    }

    #[test]
    fn iter_with_parse_rest_handles_invalid_finalization() {
        let iter = iter::once("{\"key\":1,");
        let config = NdjsonConfig::default().with_parse_rest(true);
        let mut ndjson_iter: NdjsonIter<TestStruct, _> = from_iter_with_config(iter, config);

        assert_that!(ndjson_iter.next()).to_value().is_err();
        assert_that!(ndjson_iter.next()).is_none();
    }

    #[test]
    fn iter_without_parse_rest_does_not_handle_finalization() {
        let iter = iter::once("some text");
        let config = NdjsonConfig::default().with_parse_rest(false);
        let mut ndjson_iter: NdjsonIter<TestStruct, _> = from_iter_with_config(iter, config);

        assert_that!(ndjson_iter.next()).is_none();
    }

    #[test]
    fn iter_fuses_bytes_iter() {
        #[derive(Default)]
        struct NoneThenPanicIter {
            returned_none: bool
        }

        impl Iterator for NoneThenPanicIter {
            type Item = Vec<u8>;

            fn next(&mut self) -> Option<Self::Item> {
                if self.returned_none {
                    panic!("iterator queried twice");
                }

                self.returned_none = true;
                None
            }
        }

        let iter = NoneThenPanicIter::default();
        let config = NdjsonConfig::default().with_parse_rest(true);
        let mut ndjson_iter: NdjsonIter<TestStruct, _> = from_iter_with_config(iter, config);

        assert_that!(ndjson_iter.next()).is_none();
        assert_that!(ndjson_iter.next()).is_none();
    }

    #[test]
    fn fallible_iter_correctly_forwards_json_error() {
        let iter = iter::once::<Result<&str, &str>>(Ok("\n"));
        let mut fallible_ndjson_iter: FallibleNdjsonIter<TestStruct, _> = from_fallible_iter(iter);

        assert_that!(fallible_ndjson_iter.next()).to_value().is_json_error();
    }

    #[test]
    fn fallible_iter_correctly_forwards_input_error() {
        let iter = iter::once::<Result<&str, &str>>(Err("test message"));
        let mut fallible_ndjson_iter: FallibleNdjsonIter<TestStruct, _> = from_fallible_iter(iter);

        assert_that!(fallible_ndjson_iter.next()).to_value().is_input_error("test message");
    }

    #[test]
    fn fallible_iter_operates_correctly_with_interspersed_errors() {
        let data_vec = vec![
            Ok("{\"key\":42,\"val"),
            Err("test message 1"),
            Ok("ue\":24}\n{\"key\":21,\"value\":12}\ninvalid json\n"),
            Err("test message 2"),
            Ok("{\"key\":63,\"value\":36}\n")
        ];
        let fallible_ndjson_iter: FallibleNdjsonIter<TestStruct, _> =
            from_fallible_iter(data_vec);

        assert_that!(fallible_ndjson_iter.collect::<Vec<_>>())
            .satisfies_exactly_in_given_order(dyn_assertions!(
                |it| assert_that!(it).is_input_error("test message 1"),
                |it| assert_that!(it).contains_value(TestStruct { key: 42, value: 24 }),
                |it| assert_that!(it).contains_value(TestStruct { key: 21, value: 12 }),
                |it| assert_that!(it).is_json_error(),
                |it| assert_that!(it).is_input_error("test message 2"),
                |it| assert_that!(it).contains_value(TestStruct { key: 63, value: 36 })

            ));
    }
}