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
use std::cell::RefCell;
use std::error::Error;
use std::fmt::Display;
use std::iter::Enumerate;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use std::{fmt, io};

use owo_colors::{OwoColorize, Stream};

use super::NDJSONError;

/// Holds linked position information for errors encountered while processing
#[derive(Debug)]
pub struct IndexedNDJSONError {
    pub location: String,
    pub error: NDJSONError,
}

impl IndexedNDJSONError {
    pub(crate) fn new(location: String, error: NDJSONError) -> Self {
        Self { location, error }
    }
}

impl fmt::Display for IndexedNDJSONError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Line {}: {}", self.location, self.error)?;
        if let Some(source) = self.error.source() {
            write!(f, "; {source}")?;
        }
        Ok(())
    }
}

/// Threadsafe storage for errors enounter by parallel processing.
/// Counterpart to [`Errors`]
#[derive(Debug)]
pub struct ErrorsPar<E> {
    pub container: Arc<Mutex<Vec<E>>>,
}

impl<E> ErrorsPar<E> {
    pub fn new(container: Arc<Mutex<Vec<E>>>) -> Self {
        Self { container }
    }

    pub fn new_ref(&self) -> Self {
        Self {
            container: Arc::clone(&self.container),
        }
    }

    pub fn push(&self, value: E) {
        self.container.lock().expect("not poisoned").push(value)
    }
}

impl<E> Default for ErrorsPar<E> {
    fn default() -> Self {
        Self::new(Arc::new(Mutex::new(vec![])))
    }
}

impl<E: Display> fmt::Display for ErrorsPar<E> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for i in self.container.lock().unwrap().as_slice() {
            writeln!(f, "{i}")?;
        }
        Ok(())
    }
}

// TODO: Consider blend with ErrorsContainer Trait?
pub trait NDJSONProcessingErrors {
    fn eprint(&self) {}
}

impl<E: Display> NDJSONProcessingErrors for ErrorsPar<E> {
    fn eprint(&self) {
        let stream = Stream::Stdout;
        if !self.container.lock().unwrap().is_empty() {
            eprintln!("{}", self.if_supports_color(stream, |text| text.red()));
        }
    }
}

// TODO: Create ErrorContainer Trait?
/// Storage for errors enounter by processing
/// Counterpart to [`ErrorsPar`]
#[derive(Debug)]
pub struct Errors<E> {
    pub container: Rc<RefCell<Vec<E>>>,
}

impl<E> Errors<E> {
    pub fn new(container: Rc<RefCell<Vec<E>>>) -> Self {
        Self { container }
    }

    pub fn new_ref(&self) -> Self {
        Self {
            container: Rc::clone(&self.container),
        }
    }

    pub fn push(&self, value: E) {
        self.container.borrow_mut().push(value)
    }
}

impl<E: Display> NDJSONProcessingErrors for Errors<E> {
    fn eprint(&self) {
        let stream = Stream::Stdout;
        if !self.container.borrow().is_empty() {
            eprintln!("{}", self.if_supports_color(stream, |text| text.red()));
        }
    }
}

impl<E> Default for Errors<E> {
    fn default() -> Self {
        Self::new(Rc::new(RefCell::new(vec![])))
    }
}

impl<E: Display> fmt::Display for Errors<E> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for i in self.container.borrow().as_slice() {
            writeln!(f, "{i}")?;
        }
        Ok(())
    }
}

/// Iterator that skips, but keeps track of, `Err`s while processing
pub struct ErrFiltered<I, E> {
    iter: I,
    errors: Errors<E>,
}

impl<U, E, T, I: Iterator<Item = (U, Result<T, W>)>, W> ErrFiltered<I, E> {
    pub fn new(iter: I, errors: Errors<E>) -> Self {
        Self { iter, errors }
    }
}

impl<U: Display, T, I: Iterator<Item = (U, Result<T, impl Into<NDJSONError>>)>> Iterator
    for ErrFiltered<I, IndexedNDJSONError>
{
    type Item = (U, T);
    fn next(&mut self) -> Option<Self::Item> {
        loop {
            let (id, next_item) = self.iter.next()?;
            match next_item {
                Ok(item) => break Some((id, item)),
                Err(e) => {
                    let error: NDJSONError = e.into();
                    self.errors
                        .push(IndexedNDJSONError::new(format!("{id}"), error));
                }
            }
        }
    }
}

pub trait IntoErrFiltered<U, E, T, W>: Iterator<Item = (U, Result<T, W>)> + Sized {
    fn to_err_filtered(self, errors: Errors<E>) -> ErrFiltered<Self, E> {
        ErrFiltered::new(self, errors)
    }
}

impl<U, E, T, I: Iterator<Item = (U, Result<T, W>)>, W> IntoErrFiltered<U, E, T, W> for I {}

/// Iterator that enumerates all items and skips, but keeps track of, `Err`s while processing
pub struct EnumeratedErrFiltered<I, E> {
    iter: Enumerate<I>,
    errors: Errors<E>,
}

impl<E, T, I: Iterator<Item = Result<T, W>>, W> EnumeratedErrFiltered<I, E> {
    pub fn new(iter: I, errors: Errors<E>) -> Self {
        Self {
            iter: iter.enumerate(),
            errors,
        }
    }
}

impl<T, I> Iterator for EnumeratedErrFiltered<I, IndexedNDJSONError>
where
    I: Iterator<Item = Result<T, io::Error>>,
{
    type Item = (usize, T);
    fn next(&mut self) -> Option<Self::Item> {
        loop {
            let (i, next_item) = self.iter.next()?;
            let i = i + 1; // count lines from 1
            match next_item {
                Ok(item) => break Some((i, item)),
                Err(e) => {
                    self.errors.push(IndexedNDJSONError::new(
                        i.to_string(),
                        NDJSONError::IOError(e),
                    ));
                }
            }
        }
    }
}

pub trait IntoEnumeratedErrFiltered<E, T, W>: Iterator<Item = Result<T, W>> + Sized {
    fn to_enumerated_err_filtered(self, errors: Errors<E>) -> EnumeratedErrFiltered<Self, E> {
        EnumeratedErrFiltered::new(self, errors)
    }
}

impl<E, T, I: Iterator<Item = Result<T, W>>, W> IntoEnumeratedErrFiltered<E, T, W> for I {}