use std::fmt;
use crate::ffi;
#[derive(Debug)]
pub enum Error {
Io(std::io::Error),
Cuda {
call: &'static str,
code: i32,
message: String,
},
TensorRt {
call: &'static str,
message: String,
},
UnknownTensor {
name: String,
available: Vec<String>,
},
UnsupportedDataType {
tensor: String,
code: i32,
},
DynamicShape {
tensor: String,
shape: Vec<i64>,
},
SizeMismatch {
tensor: String,
expected: usize,
found: usize,
},
TooManyDimensions {
found: usize,
max: usize,
},
InvalidTensorName(String),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Io(source) => write!(f, "io: {source}"),
Error::Cuda {
call,
code,
message,
} => write!(f, "cuda: {call} failed ({code}): {message}"),
Error::TensorRt { call, message } => {
if message.is_empty() {
write!(f, "tensorrt: {call} failed")
} else {
write!(f, "tensorrt: {call} failed: {message}")
}
}
Error::UnknownTensor { name, available } => {
let names: Vec<&str> = available.iter().map(String::as_str).collect();
write!(
f,
"no tensor named {name:?}; the engine has {}",
names.join(", ")
)
}
Error::UnsupportedDataType { tensor, code } => {
write!(
f,
"tensor {tensor:?} has data type code {code}, which this crate cannot size"
)
}
Error::DynamicShape { tensor, shape } => {
write!(
f,
"tensor {tensor:?} has dynamic dimensions {shape:?}; set an input shape first"
)
}
Error::SizeMismatch {
tensor,
expected,
found,
} => {
write!(
f,
"tensor {tensor:?} needs {expected} bytes, the buffer has {found}"
)
}
Error::TooManyDimensions { found, max } => {
write!(
f,
"shape has {found} dimensions, TensorRT allows at most {max}"
)
}
Error::InvalidTensorName(name) => write!(f, "tensor name {name:?} contains a NUL byte"),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::Io(source) => Some(source),
_ => None,
}
}
}
impl From<std::io::Error> for Error {
fn from(source: std::io::Error) -> Self {
Error::Io(source)
}
}
pub(crate) fn last_message() -> String {
let raw = unsafe { ffi::trt_last_error() };
if raw.is_null() {
return String::new();
}
unsafe { std::ffi::CStr::from_ptr(raw) }
.to_string_lossy()
.into_owned()
}
pub(crate) fn cuda_check(code: i32, call: &'static str) -> Result<(), Error> {
if code == 0 {
return Ok(());
}
let message = last_message();
Err(Error::Cuda {
call,
code,
message,
})
}
pub(crate) fn trt_check(code: i32, call: &'static str) -> Result<(), Error> {
if code == 0 {
return Ok(());
}
Err(Error::TensorRt {
call,
message: last_message(),
})
}