waddling-errors 0.7.3

Structured, secure-by-default diagnostic codes for distributed systems with no_std and role-based documentation
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
//! Severity levels for diagnostic codes

use core::fmt;

/// Diagnostic severity level (single-character prefix for 4-part codes)
///
/// Each severity gets a single-character prefix: `SEVERITY.COMPONENT.PRIMARY.SEQUENCE`
///
/// # Available Severities
///
/// | Severity | Char | Priority | Meaning |
/// |----------|------|----------|---------|
/// | Error | E | 8 | Operation failed |
/// | Blocked | B | 7 | Execution blocked/waiting |
/// | Critical | C | 6 | Severe issue requiring attention |
/// | Warning | W | 5 | Potential issue |
/// | Help | H | 4 | Helpful suggestion |
/// | Success | S | 3 | Operation succeeded |
/// | Completed | K | 2 | Task/phase completed |
/// | Info | I | 1 | Informational events |
/// | Trace | T | 0 | Execution traces |
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(u8)]
pub enum Severity {
    /// **Error (E)** - Operation failed
    Error = b'E',
    /// **Warning (W)** - Potential issue or caveat
    Warning = b'W',
    /// **Critical (C)** - Severe issue requiring attention
    Critical = b'C',
    /// **Blocked (B)** - Execution blocked/waiting
    Blocked = b'B',
    /// **Help (H)** - Helpful suggestion or recommendation
    Help = b'H',
    /// **Success (S)** - Operation succeeded
    Success = b'S',
    /// **Completed (K)** - Task or phase completed
    Completed = b'K',
    /// **Info (I)** - General informational events
    Info = b'I',
    /// **Trace (T)** - Execution traces and instrumentation
    Trace = b'T',
}

impl Severity {
    /// Get the single-character code (E, W, C, B, S, K, I, T)
    pub const fn as_char(self) -> char {
        self as u8 as char
    }

