rtoolbox-0.0.1/.cargo_vcs_info.json0000644000000001570000000000100127050ustar { "git": { "sha1": "f2f8ef20df2c65d0129e37ec8abe7f266b9def40" }, "path_in_vcs": "projects/rtoolbox" }rtoolbox-0.0.1/.github/FUNDING.yml000064400000000000000000000000341046102023000146440ustar 00000000000000liberapay: conradkleinespel rtoolbox-0.0.1/.github/workflows/rutil-rust-tests.yml000064400000000000000000000015271046102023000211110ustar 00000000000000name: rtoolbox rust tests on: pull_request jobs: rust-linux-tests: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 name: Install rust with: toolchain: stable - uses: actions-rs/cargo@v1 name: Run cargo test with: command: test args: --all-targets --all-features --manifest-path Cargo.toml rust-windows-tests: runs-on: windows-latest steps: - name: Checkout code uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 name: Install rust with: toolchain: stable - uses: actions-rs/cargo@v1 name: Run cargo test with: command: test args: --all-targets --all-features --manifest-path Cargo.toml rtoolbox-0.0.1/.gitignore000064400000000000000000000000251046102023000134570ustar 00000000000000/target/ /Cargo.lock rtoolbox-0.0.1/CONTRIBUTING.md000064400000000000000000000023041046102023000137220ustar 00000000000000# Contributing Development for this project takes place in the [conradkleinespel/duck](https://github.com/conradkleinespel/duck) repository, a mono-repo that makes code reuse easier. You are welcome to contribute to this project, following a couple of guidelines. The main principle is that we want to respect each other's time. ## Bug reports Bug reports should include instructions for how to reproduce step-by-step, include useful information such as operating system, version of Rust and Cargo used to compile, screenshots, log output, etc. Bug reports that do not give sufficient information to understand and reproduce the bug will be closed. If you have the necessary skills, you should always attempt to fix the bug yourself. Whenever possible, you should add a unit or integration test so that we don't accidentally reintroduce the bug later. ## New features R Before working on a new feature, open an issue to discuss your plans. We'll tell you if we think it falls into the scope of this project, so you only spend time implementing changes we're willing to review and merge. New features should include unit tests and integration tests if applicable, so that future development don't break your code. rtoolbox-0.0.1/Cargo.toml0000644000000022430000000000100107010ustar # 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" name = "rtoolbox" version = "0.0.1" authors = ["Conrad Kleinespel "] description = "Utility functions for other crates, no backwards compatibility guarantees." readme = "README.md" license = "Apache-2.0" [dependencies.serde] version = "1.0" features = ["derive"] optional = true [dependencies.serde_json] version = "1.0" optional = true [features] serde = [ "dep:serde", "dep:serde_json", ] [target."cfg(unix)".dependencies.libc] version = "0.2" [target."cfg(windows)".dependencies.winapi] version = "0.3" features = [ "std", "winnt", "fileapi", "processenv", "winbase", "handleapi", "consoleapi", "minwindef", "wincon", ] rtoolbox-0.0.1/Cargo.toml.orig000064400000000000000000000012101046102023000143530ustar 00000000000000[package] name = "rtoolbox" version = "0.0.1" description = "Utility functions for other crates, no backwards compatibility guarantees." authors = ["Conrad Kleinespel "] license = "Apache-2.0" edition = "2018" [features] serde = ["dep:serde", "dep:serde_json"] [dependencies] serde = { version = "1.0", features = ["derive"], optional = true } serde_json = { version = "1.0", optional = true } [target.'cfg(unix)'.dependencies.libc] version = "0.2" [target.'cfg(windows)'.dependencies.winapi] version = "0.3" features = ["std", "winnt", "fileapi", "processenv", "winbase", "handleapi", "consoleapi", "minwindef", "wincon"] rtoolbox-0.0.1/LICENSE-APACHE000064400000000000000000000236751046102023000134330ustar 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 rtoolbox-0.0.1/README.md000064400000000000000000000003231046102023000127470ustar 00000000000000# Rustastic Toolbox `rtoolbox` contains utility functions I use in other projects. There are no backwards compatibility guarantees at all. ## License The source code is released under the Apache 2.0 license. rtoolbox-0.0.1/src/atty.rs000064400000000000000000000112301046102023000136050ustar 00000000000000// Copyright (c) 2015-2019 Doug Tangren // // 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. #[cfg(windows)] use winapi::shared::minwindef::DWORD; #[cfg(windows)] use winapi::shared::ntdef::WCHAR; /// possible stream sources #[derive(Clone, Copy, Debug)] pub enum Stream { Stdout, Stderr, Stdin, } /// returns true if this is a tty #[cfg(target_family = "unix")] pub fn is(stream: Stream) -> bool { let fd = match stream { Stream::Stdout => libc::STDOUT_FILENO, Stream::Stderr => libc::STDERR_FILENO, Stream::Stdin => libc::STDIN_FILENO, }; unsafe { libc::isatty(fd) != 0 } } /// returns true if this is a tty #[cfg(target_os = "hermit")] pub fn is(stream: Stream) -> bool { let fd = match stream { Stream::Stdout => hermit_abi::STDOUT_FILENO, Stream::Stderr => hermit_abi::STDERR_FILENO, Stream::Stdin => hermit_abi::STDIN_FILENO, }; hermit_abi::isatty(fd) } /// returns true if this is a tty #[cfg(windows)] pub fn is(stream: Stream) -> bool { use winapi::um::winbase::{ STD_ERROR_HANDLE as STD_ERROR, STD_INPUT_HANDLE as STD_INPUT, STD_OUTPUT_HANDLE as STD_OUTPUT, }; let (fd, others) = match stream { Stream::Stdin => (STD_INPUT, [STD_ERROR, STD_OUTPUT]), Stream::Stderr => (STD_ERROR, [STD_INPUT, STD_OUTPUT]), Stream::Stdout => (STD_OUTPUT, [STD_INPUT, STD_ERROR]), }; if unsafe { console_on_any(&[fd]) } { // False positives aren't possible. If we got a console then // we definitely have a tty on stdin. return true; } // At this point, we *could* have a false negative. We can determine that // this is true negative if we can detect the presence of a console on // any of the other streams. If another stream has a console, then we know // we're in a Windows console and can therefore trust the negative. if unsafe { console_on_any(&others) } { return false; } // Otherwise, we fall back to a very strange msys hack to see if we can // sneakily detect the presence of a tty. unsafe { msys_tty_on(fd) } } /// returns true if this is _not_ a tty pub fn isnt(stream: Stream) -> bool { !is(stream) } /// Returns true if any of the given fds are on a console. #[cfg(windows)] unsafe fn console_on_any(fds: &[DWORD]) -> bool { use winapi::um::{consoleapi::GetConsoleMode, processenv::GetStdHandle}; for &fd in fds { let mut out = 0; let handle = GetStdHandle(fd); if GetConsoleMode(handle, &mut out) != 0 { return true; } } false } /// Returns true if there is an MSYS tty on the given handle. #[cfg(windows)] unsafe fn msys_tty_on(fd: DWORD) -> bool { use std::{mem, slice}; use winapi::{ ctypes::c_void, shared::minwindef::MAX_PATH, um::{ fileapi::FILE_NAME_INFO, minwinbase::FileNameInfo, processenv::GetStdHandle, winbase::GetFileInformationByHandleEx, }, }; let size = mem::size_of::(); let mut name_info_bytes = vec![0u8; size + MAX_PATH * mem::size_of::()]; let res = GetFileInformationByHandleEx( GetStdHandle(fd), FileNameInfo, &mut *name_info_bytes as *mut _ as *mut c_void, name_info_bytes.len() as u32, ); if res == 0 { return false; } let name_info: &FILE_NAME_INFO = &*(name_info_bytes.as_ptr() as *const FILE_NAME_INFO); let s = slice::from_raw_parts( name_info.FileName.as_ptr(), name_info.FileNameLength as usize / 2, ); let name = String::from_utf16_lossy(s); // This checks whether 'pty' exists in the file name, which indicates that // a pseudo-terminal is attached. To mitigate against false positives // (e.g., an actual file name that contains 'pty'), we also require that // either the strings 'msys-' or 'cygwin-' are in the file name as well.) let is_msys = name.contains("msys-") || name.contains("cygwin-"); let is_pty = name.contains("-pty"); is_msys && is_pty } /// returns true if this is a tty #[cfg(target_family = "wasm")] pub fn is(_stream: Stream) -> bool { false } rtoolbox-0.0.1/src/fix_line_issues.rs000064400000000000000000000013421046102023000160170ustar 00000000000000/// Normalizes the return of `read_line()` in the context of a CLI application pub fn fix_line_issues(mut line: String) -> std::io::Result { if !line.ends_with('\n') { return Err(std::io::Error::new( std::io::ErrorKind::UnexpectedEof, "unexpected end of file", )); } // Remove the \n from the line. line.pop(); // Remove the \r from the line if present if line.ends_with('\r') { line.pop(); } // Ctrl-U should remove the line in terminals if line.contains('') { line = match line.rfind('') { Some(last_ctrl_u_index) => line[last_ctrl_u_index + 1..].to_string(), None => line, }; } Ok(line) } rtoolbox-0.0.1/src/lib.rs000064400000000000000000000002261046102023000133750ustar 00000000000000pub mod atty; pub mod fix_line_issues; pub mod print_tty; pub mod safe_string; #[cfg(feature = "serde")] pub mod safe_string_serde; pub mod safe_vec; rtoolbox-0.0.1/src/print_tty.rs000064400000000000000000000043161046102023000146670ustar 00000000000000#[cfg(target_family = "wasm")] mod wasm { use std::io::Write; /// Displays a message on the STDOUT pub fn print_tty(prompt: impl ToString) -> std::io::Result<()> { let mut stdout = std::io::stdout(); write!(stdout, "{}", prompt.to_string().as_str())?; stdout.flush()?; Ok(()) } } #[cfg(target_family = "unix")] mod unix { use std::io::Write; /// Displays a message on the TTY pub fn print_tty(prompt: impl ToString) -> std::io::Result<()> { let mut stream = std::fs::OpenOptions::new().write(true).open("/dev/tty")?; stream .write_all(prompt.to_string().as_str().as_bytes()) .and_then(|_| stream.flush()) } } #[cfg(target_family = "windows")] mod windows { use std::io::Write; use std::os::windows::io::FromRawHandle; use winapi::um::fileapi::{CreateFileA, OPEN_EXISTING}; use winapi::um::handleapi::INVALID_HANDLE_VALUE; use winapi::um::winnt::{FILE_SHARE_READ, FILE_SHARE_WRITE, GENERIC_READ, GENERIC_WRITE}; /// Displays a message on the TTY pub fn print_tty(prompt: impl ToString) -> std::io::Result<()> { let handle = unsafe { CreateFileA( b"CONOUT$\x00".as_ptr() as *const i8, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, std::ptr::null_mut(), OPEN_EXISTING, 0, std::ptr::null_mut(), ) }; if handle == INVALID_HANDLE_VALUE { return Err(std::io::Error::last_os_error()); } let mut stream = unsafe { std::fs::File::from_raw_handle(handle) }; stream .write_all(prompt.to_string().as_str().as_bytes()) .and_then(|_| stream.flush()) } } /// Prints a message to a writer pub fn print_writer(stream: &mut impl Write, prompt: impl ToString) -> std::io::Result<()> { stream .write_all(prompt.to_string().as_str().as_bytes()) .and_then(|_| stream.flush()) } use std::io::Write; #[cfg(target_family = "unix")] pub use unix::print_tty; #[cfg(target_family = "wasm")] pub use wasm::print_tty; #[cfg(target_family = "windows")] pub use windows::print_tty; rtoolbox-0.0.1/src/safe_string.rs000064400000000000000000000024651046102023000151420ustar 00000000000000use std::convert::Into; use std::ops::{Deref, DerefMut, Drop}; use std::{ptr, sync::atomic}; /// String that is zeroed when dropped #[derive(Clone, Debug, PartialEq, Eq)] pub struct SafeString { inner: String, } impl SafeString { pub fn new() -> SafeString { SafeString { inner: String::new(), } } pub fn from_string(inner: String) -> SafeString { SafeString { inner } } pub fn into_inner(mut self) -> String { std::mem::replace(&mut self.inner, String::new()) } } impl Drop for SafeString { fn drop(&mut self) { let default = u8::default(); for c in unsafe { self.inner.as_bytes_mut() } { unsafe { ptr::write_volatile(c, default) }; } atomic::fence(atomic::Ordering::SeqCst); atomic::compiler_fence(atomic::Ordering::SeqCst); } } impl Deref for SafeString { type Target = String; fn deref(&self) -> &String { &self.inner } } impl DerefMut for SafeString { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.inner } } impl Into for String { fn into(self) -> SafeString { SafeString::from_string(self) } } impl<'a> Into for &'a str { fn into(self) -> SafeString { self.to_string().into() } } rtoolbox-0.0.1/src/safe_string_serde.rs000064400000000000000000000052121046102023000163150ustar 00000000000000use super::safe_string::SafeString; use serde::de::{Deserialize, Deserializer, Visitor}; use serde::ser::{Serialize, Serializer}; use std::fmt; use std::ops::Deref; struct StringVisitor; impl<'de> Visitor<'de> for StringVisitor { fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a string") } fn visit_str(self, v: &str) -> Result { Ok(String::from(v)) } type Value = String; } impl Serialize for SafeString { fn serialize(&self, serializer: S) -> Result where S: Serializer, { serializer.serialize_str(self.deref()) } } impl<'de> Deserialize<'de> for SafeString { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { deserializer .deserialize_string(StringVisitor) .map(|parsed_value| SafeString::from_string(parsed_value)) } } mod test { use super::SafeString; use serde::{Deserialize, Serialize}; #[test] fn safe_string_serialization() { let s = SafeString::from_string(String::from("blabla")); match serde_json::to_string(&s) { Ok(json) => assert_eq!("\"blabla\"", json), Err(_) => panic!("Serialization failed, somehow"), } } #[derive(Serialize, Deserialize, Debug, Eq, PartialEq)] pub struct TestStruct { password: SafeString, } #[test] fn safe_string_within_struct_serialization() { let ts = TestStruct { password: SafeString::from_string(String::from("blabla")), }; match serde_json::to_string(&ts) { Ok(json) => assert_eq!("{\"password\":\"blabla\"}", json), Err(_) => panic!("Serialization failed, somehow"), } } #[test] fn safe_string_deserialization() { let s = "\"blabla\""; let res: Result = serde_json::from_str(s); match res { Ok(ss) => assert_eq!(ss, SafeString::from_string(String::from("blabla"))), Err(_) => panic!("Deserialization failed"), } } #[test] fn safe_string_within_struct_deserialization() { let json = "{\"password\":\"blabla\"}"; let res: Result = serde_json::from_str(json); match res { Ok(ts) => assert_eq!( ts, TestStruct { password: SafeString::from_string(String::from("blabla")) } ), Err(_) => panic!("Deserialization failed"), } } } rtoolbox-0.0.1/src/safe_vec.rs000064400000000000000000000016571046102023000144130ustar 00000000000000use std::ops::Deref; use std::ops::DerefMut; use std::ops::Drop; use std::{ptr, sync::atomic}; /// Vec that is zeroed when dropped #[derive(Clone, Debug, PartialEq, Eq)] pub struct SafeVec { pub inner: Vec, } impl SafeVec { pub fn new(inner: Vec) -> SafeVec { SafeVec { inner: inner } } pub fn inner_mut(&mut self) -> &mut Vec { &mut self.inner } } impl Drop for SafeVec { fn drop(&mut self) { let default = u8::default(); for c in self.inner.as_mut_slice() { unsafe { ptr::write_volatile(c, default) }; } atomic::fence(atomic::Ordering::SeqCst); atomic::compiler_fence(atomic::Ordering::SeqCst); } } impl Deref for SafeVec { type Target = [u8]; fn deref(&self) -> &[u8] { self.inner.deref() } } impl DerefMut for SafeVec { fn deref_mut(&mut self) -> &mut [u8] { self.inner.deref_mut() } }