risc0_zkvm/serde/
err.rs

1// Copyright 2024 RISC Zero, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use alloc::string::{String, ToString};
16use core::fmt::{Display, Formatter};
17
18/// Errors used by Serde
19#[derive(Clone, Debug, Eq, PartialEq)]
20pub enum Error {
21    /// A custom error
22    Custom(String),
23    /// Found a bool that wasn't 0 or 1
24    DeserializeBadBool,
25    /// Found an invalid unicode char
26    DeserializeBadChar,
27    /// Found an Option discriminant that wasn't 0 or 1
28    DeserializeBadOption,
29    /// Tried to parse invalid utf-8
30    DeserializeBadUtf8,
31    /// Unexpected end during deserialization
32    DeserializeUnexpectedEnd,
33    /// Not supported
34    NotSupported,
35    /// The serialize buffer is full
36    SerializeBufferFull,
37}
38
39/// A Result type for `risc0_zkvm::serde` operations that can fail
40pub type Result<T> = core::result::Result<T, Error>;
41
42impl Display for Error {
43    fn fmt(&self, formatter: &mut Formatter) -> core::fmt::Result {
44        formatter.write_str(match self {
45            Self::Custom(msg) => msg,
46            Self::DeserializeBadBool => "Found a bool that wasn't 0 or 1",
47            Self::DeserializeBadChar => "Found an invalid unicode char",
48            Self::DeserializeBadOption => "Found an Option discriminant that wasn't 0 or 1",
49            Self::DeserializeBadUtf8 => "Tried to parse invalid utf-8",
50            Self::DeserializeUnexpectedEnd => "Unexpected end during deserialization",
51            Self::NotSupported => "Not supported",
52            Self::SerializeBufferFull => "The serialize buffer is full",
53        })
54    }
55}
56
57impl serde::ser::Error for Error {
58    fn custom<T: Display>(msg: T) -> Self {
59        Error::Custom(msg.to_string())
60    }
61}
62
63impl serde::de::Error for Error {
64    fn custom<T: Display>(msg: T) -> Self {
65        Error::Custom(msg.to_string())
66    }
67}
68
69// This is an alias for either std::Error, or serde's no_std error replacement.
70impl serde::ser::StdError for Error {}