Skip to content

Commit

Permalink
Merge pull request #37 from jewlexx/no_std
Browse files Browse the repository at this point in the history
Add no_std support
  • Loading branch information
jewlexx authored May 3, 2024
2 parents 8adfc39 + fc1b0cc commit cbf50af
Show file tree
Hide file tree
Showing 8 changed files with 308 additions and 264 deletions.
10 changes: 6 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ authors = ["Juliette Cordor"]
categories = ["development-tools", "os", "os::unix-apis", "os::windows-apis"]
description = "A collection of small things that don't deserve their own crate"
documentation = "https://docs.rs/quork"
edition = "2018"
edition = "2021"
homepage = "https://github.com/jewlexx/quork.git"
keywords = ["admin", "linux", "network", "sys", "windows"]
license = "MIT OR Apache-2.0"
Expand All @@ -25,10 +25,11 @@ spin = { version = "0.9", optional = true }
thiserror = { version = "1.0" }

[target.'cfg(windows)'.dependencies]
windows = { version = "0.56.0", features = [
windows = { version = "0.56", features = [
"Win32_Foundation",
"Win32_Networking_NetworkListManager",
"Win32_Security",
"Win32_Security",
"Win32_System_Com",
"Win32_System_Threading",
] }
Expand All @@ -37,11 +38,12 @@ windows = { version = "0.56.0", features = [
nix = { version = "0.28", features = ["user"] }

[features]
all = ["macros", "network", "root", "traits"]
all = ["macros", "network", "root", "std", "traits"]
default = ["all"]
macros = ["quork-proc"]
network = []
root = []
root = ["std"]
std = []
traits = []

[build-dependencies]
Expand Down
9 changes: 7 additions & 2 deletions examples/printroot.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
use quork::prelude::is_root;

#[cfg(feature = "std")]
fn main() {
use quork::prelude::is_root;
let root = is_root().unwrap();

println!("Is the the process running as admin? {}", root);
}

#[cfg(not(feature = "std"))]
fn main() {
panic!("This example requires the standard crate")
}
162 changes: 14 additions & 148 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,24 @@
#![warn(clippy::pedantic)]
#![warn(missing_docs)]
#![doc = include_str!("../README.md")]
#![cfg_attr(not(feature = "std"), no_std)]

extern crate alloc;

cfg_if::cfg_if! {
if #[cfg(feature = "std")] {
use std as std;
} else {
use core as std;
}
}

pub mod prelude {
//! `use quork::prelude::*` To include common helpful items

cfg_if::cfg_if! {
if #[cfg(feature = "traits")] {
pub use crate::traits::flip::*;
pub use crate::traits::lock::*;
pub use crate::traits::truthy::*;
pub use crate::traits::list::*;
pub use crate::traits::prelude::*;
}
}

Expand All @@ -37,152 +45,10 @@ pub mod traits;
pub mod network;

cfg_if::cfg_if! {
if #[cfg(feature = "root")] {
if #[cfg(all(feature = "root", feature = "std"))] {
pub mod root;
}
}

/// Truncation helpers for truncating strings when formatting
pub mod truncate {
use std::fmt;

pub use crate::traits::truncate::Truncation;

#[derive(Debug)]
#[must_use]
/// A wrapper that truncates its contents when used.
///
/// This should be used through the [`fmt::Display`] trait,
/// in [`println!`] and other formatting circumstances
///
/// # Examples
///
/// ```rust
/// # use quork::truncate::Truncate;
/// let name = Truncate::new("Juliette Cordor", 8);
///
/// assert_eq!(name.to_string(), "Juliette")
/// ```
pub struct Truncate<T> {
length: usize,
data: T,
suffix: Option<String>,
}

impl<T> Truncate<T> {
/// Construct a new [`Truncate`] from the provided data and length
pub fn new(data: T, length: usize) -> Self {
Self {
length,
data,
suffix: None,
}
}

/// Add a suffix to the provided [`Truncate`], to print after the truncation
///
/// # Examples
///
/// ```rust
/// # use quork::truncate::Truncate;
/// let mut name = Truncate::new("Juliette Cordor", 8).with_suffix("...");
///
/// assert_eq!(name.to_string(), "Julie...")
/// ```
pub fn with_suffix(self, suffix: impl fmt::Display) -> Self {
Self {
suffix: Some(suffix.to_string()),
..self
}
}
}

impl<T: fmt::Display> fmt::Display for Truncate<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// TODO: Remove string allocation here?
let truncated = &self
.data
.to_string()
.chars()
.take(if let Some(ref suffix) = self.suffix {
// Account for length of suffix
self.length - suffix.len()
} else {
self.length
})
.collect::<String>();

truncated.fmt(f)?;

if let Some(ref suffix) = self.suffix {
suffix.fmt(f)?;
}

Ok(())
}
}

#[must_use]
#[deprecated = "This is no longer used internally, and was never intended to be used externally"]
/// A wrapper over a writer that truncates the output to a certain length
///
/// Primarily intended to be used through the [`Truncate`] struct
pub struct TruncatedFormatter<'a> {
remaining: usize,
writer: &'a mut fmt::Formatter<'a>,
}

#[allow(deprecated)]
impl<'a> TruncatedFormatter<'a> {
/// Construct a new [`TruncatedFormatter`] from the provided writer and length
pub fn new(writer: &'a mut fmt::Formatter<'a>, length: usize) -> Self {
Self {
remaining: length,
writer,
}
}
}

#[allow(deprecated)]
impl<'a> fmt::Write for TruncatedFormatter<'a> {
fn write_str(&mut self, s: &str) -> fmt::Result {
if self.remaining < s.len() {
self.writer.write_str(&s[0..self.remaining])?;
self.remaining = 0;
Ok(())
} else {
self.remaining -= s.len();
self.writer.write_str(s)
}
}
}

#[cfg(test)]
mod tests {
use super::Truncate;

#[test]
fn test_with_suffix() {
let suffixed = Truncate::new("Hello, World!", 8).with_suffix("...");

assert_eq!("Hello...", suffixed.to_string());
}

#[test]
fn test_with_padding() {
let truncated = Truncate::new("Hello, World!", 5);

let padded = format!("{truncated:<10}");

assert_eq!("Hello ", padded);
}

// This used to crash, this test exists to ensure that doesn't happen again
#[test]
fn test_longer_length_than_string() {
let truncated = Truncate::new("Hey", 15);

assert_eq!("Hey", truncated.to_string());
}
}
}
pub mod truncate;
2 changes: 1 addition & 1 deletion src/root.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
/// Errors when checking if process is root
pub enum Error {
#[cfg(windows)]
/// The Windows Process elevation cannot be checked
#[error("Windows related error: {0}")]
/// The Windows Process elevation cannot be checked
WindowsError(#[from] windows::core::Error),
}

Expand Down
Loading

0 comments on commit cbf50af

Please sign in to comment.