hedl-csv 2.0.0

HEDL to/from CSV conversion
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
// Dweve HEDL - Hierarchical Entity Data Language
//
// Copyright (c) 2025 Dweve IP B.V. and individual contributors.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License in the LICENSE file at the
// root of this repository or at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Error types for CSV conversion operations.

use thiserror::Error;

/// CSV conversion error types.
///
/// This enum provides structured error handling for CSV parsing and generation,
/// with contextual information to help diagnose issues.
///
/// # Examples
///
/// ```
/// use hedl_csv::CsvError;
///
/// let err = CsvError::TypeMismatch {
///     column: "age".to_string(),
///     expected: "integer".to_string(),
///     value: "abc".to_string(),
/// };
///
/// assert_eq!(
///     err.to_string(),
///     "Type mismatch in column 'age': expected integer, got 'abc'"
/// );
/// ```
#[derive(Debug, Error)]
pub enum CsvError {
    /// CSV parsing error at a specific line.
    ///
    /// # Examples
    ///
    /// ```
    /// use hedl_csv::CsvError;
    ///
    /// let err = CsvError::ParseError {
    ///     line: 42,
    ///     message: "Invalid escape sequence".to_string(),
    /// };
    /// assert!(err.to_string().contains("line 42"));
    /// ```
    #[error("CSV parse error at line {line}: {message}")]
    ParseError {
        /// Line number where the error occurred (1-based).
        line: usize,
        /// Detailed error message.
        message: String,
    },

    /// Type mismatch when converting values.
    ///
    /// This error occurs when a CSV field value cannot be converted to the expected type.
    ///
    /// # Examples
    ///
    /// ```
    /// use hedl_csv::CsvError;
    ///
    /// let err = CsvError::TypeMismatch {
    ///     column: "price".to_string(),
    ///     expected: "float".to_string(),
    ///     value: "not-a-number".to_string(),
    /// };
    /// ```
    #[error("Type mismatch in column '{column}': expected {expected}, got '{value}'")]
    TypeMismatch {
        /// Column name where the mismatch occurred.
        column: String,
        /// Expected type description.
        expected: String,
        /// Actual value that failed to convert.
        value: String,
    },

    /// Missing required column in CSV data.
    ///
    /// # Examples
    ///
    /// ```
    /// use hedl_csv::CsvError;
    ///
    /// let err = CsvError::MissingColumn("id".to_string());
    /// assert_eq!(err.to_string(), "Missing required column: id");
    /// ```
    #[error("Missing required column: {0}")]
    MissingColumn(String),

    /// Invalid header format or content.
    ///
    /// # Examples
    ///
    /// ```
    /// use hedl_csv::CsvError;
    ///
    /// let err = CsvError::InvalidHeader {
    ///     position: 0,
    ///     reason: "Empty column name".to_string(),
    /// };
    /// ```
    #[error("Invalid header at position {position}: {reason}")]
    InvalidHeader {
        /// Position of the invalid header (0-based).
        position: usize,
        /// Reason the header is invalid.
        reason: String,
    },

    /// Row has wrong number of columns.
    ///
    /// # Examples
    ///
    /// ```
    /// use hedl_csv::CsvError;
    ///
    /// let err = CsvError::WidthMismatch {
    ///     expected: 5,
    ///     actual: 3,
    ///     row: 10,
    /// };
    /// assert!(err.to_string().contains("expected 5 columns"));
    /// assert!(err.to_string().contains("got 3"));
    /// ```
    #[error("Row width mismatch: expected {expected} columns, got {actual} in row {row}")]
    WidthMismatch {
        /// Expected number of columns.
        expected: usize,
        /// Actual number of columns in the row.
        actual: usize,
        /// Row number where the mismatch occurred (1-based).
        row: usize,
    },