    /// Get the full name as a string slice (e.g., "Error", "Warning")
    pub const fn as_str(self) -> &'static str {
        match self {
            Severity::Error => "Error",
            Severity::Warning => "Warning",
            Severity::Critical => "Critical",
            Severity::Blocked => "Blocked",
            Severity::Help => "Help",
            Severity::Success => "Success",
            Severity::Completed => "Completed",
            Severity::Info => "Info",
            Severity::Trace => "Trace",
        }
    }

    /// Get a human-readable description of this severity level
    pub const fn description(self) -> &'static str {
        match self {
            Severity::Error => "Operation failed",
            Severity::Warning => "Potential issue or caveat",
            Severity::Critical => "Severe issue requiring attention",
            Severity::Blocked => "Execution blocked or waiting",
            Severity::Help => "Helpful suggestion or recommendation",
            Severity::Success => "Operation succeeded",
            Severity::Completed => "Task or phase completed",
            Severity::Info => "General informational events",
            Severity::Trace => "Execution traces and instrumentation",
        }
    }

    /// Get the priority level (0-8, higher = more severe)
    ///
    /// **Priority Scale:**
    /// - 0-1: Diagnostic (Trace, Info)
    /// - 2-3: Positive (Completed, Success)
    /// - 4: Suggestions (Help)
    /// - 5-6: Issues (Warning, Critical)
    /// - 7-8: Blocking (Blocked, Error)
    pub const fn priority(self) -> u8 {
        match self {
            Severity::Trace => 0,
            Severity::Info => 1,
            Severity::Completed => 2,
            Severity::Success => 3,
            Severity::Help => 4,
            Severity::Warning => 5,
            Severity::Critical => 6,
            Severity::Blocked => 7,
            Severity::Error => 8,
        }
    }

    /// Check if this severity **blocks execution**
    ///
    /// Returns `true` only for Error and Blocked.
    /// Critical is a severe warning but does NOT block.
    pub const fn is_blocking(self) -> bool {
        matches!(self, Severity::Error | Severity::Blocked)
    }

    /// Check if this is a **positive outcome** (Success/Completed)
    pub const fn is_positive(self) -> bool {
        matches!(self, Severity::Success | Severity::Completed)
    }

    /// Check if this is a **negative outcome** (Error/Warning/Critical/Blocked)
    pub const fn is_negative(self) -> bool {
        matches!(
            self,
            Severity::Error | Severity::Warning | Severity::Critical | Severity::Blocked
        )
    }

    /// Check if this is **neutral** (Info/Trace)
    pub const fn is_neutral(self) -> bool {
        matches!(self, Severity::Info | Severity::Trace)
    }

    /// Get emoji representation for visual display (requires "emoji" feature)
    ///
    /// Returns a unicode emoji that visually represents the severity level.
    /// Perfect for modern terminal UIs, logs, and documentation.
    ///
    /// # Emoji Mapping
    ///
    /// - Error: ❌ (cross mark)
    /// - Blocked: đŸšĢ (prohibited)
    /// - Critical: đŸ”Ĩ (fire - severe issue!)
    /// - Critical: đŸ”Ĩ (fire - severe issue!)
    /// - Warning: âš ī¸ (warning sign)
    /// - Help: 💡 (light bulb - helpful suggestion)
    /// - Success: ✅ (check mark)
    /// - Completed: âœ”ī¸ (check mark button)
    /// - Info: â„šī¸ (information)
    /// - Trace: 🔍 (magnifying glass)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use waddling_errors::Severity;
    ///
    /// println!("{} Error occurred!", Severity::Error.emoji());
    /// println!("{} Build successful!", Severity::Success.emoji());
    /// ```
    #[cfg(feature = "emoji")]
    pub const fn emoji(self) -> &'static str {
        match self {
            Severity::Error => "❌",
            Severity::Blocked => "đŸšĢ",
            Severity::Critical => "đŸ”Ĩ",
            Severity::Warning => "âš ī¸",
            Severity::Help => "💡",
            Severity::Success => "✅",
            Severity::Completed => "âœ”ī¸",
            Severity::Info => "â„šī¸",
            Severity::Trace => "🔍",
        }
    }

    /// Get ANSI color code for terminal display (requires "ansi-colors" feature)
    ///
    /// Returns the ANSI escape sequence to colorize terminal output.
    ///
    /// # Color Scheme
    ///
    /// - Error: Red (bold)
    /// - Blocked: Red
    /// - Critical: Yellow (bold)
    /// - Warning: Yellow
    /// - Help: Green
    /// - Success: Green (bold)
    /// - Completed: Green
    /// - Info: Cyan
    /// - Trace: Blue (dim)
    #[cfg(feature = "ansi-colors")]
    pub const fn ansi_color(self) -> &'static str {
        match self {
            Severity::Error => "\x1b[1;31m",    // Bold Red
            Severity::Blocked => "\x1b[31m",    // Red
            Severity::Critical => "\x1b[1;33m", // Bold Yellow
            Severity::Warning => "\x1b[33m",    // Yellow
            Severity::Help => "\x1b[32m",       // Green
            Severity::Success => "\x1b[1;32m",  // Bold Green
            Severity::Completed => "\x1b[32m",  // Green
            Severity::Info => "\x1b[36m",       // Cyan
            Severity::Trace => "\x1b[2;34m",    // Dim Blue
        }
    }

    /// ANSI reset code (requires "ansi-colors" feature)
    #[cfg(feature = "ansi-colors")]
    pub const ANSI_RESET: &'static str = "\x1b[0m";

    /// Get hex color for HTML/CSS display (light mode)
    ///
    /// Returns Radix Colors for light backgrounds per WDP Part 10.
    /// Uses step 11 (text) or step 9 (emphasis) for WCAG AA contrast.
    ///
    /// # WDP Part 10 Color Scheme (Radix Colors)
    ///
    /// - Error: #ce2c31 (red-11)
    /// - Blocked: #dc3e42 (red-10)
    /// - Critical: #cc4e00 (orange-11)
    /// - Warning: #ab6400 (amber-11)
    /// - Help: #218358 (green-11)
    /// - Success: #30a46c (green-9)
    /// - Completed: #008573 (teal-11)
    /// - Info: #0d74ce (blue-11)
    /// - Trace: #60646c (slate-11)
    pub const fn hex_color(self) -> &'static str {
        match self {
            Severity::Error => "#ce2c31",
            Severity::Blocked => "#dc3e42",
            Severity::Critical => "#cc4e00",
            Severity::Warning => "#ab6400",
            Severity::Help => "#218358",
            Severity::Success => "#30a46c",
            Severity::Completed => "#008573",
            Severity::Info => "#0d74ce",
            Severity::Trace => "#60646c",
        }
    }

    /// Get hex color for HTML/CSS display (dark mode)
    ///
    /// Returns Radix Colors dark scale for dark backgrounds per WDP Part 10.
    /// Perceptually matched with light mode colors for consistency.
    ///
    /// # WDP Part 10 Dark Mode Colors (Radix Colors Dark Scale)
    ///
    /// - Error: #ff9592 (red-11 dark)
    /// - Blocked: #ec5d5e (red-10 dark)
    /// - Critical: #ffa057 (orange-11 dark)
    /// - Warning: #ffca16 (amber-11 dark)
    /// - Help: #3dd68c (green-11 dark)
    /// - Success: #33b074 (green-10 dark)
    /// - Completed: #0bd8b6 (teal-11 dark)
    /// - Info: #70b8ff (blue-11 dark)
    /// - Trace: #b0b4ba (slate-11 dark)
    pub const fn hex_color_dark(self) -> &'static str {
        match self {
            Severity::Error => "#ff9592",
            Severity::Blocked => "#ec5d5e",
            Severity::Critical => "#ffa057",
            Severity::Warning => "#ffca16",
            Severity::Help => "#3dd68c",
            Severity::Success => "#33b074",
            Severity::Completed => "#0bd8b6",
            Severity::Info => "#70b8ff",
            Severity::Trace => "#b0b4ba",
        }
    }

    /// Get background color for HTML/CSS badges (light mode)
    ///
    /// Returns Radix Colors step 3 for light, subtle backgrounds per WDP Part 10.
    /// Perfect for badges, chips, and callout boxes.
    pub const fn hex_bg_color(self) -> &'static str {
        match self {
            Severity::Error => "#feebec",
            Severity::Blocked => "#ffdbdc",
            Severity::Critical => "#ffefd6",
            Severity::Warning => "#fff7c2",
            Severity::Help => "#e6f6eb",
            Severity::Success => "#d6f1df",
            Severity::Completed => "#e0f8f3",
            Severity::Info => "#e6f4fe",
            Severity::Trace => "#f0f0f3",
        }
    }

    /// Get background color for HTML/CSS badges (dark mode)
    ///
    /// Returns Radix Colors dark scale step 3 for dark, muted backgrounds per WDP Part 10.
    /// Perfect for badges, chips, and callout boxes in dark themes.
    pub const fn hex_bg_color_dark(self) -> &'static str {
        match self {
            Severity::Error => "#3b1219",
            Severity::Blocked => "#500f1c",
            Severity::Critical => "#331e0b",
            Severity::Warning => "#302008",
            Severity::Help => "#132d21",
            Severity::Success => "#113b29",
            Severity::Completed => "#0d2d2a",
            Severity::Info => "#0d2847",
            Severity::Trace => "#212225",
        }
    }
}

