Skip to main content

litert/
error.rs

1// Copyright 2026 Google LLC.
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
15#![allow(non_upper_case_globals)]
16
17use crate::bindings::*;
18
19use std::fmt;
20
21/// Reason of the error. It provides information where in the binding code the error occurred.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum ErrorCause {
24    Unknown,
25    // compiled_model
26    CreateOptions,
27    SetOptionsHardwareAccelerators,
28    CreateCompiledModel,
29    GetCompiledModelInputBufferRequirements,
30    GetCompiledModelOutputBufferRequirements,
31    InputDoesntSupportAnyTensorBufferTypes,
32    RunCompiledModel,
33    // environment
34    NotSupportedLiteRtAnyType,
35    CreateEnvironment,
36    // model
37    GetSignatureKey,
38    GetSignatureSubgraph,
39    GetNumSignatureInputs,
40    GetSignatureInputName,
41    GetNumSignatureOutputs,
42    GetSignatureOutputName,
43    GetSignature,
44    GetTensorTypeId,
45    GetUnrankedTensorType,
46    GetRankedTensorType,
47    InvalidTensorTypeId,
48    GetTensorName,
49    GetNumSubgraphInputs,
50    GetNumSubgraphOutputs,
51    GetSubgraphInput,
52    SubgraphInputTensorByNameNotFound,
53    GetSubgraphOutput,
54    SubgraphOutputTensorByNameNotFound,
55    CreateModelFromFile,
56    CreateModelFromBuffer,
57    GetNumModelSubgraphs,
58    GetNumModelSignatures,
59    GetModelSignature,
60    //tensor_buffer
61    GetTensorBufferRequirementsBufferSize,
62    GetNumTensorBufferRequirementsSupportedBufferTypes,
63    GetTensorBufferRequirementsSupportedTensorBufferType,
64    InvalidElementTypeEnumValue,
65    InvalidTensorBufferTypeEnumValue,
66    CreateManagedTensorBuffer,
67    LockTensorBufferRead,
68    LockTensorBufferWrite,
69    GetTensorBufferPackedSize,
70    IncompatibleWriteType,
71    TensorBufferTooSmall,
72    IncompatibleReadType,
73    ReadBufferTooSmall,
74    // util
75    InvalidStringEncoding,
76}
77
78/// Error returned by the bindings.
79///
80/// It contains the reason of the error and the LiteRtStatus returned by the C code.
81///
82/// Error supports `fmt::Display` and `fmt::Debug` traits.
83///
84/// ```
85/// match(litert_status) {
86///     Ok(env) => { ... },
87///     Err(error) => {
88///         println!("Error: {:?}", error);
89///     }
90/// }
91/// ```
92#[derive(Clone, Copy, PartialEq, Eq)]
93pub struct Error {
94    cause: ErrorCause,
95    litert_status: LiteRtStatus,
96}
97
98impl fmt::Display for Error {
99    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100        write!(f, "Error: {:?}", self.cause)?;
101        let status_description = self.litert_status_description();
102        write!(f, " LiteRtStatus: {:?} [{}] ", self.litert_status, status_description)
103    }
104}
105
106impl fmt::Debug for Error {
107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108        fmt::Display::fmt(self, f)
109    }
110}
111
112impl std::error::Error for Error {}
113
114impl Error {
115    pub(crate) fn new(cause: ErrorCause, status: LiteRtStatus) -> Self {
116        Error { cause, litert_status: status }
117    }
118
119    /// Returns the reason of the error from the binding code.
120    pub fn cause(&self) -> ErrorCause {
121        self.cause
122    }
123
124    /// Returns the LiteRtStatus returned by the C code.
125    pub fn litert_status(&self) -> LiteRtStatus {
126        self.litert_status
127    }
128
129    /// Returns a string description of the LiteRtStatus returned by the C code.
130    pub fn litert_status_description(&self) -> String {
131        // LINT.IfChange(status_codes)
132        match self.litert_status {
133            LiteRtStatus_kLiteRtStatusOk => "kLiteRtStatusOk",
134
135            // Generic errors.
136            LiteRtStatus_kLiteRtStatusErrorInvalidArgument => "kLiteRtStatusErrorInvalidArgument",
137            LiteRtStatus_kLiteRtStatusErrorMemoryAllocationFailure => {
138                "kLiteRtStatusErrorMemoryAllocationFailure"
139            }
140            LiteRtStatus_kLiteRtStatusErrorRuntimeFailure => "kLiteRtStatusErrorRuntimeFailure",
141            LiteRtStatus_kLiteRtStatusErrorMissingInputTensor => {
142                "kLiteRtStatusErrorMissingInputTensor"
143            }
144            LiteRtStatus_kLiteRtStatusErrorUnsupported => "kLiteRtStatusErrorUnsupported",
145            LiteRtStatus_kLiteRtStatusErrorNotFound => "kLiteRtStatusErrorNotFound",
146            LiteRtStatus_kLiteRtStatusErrorTimeoutExpired => "kLiteRtStatusErrorTimeoutExpired",
147            LiteRtStatus_kLiteRtStatusErrorWrongVersion => "kLiteRtStatusErrorWrongVersion",
148            LiteRtStatus_kLiteRtStatusErrorUnknown => "kLiteRtStatusErrorUnknown",
149            LiteRtStatus_kLiteRtStatusErrorAlreadyExists => "kLiteRtStatusErrorAlreadyExists",
150
151            // Inference progression errors.
152            LiteRtStatus_kLiteRtStatusCancelled => "kLiteRtStatusCancelled",
153
154            // File and loading related errors.
155            LiteRtStatus_kLiteRtStatusErrorFileIO => "kLiteRtStatusErrorFileIO",
156            LiteRtStatus_kLiteRtStatusErrorInvalidFlatbuffer => {
157                "kLiteRtStatusErrorInvalidFlatbuffer"
158            }
159            LiteRtStatus_kLiteRtStatusErrorDynamicLoading => "kLiteRtStatusErrorDynamicLoading",
160            LiteRtStatus_kLiteRtStatusErrorSerialization => "kLiteRtStatusErrorSerialization",
161            LiteRtStatus_kLiteRtStatusErrorCompilation => "kLiteRtStatusErrorCompilation",
162
163            // IR related errors.
164            LiteRtStatus_kLiteRtStatusErrorIndexOOB => "kLiteRtStatusErrorIndexOOB",
165            LiteRtStatus_kLiteRtStatusErrorInvalidIrType => "kLiteRtStatusErrorInvalidIrType",
166            LiteRtStatus_kLiteRtStatusErrorInvalidGraphInvariant => {
167                "kLiteRtStatusErrorInvalidGraphInvariant"
168            }
169            LiteRtStatus_kLiteRtStatusErrorGraphModification => {
170                "kLiteRtStatusErrorGraphModification"
171            }
172
173            // Tool related errors.
174            LiteRtStatus_kLiteRtStatusErrorInvalidToolConfig => {
175                "kLiteRtStatusErrorInvalidToolConfig"
176            }
177
178            // Legalization related errors.
179            LiteRtStatus_kLiteRtStatusLegalizeNoMatch => "kLiteRtStatusLegalizeNoMatch",
180            LiteRtStatus_kLiteRtStatusErrorInvalidLegalization => {
181                "kLiteRtStatusErrorInvalidLegalization"
182            }
183
184            // Transformation related errors.
185            LiteRtStatus_kLiteRtStatusPatternNoMatch => "kLiteRtStatusPatternNoMatch",
186            LiteRtStatus_kLiteRtStatusInvalidTransformation => "kLiteRtStatusInvalidTransformation",
187
188            // Version related errors.
189            LiteRtStatus_kLiteRtStatusErrorUnsupportedRuntimeVersion => {
190                "kLiteRtStatusErrorUnsupportedRuntimeVersion"
191            }
192            LiteRtStatus_kLiteRtStatusErrorUnsupportedCompilerVersion => {
193                "kLiteRtStatusErrorUnsupportedCompilerVersion"
194            }
195            LiteRtStatus_kLiteRtStatusErrorIncompatibleByteCodeVersion => {
196                "kLiteRtStatusErrorIncompatibleByteCodeVersion"
197            }
198
199            // Shape related errors.
200            LiteRtStatus_kLiteRtStatusErrorUnsupportedOpShapeInferer => {
201                "kLiteRtStatusErrorUnsupportedOpShapeInferer"
202            }
203            LiteRtStatus_kLiteRtStatusErrorShapeInferenceFailed => {
204                "kLiteRtStatusErrorShapeInferenceFailed"
205            }
206
207            _ => "???",
208        }
209        // LINT.ThenChange(../../c/litert_common.h:status_codes)
210        .to_string()
211    }
212}