qubit_json/encode/jcs_encode_error_kind.rs
1// =============================================================================
2// Copyright (c) 2026 Haixing Hu.
3//
4// SPDX-License-Identifier: Apache-2.0
5//
6// Licensed under the Apache License, Version 2.0.
7// =============================================================================
8//! Defines stable categories for JCS encoding failures.
9
10use std::fmt;
11use std::str::FromStr;
12
13/// Stable category describing a failure while producing JCS output.
14///
15/// The string representation is stable and uses lowercase snake case, making
16/// the kind suitable for logs and interchange formats.
17///
18/// # Examples
19///
20/// ```
21/// use qubit_json::encode::JcsEncodeErrorKind;
22/// use std::str::FromStr;
23///
24/// let kind = JcsEncodeErrorKind::from_str("working_memory")
25/// .expect("known error kind");
26/// assert_eq!(kind.to_string(), "working_memory");
27/// ```
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
29pub enum JcsEncodeErrorKind {
30 /// Resource accounting rejected the value or output.
31 Budget,
32 /// The encoder's auxiliary working memory exceeded its configured limit.
33 WorkingMemory,
34 /// JCS serialization could not represent the value.
35 Serialize,
36 /// The external destination rejected output bytes.
37 Write,
38}
39
40impl fmt::Display for JcsEncodeErrorKind {
41 /// Writes the stable lowercase snake-case category name.
42 ///
43 /// # Parameters
44 ///
45 /// * `formatter` - Destination that receives the category name.
46 ///
47 /// # Errors
48 ///
49 /// Returns the formatter's error if writing the name fails.
50 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
51 formatter.write_str(match self {
52 Self::Budget => "budget",
53 Self::WorkingMemory => "working_memory",
54 Self::Serialize => "serialize",
55 Self::Write => "write",
56 })
57 }
58}
59
60impl FromStr for JcsEncodeErrorKind {
61 type Err = &'static str;
62
63 /// Parses a category name without ASCII case sensitivity.
64 ///
65 /// # Parameters
66 ///
67 /// * `value` - Category name to parse.
68 ///
69 /// # Returns
70 ///
71 /// The matching JCS encoding error category.
72 ///
73 /// # Errors
74 ///
75 /// Returns a static diagnostic when `value` is not a known category.
76 fn from_str(value: &str) -> Result<Self, Self::Err> {
77 if value.eq_ignore_ascii_case("budget") {
78 Ok(Self::Budget)
79 } else if value.eq_ignore_ascii_case("working_memory") {
80 Ok(Self::WorkingMemory)
81 } else if value.eq_ignore_ascii_case("serialize") {
82 Ok(Self::Serialize)
83 } else if value.eq_ignore_ascii_case("write") {
84 Ok(Self::Write)
85 } else {
86 Err("unknown JcsEncodeErrorKind")
87 }
88 }
89}