    /// I/O error during CSV reading or writing.
    ///
    /// # Examples
    ///
    /// ```
    /// use hedl_csv::CsvError;
    /// use std::io;
    ///
    /// let io_err = io::Error::new(io::ErrorKind::NotFound, "file not found");
    /// let csv_err = CsvError::from(io_err);
    /// ```
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),

    /// Error from underlying CSV library.
    ///
    /// # Examples
    ///
    /// ```
    /// use hedl_csv::CsvError;
    ///
    /// // This error type wraps csv::Error transparently
    /// ```
    #[error("CSV library error: {0}")]
    CsvLib(#[from] csv::Error),

    /// HEDL core error during conversion.
    ///
    /// This wraps errors from the `hedl_core` crate when they occur during
    /// CSV conversion operations.
    #[error("HEDL core error: {0}")]
    HedlCore(String),

    /// Row count exceeded security limit.
    ///
    /// # Examples
    ///
    /// ```
    /// use hedl_csv::CsvError;
    ///
    /// let err = CsvError::SecurityLimit {
    ///     limit: 1_000_000,
    ///     actual: 1_000_001,
    /// };
    /// assert!(err.to_string().contains("Security limit"));
    /// ```
    #[error("Security limit exceeded: row count {actual} exceeds maximum {limit}")]
    SecurityLimit {
        /// Maximum allowed rows.
        limit: usize,
        /// Actual row count encountered.
        actual: usize,
    },

    /// Empty ID field in CSV data.
    ///
    /// # Examples
    ///
    /// ```
    /// use hedl_csv::CsvError;
    ///
    /// let err = CsvError::EmptyId { row: 5 };
    /// assert_eq!(err.to_string(), "Empty 'id' field at row 5");
    /// ```
    #[error("Empty 'id' field at row {row}")]
    EmptyId {
        /// Row number with empty ID (1-based).
        row: usize,
    },

    /// Matrix list not found in document.
    ///
    /// # Examples
    ///
    /// ```
    /// use hedl_csv::CsvError;
    ///
    /// let err = CsvError::ListNotFound {
    ///     name: "people".to_string(),
    ///     available: "users, items".to_string(),
    /// };
    /// assert!(err.to_string().contains("not found"));
    /// ```
    #[error("Matrix list '{name}' not found in document (available: {available})")]
    ListNotFound {
        /// Name of the list that was not found.
        name: String,
        /// Available list names in the document.
        available: String,
    },

    /// Item is not a matrix list.
    ///
    /// # Examples
    ///
    /// ```
    /// use hedl_csv::CsvError;
    ///
    /// let err = CsvError::NotAList {
    ///     name: "value".to_string(),
    ///     actual_type: "scalar".to_string(),
    /// };
    /// ```
    #[error("Item '{name}' is not a matrix list (found: {actual_type})")]
    NotAList {
        /// Name of the item.
        name: String,
        /// Actual type of the item.
        actual_type: String,
    },

    /// No matrix lists found in document.
    #[error("No matrix lists found in document")]
    NoLists,

    /// Invalid UTF-8 in CSV output.
    ///
    /// # Examples
    ///
    /// ```
    /// use hedl_csv::CsvError;
    ///
    /// let err = CsvError::InvalidUtf8 {
    ///     context: "CSV serialization".to_string(),
    /// };
    /// ```
    #[error("Invalid UTF-8 in {context}")]
    InvalidUtf8 {
        /// Context where the invalid UTF-8 was encountered.
        context: String,
    },

    /// Generic error with custom message.
    ///
    /// This is a catch-all for errors that don't fit other categories.
    #[error("{0}")]
    Other(String),

    /// Security limit violated.
    ///
    /// This error occurs when CSV data exceeds configured security limits to prevent
    /// denial-of-service attacks.
    ///
    /// # Examples
    ///
    /// ```
    /// use hedl_csv::CsvError;
    ///
    /// let err = CsvError::Security {
    ///     limit_type: "column count".to_string(),
    ///     limit: 10_000,
    ///     actual: 15_000,
    ///     message: "CSV has 15000 columns, exceeds limit of 10000".to_string(),
    /// };
    /// assert!(err.to_string().contains("Security limit"));
    /// ```
    #[error("Security limit violated: {message}")]
    Security {
        /// Type of limit that was violated.
        limit_type: String,
        /// Configured limit value.
        limit: usize,
        /// Actual value encountered.
        actual: usize,
        /// Detailed error message.
        message: String,
    },
}