impl fmt::Display for Severity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_char())
    }
}

impl PartialOrd for Severity {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Severity {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        self.priority().cmp(&other.priority())
    }
}

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

    #[test]
    fn test_severity_ordering() {
        assert!(Severity::Trace.priority() < Severity::Error.priority());
        assert!(Severity::Warning.priority() < Severity::Critical.priority());
    }

    #[test]
    fn test_severity_comparison() {
        assert!(Severity::Trace < Severity::Error);
        assert!(Severity::Info < Severity::Warning);
        assert!(Severity::Warning < Severity::Critical);
        assert!(Severity::Critical < Severity::Blocked);
        assert!(Severity::Blocked < Severity::Error);
    }

    #[test]
    fn test_severity_blocking() {
        // Blocking
        assert!(Severity::Error.is_blocking());
        assert!(Severity::Blocked.is_blocking());

        // Non-blocking (Critical is a warning!)
        assert!(!Severity::Critical.is_blocking());
        assert!(!Severity::Warning.is_blocking());
        assert!(!Severity::Success.is_blocking());
        assert!(!Severity::Completed.is_blocking());
        assert!(!Severity::Info.is_blocking());
        assert!(!Severity::Trace.is_blocking());
    }

    #[test]
    fn test_severity_categorization() {
        // Positive
        assert!(Severity::Success.is_positive());
        assert!(Severity::Completed.is_positive());

        // Negative
        assert!(Severity::Error.is_negative());
        assert!(Severity::Warning.is_negative());
        assert!(Severity::Critical.is_negative());
        assert!(Severity::Blocked.is_negative());

        // Neutral
        assert!(Severity::Info.is_neutral());
        assert!(Severity::Trace.is_neutral());

        // Mutual exclusivity
        assert!(!Severity::Error.is_positive());
        assert!(!Severity::Success.is_negative());
        assert!(!Severity::Info.is_positive());
        assert!(!Severity::Info.is_negative());
    }

    #[test]
    fn test_severity_metadata() {
        assert_eq!(Severity::Error.as_str(), "Error");
        assert_eq!(Severity::Warning.as_str(), "Warning");
        assert_eq!(Severity::Critical.as_str(), "Critical");

        assert_eq!(Severity::Error.description(), "Operation failed");
        assert_eq!(Severity::Warning.description(), "Potential issue or caveat");

        assert_eq!(Severity::Error.as_char(), 'E');
        assert_eq!(Severity::Warning.as_char(), 'W');
    }

    #[test]
    fn test_severity_positive() {
        assert!(Severity::Success.is_positive());
        assert!(Severity::Completed.is_positive());
        assert!(!Severity::Error.is_positive());
        assert!(!Severity::Warning.is_positive());
        assert!(!Severity::Critical.is_positive());
        assert!(!Severity::Blocked.is_positive());
        assert!(!Severity::Info.is_positive());
        assert!(!Severity::Trace.is_positive());
    }

    #[cfg(feature = "emoji")]
    #[test]
    fn test_emoji() {
        assert_eq!(Severity::Error.emoji(), "❌");
        assert_eq!(Severity::Warning.emoji(), "âš ī¸");
        assert_eq!(Severity::Critical.emoji(), "đŸ”Ĩ");
        assert_eq!(Severity::Success.emoji(), "✅");
        assert_eq!(Severity::Completed.emoji(), "âœ”ī¸");
        assert_eq!(Severity::Info.emoji(), "â„šī¸");
        assert_eq!(Severity::Trace.emoji(), "🔍");
        assert_eq!(Severity::Blocked.emoji(), "đŸšĢ");
    }

    #[cfg(feature = "ansi-colors")]
    #[test]
    fn test_ansi_colors() {
        assert_eq!(Severity::Error.ansi_color(), "\x1b[1;31m");
        assert_eq!(Severity::Warning.ansi_color(), "\x1b[33m");
        assert_eq!(Severity::Success.ansi_color(), "\x1b[1;32m");
        assert_eq!(Severity::ANSI_RESET, "\x1b[0m");
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_serde() {
        use serde_json;

        let severity = Severity::Error;
        let json = serde_json::to_string(&severity).unwrap();
        let deserialized: Severity = serde_json::from_str(&json).unwrap();
        assert_eq!(severity, deserialized);
    }
}