errno-0.3.8/.cargo_vcs_info.json0000644000000001360000000000100121710ustar { "git": { "sha1": "529718762b1f752ccc894de5380d3aa10889733d" }, "path_in_vcs": "" }errno-0.3.8/.github/dependabot.yml000064400000000000000000000003171046102023000151520ustar 00000000000000version: 2 updates: - package-ecosystem: "cargo" directory: "/" schedule: interval: "weekly" - package-ecosystem: "github-actions" directory: "/" schedule: interval: "weekly" errno-0.3.8/.github/workflows/main.yml000064400000000000000000000034431046102023000160310ustar 00000000000000on: push: branches: - main pull_request: schedule: - cron: '5 21 * * 5' workflow_dispatch: name: CI jobs: test: name: Test runs-on: ${{ matrix.os }} strategy: matrix: os: [ubuntu-latest, macos-latest, windows-latest] rust: [stable, nightly, '1.56'] steps: - name: Checkout repository uses: actions/checkout@v4 - name: Install toolchain uses: dtolnay/rust-toolchain@master with: toolchain: ${{ matrix.rust }} - name: Setup cache uses: Swatinem/rust-cache@v2 - name: Test (no features) run: cargo test --no-default-features - name: Test (all features) run: cargo test --all-features wasi: name: Test WASI runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v4 - name: Install toolchain uses: dtolnay/rust-toolchain@nightly with: targets: wasm32-wasi - name: Install wasmtime run: | curl https://wasmtime.dev/install.sh -sSf | bash echo "$HOME/.wasmtime/bin" >> $GITHUB_PATH - name: Test (no features) run: CARGO_TARGET_WASM32_WASI_RUNNER=wasmtime cargo test --target wasm32-wasi --no-default-features - name: Test (all features) run: CARGO_TARGET_WASM32_WASI_RUNNER=wasmtime cargo test --target wasm32-wasi --all-features lints: name: Rustfmt & Clippy runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v4 - name: Install toolchain uses: dtolnay/rust-toolchain@stable with: components: rustfmt, clippy - name: Check formatting run: cargo fmt --check - name: Check clippy run: cargo clippy -- -D warnings errno-0.3.8/.gitignore000064400000000000000000000000221046102023000127430ustar 00000000000000target Cargo.lock errno-0.3.8/CHANGELOG.md000064400000000000000000000063101046102023000125720ustar 00000000000000# [Unreleased] # [0.3.8] - 2023-11-27 - Update to windows-sys 0.52. [#91](https://github.com/lambda-fairy/rust-errno/pull/91) - Update minimum Rust version to 1.56 [#91](https://github.com/lambda-fairy/rust-errno/pull/91) # [0.3.7] - 2023-11-15 - Fix `to_string()` handling for unknown error codes [#88](https://github.com/lambda-fairy/rust-errno/pull/88) # [0.3.6] - 2023-11-07 - Add support for tvOS and watchOS [#84](https://github.com/lambda-fairy/rust-errno/pull/84) - Added support for vita target [#86](https://github.com/lambda-fairy/rust-errno/pull/86) # [0.3.5] - 2023-10-08 - Use __errno_location on DragonFly BSD [#82](https://github.com/lambda-fairy/rust-errno/pull/82) # [0.3.4] - 2023-10-01 - Add GNU/Hurd support [#80](https://github.com/lambda-fairy/rust-errno/pull/80) # [0.3.3] - 2023-08-28 - Disable "libc/std" in no-std configurations. [#77](https://github.com/lambda-fairy/rust-errno/pull/77) - Bump errno-dragonfly to 0.1.2 [#75](https://github.com/lambda-fairy/rust-errno/pull/75) - Support for the ESP-IDF framework [#74](https://github.com/lambda-fairy/rust-errno/pull/74) # [0.3.2] - 2023-07-30 - Fix build on Hermit [#73](https://github.com/lambda-fairy/rust-errno/pull/73) - Add support for QNX Neutrino [#72](https://github.com/lambda-fairy/rust-errno/pull/72) # [0.3.1] - 2023-04-08 - Correct link name on redox [#69](https://github.com/lambda-fairy/rust-errno/pull/69) - Update windows-sys requirement from 0.45 to 0.48 [#70](https://github.com/lambda-fairy/rust-errno/pull/70) # [0.3.0] - 2023-02-12 - Add haiku support [#42](https://github.com/lambda-fairy/rust-errno/pull/42) - Add AIX support [#54](https://github.com/lambda-fairy/rust-errno/pull/54) - Add formatting with `#![no_std]` [#44](https://github.com/lambda-fairy/rust-errno/pull/44) - Switch from `winapi` to `windows-sys` [#55](https://github.com/lambda-fairy/rust-errno/pull/55) - Update minimum Rust version to 1.48 [#48](https://github.com/lambda-fairy/rust-errno/pull/48) [#55](https://github.com/lambda-fairy/rust-errno/pull/55) - Upgrade to Rust 2018 edition [#59](https://github.com/lambda-fairy/rust-errno/pull/59) - wasm32-wasi: Use `__errno_location` instead of `feature(thread_local)`. [#66](https://github.com/lambda-fairy/rust-errno/pull/66) # [0.2.8] - 2021-10-27 - Optionally support no_std [#31](https://github.com/lambda-fairy/rust-errno/pull/31) [Unreleased]: https://github.com/lambda-fairy/rust-errno/compare/v0.3.8...HEAD [0.3.8]: https://github.com/lambda-fairy/rust-errno/compare/v0.3.7...v0.3.8 [0.3.7]: https://github.com/lambda-fairy/rust-errno/compare/v0.3.6...v0.3.7 [0.3.6]: https://github.com/lambda-fairy/rust-errno/compare/v0.3.5...v0.3.6 [0.3.5]: https://github.com/lambda-fairy/rust-errno/compare/v0.3.4...v0.3.5 [0.3.4]: https://github.com/lambda-fairy/rust-errno/compare/v0.3.3...v0.3.4 [0.3.3]: https://github.com/lambda-fairy/rust-errno/compare/v0.3.2...v0.3.3 [0.3.2]: https://github.com/lambda-fairy/rust-errno/compare/v0.3.1...v0.3.2 [0.3.1]: https://github.com/lambda-fairy/rust-errno/compare/v0.3.0...v0.3.1 [0.3.0]: https://github.com/lambda-fairy/rust-errno/compare/v0.2.8...v0.3.0 [0.2.8]: https://github.com/lambda-fairy/rust-errno/compare/v0.2.7...v0.2.8 errno-0.3.8/Cargo.toml0000644000000024510000000000100101710ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" rust-version = "1.56" name = "errno" version = "0.3.8" authors = ["Chris Wong "] description = "Cross-platform interface to the `errno` variable." documentation = "https://docs.rs/errno" readme = "README.md" categories = [ "no-std", "os", ] license = "MIT OR Apache-2.0" repository = "https://github.com/lambda-fairy/rust-errno" [features] default = ["std"] std = ["libc/std"] [target."cfg(target_os=\"hermit\")".dependencies.libc] version = "0.2" default-features = false [target."cfg(target_os=\"wasi\")".dependencies.libc] version = "0.2" default-features = false [target."cfg(unix)".dependencies.libc] version = "0.2" default-features = false [target."cfg(windows)".dependencies.windows-sys] version = "0.52" features = [ "Win32_Foundation", "Win32_System_Diagnostics_Debug", ] errno-0.3.8/Cargo.toml.orig000064400000000000000000000015051046102023000136510ustar 00000000000000[package] name = "errno" version = "0.3.8" authors = ["Chris Wong "] license = "MIT OR Apache-2.0" edition = "2018" documentation = "https://docs.rs/errno" repository = "https://github.com/lambda-fairy/rust-errno" description = "Cross-platform interface to the `errno` variable." categories = ["no-std", "os"] rust-version = "1.56" [target.'cfg(unix)'.dependencies] libc = { version = "0.2", default-features = false } [target.'cfg(windows)'.dependencies.windows-sys] version = "0.52" features = [ "Win32_Foundation", "Win32_System_Diagnostics_Debug", ] [target.'cfg(target_os="wasi")'.dependencies] libc = { version = "0.2", default-features = false } [target.'cfg(target_os="hermit")'.dependencies] libc = { version = "0.2", default-features = false } [features] default = ["std"] std = ["libc/std"] errno-0.3.8/LICENSE-APACHE000064400000000000000000000251371046102023000127150ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. errno-0.3.8/LICENSE-MIT000064400000000000000000000020361046102023000124160ustar 00000000000000Copyright (c) 2014 Chris Wong Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. errno-0.3.8/README.md000064400000000000000000000026061046102023000122440ustar 00000000000000# errno [![CI](https://github.com/lambda-fairy/rust-errno/actions/workflows/main.yml/badge.svg)](https://github.com/lambda-fairy/rust-errno/actions/workflows/main.yml) [![Cargo](https://img.shields.io/crates/v/errno.svg)](https://crates.io/crates/errno) Cross-platform interface to the [`errno`][errno] variable. Works on Rust 1.56 or newer. Documentation is available at . [errno]: https://en.wikipedia.org/wiki/Errno.h ## Dependency Add to your `Cargo.toml`: ```toml [dependencies] errno = "*" ``` ## Comparison with `std::io::Error` The standard library provides [`Error::last_os_error`][last_os_error] which fetches `errno` in the same way. This crate provides these extra features: - No heap allocations - Optional `#![no_std]` support - A `set_errno` function [last_os_error]: https://doc.rust-lang.org/std/io/struct.Error.html#method.last_os_error ## Examples ```rust extern crate errno; use errno::{Errno, errno, set_errno}; // Get the current value of errno let e = errno(); // Set the current value of errno set_errno(e); // Extract the error code as an i32 let code = e.0; // Display a human-friendly error message println!("Error {}: {}", code, e); ``` ## `#![no_std]` Enable `#![no_std]` support by disabling the default `std` feature: ```toml [dependencies] errno = { version = "*", default-features = false } ``` The `Error` impl will be unavailable. errno-0.3.8/clippy.toml000064400000000000000000000000161046102023000131530ustar 00000000000000msrv = "1.56" errno-0.3.8/src/hermit.rs000064400000000000000000000017711046102023000134140ustar 00000000000000//! Implementation of `errno` functionality for RustyHermit. //! //! Currently, the error handling in RustyHermit isn't clearly //! defined. At the current stage of RustyHermit, only a placeholder //! is provided to be compatible to the classical errno interface. // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. use crate::Errno; pub fn with_description(_err: Errno, callback: F) -> T where F: FnOnce(Result<&str, Errno>) -> T, { callback(Ok("unknown error")) } pub const STRERROR_NAME: &str = "strerror_r"; pub fn errno() -> Errno { Errno(0) } pub fn set_errno(_: Errno) {} errno-0.3.8/src/lib.rs000064400000000000000000000072401046102023000126670ustar 00000000000000//! Cross-platform interface to the `errno` variable. //! //! # Examples //! ``` //! use errno::{Errno, errno, set_errno}; //! //! // Get the current value of errno //! let e = errno(); //! //! // Set the current value of errno //! set_errno(e); //! //! // Extract the error code as an i32 //! let code = e.0; //! //! // Display a human-friendly error message //! println!("Error {}: {}", code, e); //! ``` #![cfg_attr(not(feature = "std"), no_std)] #[cfg_attr(unix, path = "unix.rs")] #[cfg_attr(windows, path = "windows.rs")] #[cfg_attr(target_os = "wasi", path = "wasi.rs")] #[cfg_attr(target_os = "hermit", path = "hermit.rs")] mod sys; use core::fmt; #[cfg(feature = "std")] use std::error::Error; #[cfg(feature = "std")] use std::io; /// Wraps a platform-specific error code. /// /// The `Display` instance maps the code to a human-readable string. It /// calls [`strerror_r`][1] under POSIX, and [`FormatMessageW`][2] on /// Windows. /// /// [1]: http://pubs.opengroup.org/onlinepubs/009695399/functions/strerror.html /// [2]: https://msdn.microsoft.com/en-us/library/windows/desktop/ms679351%28v=vs.85%29.aspx #[derive(Copy, Clone, Eq, Ord, PartialEq, PartialOrd, Hash)] pub struct Errno(pub i32); impl fmt::Debug for Errno { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { sys::with_description(*self, |desc| { fmt.debug_struct("Errno") .field("code", &self.0) .field("description", &desc.ok()) .finish() }) } } impl fmt::Display for Errno { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { sys::with_description(*self, |desc| match desc { Ok(desc) => fmt.write_str(desc), Err(fm_err) => write!( fmt, "OS error {} ({} returned error {})", self.0, sys::STRERROR_NAME, fm_err.0 ), }) } } impl From for i32 { fn from(e: Errno) -> Self { e.0 } } #[cfg(feature = "std")] impl Error for Errno { // TODO: Remove when MSRV >= 1.27 #[allow(deprecated)] fn description(&self) -> &str { "system error" } } #[cfg(feature = "std")] impl From for io::Error { fn from(errno: Errno) -> Self { io::Error::from_raw_os_error(errno.0) } } /// Returns the platform-specific value of `errno`. pub fn errno() -> Errno { sys::errno() } /// Sets the platform-specific value of `errno`. pub fn set_errno(err: Errno) { sys::set_errno(err) } #[test] fn it_works() { let x = errno(); set_errno(x); } #[cfg(feature = "std")] #[test] fn it_works_with_to_string() { let x = errno(); let _ = x.to_string(); } #[cfg(feature = "std")] #[test] fn check_description() { let expect = if cfg!(windows) { "Incorrect function." } else if cfg!(target_os = "illumos") { "Not owner" } else if cfg!(target_os = "wasi") { "Argument list too long" } else if cfg!(target_os = "haiku") { "Operation not allowed" } else { "Operation not permitted" }; let errno_code = if cfg!(target_os = "haiku") { -2147483633 } else { 1 }; set_errno(Errno(errno_code)); assert_eq!(errno().to_string(), expect); assert_eq!( format!("{:?}", errno()), format!( "Errno {{ code: {}, description: Some({:?}) }}", errno_code, expect ) ); } #[cfg(feature = "std")] #[test] fn check_error_into_errno() { const ERROR_CODE: i32 = 1; let error = io::Error::from_raw_os_error(ERROR_CODE); let new_error: io::Error = Errno(ERROR_CODE).into(); assert_eq!(error.kind(), new_error.kind()); } errno-0.3.8/src/unix.rs000064400000000000000000000055641046102023000131130ustar 00000000000000//! Implementation of `errno` functionality for Unix systems. //! //! Adapted from `src/libstd/sys/unix/os.rs` in the Rust distribution. // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. use core::str; use libc::{self, c_int, size_t, strerror_r, strlen}; use crate::Errno; fn from_utf8_lossy(input: &[u8]) -> &str { match str::from_utf8(input) { Ok(valid) => valid, Err(error) => unsafe { str::from_utf8_unchecked(&input[..error.valid_up_to()]) }, } } pub fn with_description(err: Errno, callback: F) -> T where F: FnOnce(Result<&str, Errno>) -> T, { let mut buf = [0u8; 1024]; let c_str = unsafe { let rc = strerror_r(err.0, buf.as_mut_ptr() as *mut _, buf.len() as size_t); if rc != 0 { // Handle negative return codes for compatibility with glibc < 2.13 let fm_err = match rc < 0 { true => errno(), false => Errno(rc), }; if fm_err != Errno(libc::ERANGE) { return callback(Err(fm_err)); } } let c_str_len = strlen(buf.as_ptr() as *const _); &buf[..c_str_len] }; callback(Ok(from_utf8_lossy(c_str))) } pub const STRERROR_NAME: &str = "strerror_r"; pub fn errno() -> Errno { unsafe { Errno(*errno_location()) } } pub fn set_errno(Errno(errno): Errno) { unsafe { *errno_location() = errno; } } extern "C" { #[cfg_attr( any( target_os = "macos", target_os = "ios", target_os = "tvos", target_os = "watchos", target_os = "freebsd" ), link_name = "__error" )] #[cfg_attr( any( target_os = "openbsd", target_os = "netbsd", target_os = "bitrig", target_os = "android", target_os = "espidf", target_env = "newlib" ), link_name = "__errno" )] #[cfg_attr( any(target_os = "solaris", target_os = "illumos"), link_name = "___errno" )] #[cfg_attr(target_os = "haiku", link_name = "_errnop")] #[cfg_attr( any( target_os = "linux", target_os = "hurd", target_os = "redox", target_os = "dragonfly" ), link_name = "__errno_location" )] #[cfg_attr(target_os = "aix", link_name = "_Errno")] #[cfg_attr(target_os = "nto", link_name = "__get_errno_ptr")] fn errno_location() -> *mut c_int; } errno-0.3.8/src/wasi.rs000064400000000000000000000032261046102023000130640ustar 00000000000000//! Implementation of `errno` functionality for WASI. //! //! Adapted from `unix.rs`. // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. use core::str; use libc::{self, c_int, size_t, strerror_r, strlen}; use crate::Errno; fn from_utf8_lossy(input: &[u8]) -> &str { match str::from_utf8(input) { Ok(valid) => valid, Err(error) => unsafe { str::from_utf8_unchecked(&input[..error.valid_up_to()]) }, } } pub fn with_description(err: Errno, callback: F) -> T where F: FnOnce(Result<&str, Errno>) -> T, { let mut buf = [0u8; 1024]; let c_str = unsafe { let rc = strerror_r(err.0, buf.as_mut_ptr() as *mut _, buf.len() as size_t); if rc != 0 { let fm_err = Errno(rc); if fm_err != Errno(libc::ERANGE) { return callback(Err(fm_err)); } } let c_str_len = strlen(buf.as_ptr() as *const _); &buf[..c_str_len] }; callback(Ok(from_utf8_lossy(c_str))) } pub const STRERROR_NAME: &str = "strerror_r"; pub fn errno() -> Errno { unsafe { Errno(*__errno_location()) } } pub fn set_errno(Errno(new_errno): Errno) { unsafe { *__errno_location() = new_errno; } } extern "C" { fn __errno_location() -> *mut c_int; } errno-0.3.8/src/windows.rs000064400000000000000000000050601046102023000136110ustar 00000000000000//! Implementation of `errno` functionality for Windows. //! //! Adapted from `src/libstd/sys/windows/os.rs` in the Rust distribution. // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. use core::char::{self, REPLACEMENT_CHARACTER}; use core::ptr; use core::str; use windows_sys::Win32::Foundation::{GetLastError, SetLastError, WIN32_ERROR}; use windows_sys::Win32::System::Diagnostics::Debug::{ FormatMessageW, FORMAT_MESSAGE_FROM_SYSTEM, FORMAT_MESSAGE_IGNORE_INSERTS, }; use crate::Errno; fn from_utf16_lossy<'a>(input: &[u16], output: &'a mut [u8]) -> &'a str { let mut output_len = 0; for c in char::decode_utf16(input.iter().copied().take_while(|&x| x != 0)) .map(|x| x.unwrap_or(REPLACEMENT_CHARACTER)) { let c_len = c.len_utf8(); if c_len > output.len() - output_len { break; } c.encode_utf8(&mut output[output_len..]); output_len += c_len; } unsafe { str::from_utf8_unchecked(&output[..output_len]) } } pub fn with_description(err: Errno, callback: F) -> T where F: FnOnce(Result<&str, Errno>) -> T, { // This value is calculated from the macro // MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT) let lang_id = 0x0800_u32; let mut buf = [0u16; 2048]; unsafe { let res = FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, ptr::null_mut(), err.0 as u32, lang_id, buf.as_mut_ptr(), buf.len() as u32, ptr::null_mut(), ); if res == 0 { // Sometimes FormatMessageW can fail e.g. system doesn't like lang_id let fm_err = errno(); return callback(Err(fm_err)); } let mut msg = [0u8; 2048]; let msg = from_utf16_lossy(&buf[..res as usize], &mut msg[..]); // Trim trailing CRLF inserted by FormatMessageW callback(Ok(msg.trim_end())) } } pub const STRERROR_NAME: &str = "FormatMessageW"; pub fn errno() -> Errno { unsafe { Errno(GetLastError() as i32) } } pub fn set_errno(Errno(errno): Errno) { unsafe { SetLastError(errno as WIN32_ERROR) } }