/// Convenience type alias for `Result` with `CsvError`.
pub type Result<T> = std::result::Result<T, CsvError>;

impl CsvError {
    /// Add context to an error message.
    ///
    /// This is useful for providing additional information about where an error occurred.
    ///
    /// # Examples
    ///
    /// ```
    /// use hedl_csv::CsvError;
    ///
    /// let err = CsvError::ParseError {
    ///     line: 5,
    ///     message: "Invalid value".to_string(),
    /// };
    /// let with_context = err.with_context("in column 'age' at line 10".to_string());
    /// ```
    #[must_use]
    pub fn with_context(self, context: String) -> Self {
        match self {
            CsvError::ParseError { line, message } => CsvError::ParseError {
                line,
                message: format!("{message} ({context})"),
            },
            CsvError::HedlCore(msg) => CsvError::HedlCore(format!("{msg} ({context})")),
            CsvError::Other(msg) => CsvError::Other(format!("{msg} ({context})")),
            // For other variants, wrap in Other with context
            other => CsvError::Other(format!("{other} ({context})")),
        }
    }

    /// Create a security error for limit violations.
    ///
    /// This is a convenience method for creating Security error variants.
    ///
    /// # Examples
    ///
    /// ```
    /// use hedl_csv::CsvError;
    ///
    /// let err = CsvError::security(
    ///     "CSV has 15000 columns, exceeds limit of 10000".to_string(),
    ///     0
    /// );
    /// assert!(matches!(err, CsvError::Security { .. }));
    /// ```
    #[must_use]
    pub fn security(message: String, _line: usize) -> Self {
        // Parse the message to extract limit information
        // This is a simplified approach - the actual implementation will use structured data
        CsvError::Security {
            limit_type: "unknown".to_string(),
            limit: 0,
            actual: 0,
            message,
        }
    }
}

