Skip to content

Commit 83eafc5

Browse files
committed
feat(stack-cstr): add thiserror dependency for error handling, replacing &'static str
1 parent 754f60a commit 83eafc5

File tree

5 files changed

+74
-9
lines changed

5 files changed

+74
-9
lines changed

Cargo.lock

Lines changed: 57 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "stack-cstr"
3-
version = "0.1.2"
3+
version = "0.1.3"
44
edition = "2024"
55
authors = ["Junkang Yuan <[email protected]>"]
66
description = "High-performance stack-to-heap C string creation for Rust with FFI support"
@@ -12,3 +12,4 @@ categories = ["development-tools::ffi", "memory-management"]
1212

1313
[dependencies]
1414
arrayvec = "0.7.6"
15+
thiserror = "2.0.16"

src/cstr_stack.rs

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use std::ffi::{CStr, c_char};
22

33
use arrayvec::ArrayString;
44

5-
use crate::CStrLike;
5+
use crate::{CStrError, CStrLike};
66

77
/// A stack-allocated, null-terminated C string with fixed capacity.
88
///
@@ -41,14 +41,11 @@ impl<const N: usize> CStrStack<N> {
4141
///
4242
/// The string is written into an internal buffer of size `N`.
4343
/// If the string does not fit, returns an error.
44-
pub fn new(fmt: std::fmt::Arguments) -> Result<CStrStack<N>, &'static str> {
44+
pub fn new(fmt: std::fmt::Arguments) -> Result<CStrStack<N>, CStrError> {
4545
let mut buf: ArrayString<N> = ArrayString::new();
46-
std::fmt::write(&mut buf, fmt).map_err(|_| "format failed")?;
46+
std::fmt::write(&mut buf, fmt)?;
4747

48-
if buf.len() + 1 > N {
49-
return Err("buffer overflow");
50-
}
51-
buf.push('\0');
48+
buf.try_push('\0')?;
5249

5350
Ok(Self { buf })
5451
}

src/error.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
use thiserror::Error;
2+
3+
#[derive(Error, Debug)]
4+
pub enum CStrError {
5+
#[error("format failed")]
6+
FormatError(#[from] core::fmt::Error),
7+
#[error("buffer overflow")]
8+
OverflowError(#[from] arrayvec::CapacityError<char>),
9+
}

src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,8 +102,10 @@
102102
pub mod cstr_heap;
103103
pub mod cstr_like;
104104
pub mod cstr_stack;
105+
pub mod error;
105106
pub mod macros;
106107

107108
pub use cstr_heap::CStrHeap;
108109
pub use cstr_like::CStrLike;
109110
pub use cstr_stack::CStrStack;
111+
pub use error::CStrError;

0 commit comments

Comments
 (0)