From 26a029d407be480d791972afb5975cf62c9360a6 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Fri, 19 Apr 2024 02:47:55 +0200 Subject: Adding upstream version 124.0.1. Signed-off-by: Daniel Baumann --- xpcom/rust/nserror/Cargo.toml | 11 ++++++ xpcom/rust/nserror/src/lib.rs | 79 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+) create mode 100644 xpcom/rust/nserror/Cargo.toml create mode 100644 xpcom/rust/nserror/src/lib.rs (limited to 'xpcom/rust/nserror') diff --git a/xpcom/rust/nserror/Cargo.toml b/xpcom/rust/nserror/Cargo.toml new file mode 100644 index 0000000000..4fca5a4c2c --- /dev/null +++ b/xpcom/rust/nserror/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "nserror" +version = "0.1.0" +authors = ["Nika Layzell "] +license = "MPL-2.0" +description = "Rust bindings to xpcom nsresult and NS_ERROR_ values" +edition = "2018" + +[dependencies] +nsstring = { path = "../nsstring" } +mozbuild = "0.1" diff --git a/xpcom/rust/nserror/src/lib.rs b/xpcom/rust/nserror/src/lib.rs new file mode 100644 index 0000000000..e4107d1b57 --- /dev/null +++ b/xpcom/rust/nserror/src/lib.rs @@ -0,0 +1,79 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +use nsstring::{nsACString, nsCString}; +use std::error::Error; +use std::fmt; + +/// The type of errors in gecko. Uses a newtype to provide additional type +/// safety in Rust and #[repr(transparent)] to ensure the same representation +/// as the C++ equivalent. +#[repr(transparent)] +#[allow(non_camel_case_types)] +#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)] +pub struct nsresult(pub u32); + +impl nsresult { + pub fn failed(self) -> bool { + (self.0 >> 31) != 0 + } + + pub fn succeeded(self) -> bool { + !self.failed() + } + + pub fn to_result(self) -> Result<(), nsresult> { + if self.failed() { + Err(self) + } else { + Ok(()) + } + } + + /// Get a printable name for the nsresult error code. This function returns + /// a nsCString<'static>, which implements `Display`. + pub fn error_name(self) -> nsCString { + let mut cstr = nsCString::new(); + unsafe { + Gecko_GetErrorName(self, &mut *cstr); + } + cstr + } +} + +impl fmt::Display for nsresult { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.error_name()) + } +} + +impl fmt::Debug for nsresult { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.error_name()) + } +} + +impl From> for nsresult +where + E: Into, +{ + fn from(result: Result) -> nsresult { + match result { + Ok(_) => NS_OK, + Err(e) => e.into(), + } + } +} + +impl Error for nsresult {} + +extern "C" { + fn Gecko_GetErrorName(rv: nsresult, cstr: *mut nsACString); +} + +mod error_list { + include!(mozbuild::objdir_path!("xpcom/base/error_list.rs")); +} + +pub use error_list::*; -- cgit v1.2.3