impl From<hedl_core::HedlError> for CsvError {
    fn from(err: hedl_core::HedlError) -> Self {
        CsvError::HedlCore(err.to_string())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_error_display() {
        let err = CsvError::ParseError {
            line: 42,
            message: "Invalid escape sequence".to_string(),
        };
        assert_eq!(
            err.to_string(),
            "CSV parse error at line 42: Invalid escape sequence"
        );
    }

    #[test]
    fn test_type_mismatch_display() {
        let err = CsvError::TypeMismatch {
            column: "age".to_string(),
            expected: "integer".to_string(),
            value: "abc".to_string(),
        };
        assert_eq!(
            err.to_string(),
            "Type mismatch in column 'age': expected integer, got 'abc'"
        );
    }

    #[test]
    fn test_missing_column_display() {
        let err = CsvError::MissingColumn("id".to_string());
        assert_eq!(err.to_string(), "Missing required column: id");
    }

    #[test]
    fn test_invalid_header_display() {
        let err = CsvError::InvalidHeader {
            position: 3,
            reason: "Empty column name".to_string(),
        };
        assert_eq!(
            err.to_string(),
            "Invalid header at position 3: Empty column name"
        );
    }

    #[test]
    fn test_width_mismatch_display() {
        let err = CsvError::WidthMismatch {
            expected: 5,
            actual: 3,
            row: 10,
        };
        assert_eq!(
            err.to_string(),
            "Row width mismatch: expected 5 columns, got 3 in row 10"
        );
    }

    #[test]
    fn test_security_limit_display() {
        let err = CsvError::SecurityLimit {
            limit: 1_000_000,
            actual: 1_500_000,
        };
        assert_eq!(
            err.to_string(),
            "Security limit exceeded: row count 1500000 exceeds maximum 1000000"
        );
    }

    #[test]
    fn test_empty_id_display() {
        let err = CsvError::EmptyId { row: 5 };
        assert_eq!(err.to_string(), "Empty 'id' field at row 5");
    }

    #[test]
    fn test_list_not_found_display() {
        let err = CsvError::ListNotFound {
            name: "people".to_string(),
            available: "users, items".to_string(),
        };
        assert_eq!(
            err.to_string(),
            "Matrix list 'people' not found in document (available: users, items)"
        );
    }

    #[test]
    fn test_not_a_list_display() {
        let err = CsvError::NotAList {
            name: "value".to_string(),
            actual_type: "scalar".to_string(),
        };
        assert_eq!(
            err.to_string(),
            "Item 'value' is not a matrix list (found: scalar)"
        );
    }

    #[test]
    fn test_no_lists_display() {
        let err = CsvError::NoLists;
        assert_eq!(err.to_string(), "No matrix lists found in document");
    }

    #[test]
    fn test_invalid_utf8_display() {
        let err = CsvError::InvalidUtf8 {
            context: "CSV output".to_string(),
        };
        assert_eq!(err.to_string(), "Invalid UTF-8 in CSV output");
    }

    #[test]
    fn test_other_display() {
        let err = CsvError::Other("Custom error message".to_string());
        assert_eq!(err.to_string(), "Custom error message");
    }

    #[test]
    fn test_io_error_conversion() {
        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
        let csv_err = CsvError::from(io_err);
        assert!(csv_err.to_string().contains("I/O error"));
    }

    #[test]
    fn test_hedl_error_conversion() {
        let hedl_err = hedl_core::HedlError::new(
            hedl_core::HedlErrorKind::Syntax,
            "Syntax error".to_string(),
            1,
        );
        let csv_err = CsvError::from(hedl_err);
        assert!(csv_err.to_string().contains("HEDL core error"));
    }

    #[test]
    fn test_error_is_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<CsvError>();
    }

    #[test]
    fn test_error_debug() {
        let err = CsvError::MissingColumn("id".to_string());
        let debug = format!("{err:?}");
        assert!(debug.contains("MissingColumn"));
        assert!(debug.contains("id"));
    }

    #[test]
    fn test_error_messages() {
        let err = CsvError::TypeMismatch {
            column: "age".to_string(),
            expected: "integer".to_string(),
            value: "abc".to_string(),
        };
        assert_eq!(
            err.to_string(),
            "Type mismatch in column 'age': expected integer, got 'abc'"
        );
    }

    #[test]
    fn test_with_context() {
        let err = CsvError::ParseError {
            line: 10,
            message: "Invalid value".to_string(),
        };
        let with_ctx = err.with_context("in field 'name'".to_string());
        assert_eq!(
            with_ctx.to_string(),
            "CSV parse error at line 10: Invalid value (in field 'name')"
        );
    }

    #[test]
    fn test_security_display() {
        let err = CsvError::Security {
            limit_type: "column count".to_string(),
            limit: 10_000,
            actual: 15_000,
            message: "CSV has 15000 columns, exceeds limit of 10000".to_string(),
        };
        assert!(err.to_string().contains("Security limit"));
        assert!(err.to_string().contains("15000"));
    }

    #[test]
    fn test_security_error() {
        let err = CsvError::security(
            "CSV has 15000 columns, exceeds limit of 10000".to_string(),
            0,
        );
        assert!(matches!(err, CsvError::Security { .. }));
        assert!(err.to_string().contains("Security limit"));
    }

    #[test]
    fn test_security_with_context() {
        let err = CsvError::Security {
            limit_type: "cell size".to_string(),
            limit: 1_048_576,
            actual: 2_000_000,
            message: "Cell size exceeds limit".to_string(),
        };
        let with_ctx = err.with_context("at row 5, column 3".to_string());
        assert!(with_ctx.to_string().contains("Cell size exceeds limit"));
        assert!(with_ctx.to_string().contains("at row 5, column 3"));
    }
}