Skip to content

Commit feda5d8

Browse files
committed
refactor: Move functions to handle C types to c submodule
1 parent 26cac75 commit feda5d8

File tree

3 files changed

+31
-23
lines changed

3 files changed

+31
-23
lines changed

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,4 @@ repository = "https://github.com/jhg/opaque-pointer-rs/"
1313
[features]
1414
default = ["std"]
1515
std = []
16+
c-types = []

src/c.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
//! # C types FFI opaque pointers.
2+
//!
3+
//! Specific C types like C-like string pointers.
4+
5+
#![cfg(all(feature = "std", feature = "c-types"))]
6+
7+
use std::os::raw::c_char;
8+
use std::ffi::CStr;
9+
10+
use super::panic_if_null;
11+
12+
/// Reference to a C string.
13+
///
14+
/// # Safety
15+
///
16+
/// The pointer must be a valid reference to that value with that type.
17+
///
18+
/// # Panics
19+
///
20+
/// This could panic if the C string is not a valid UTF-8 string.
21+
#[must_use]
22+
#[inline]
23+
pub unsafe fn ref_str<'a>(string: *const c_char) -> &'a str {
24+
panic_if_null(string);
25+
// CAUTION: this is unsafe
26+
let string = CStr::from_ptr(string);
27+
return string.to_str().expect("Invalid UTF-8 string from C or C++ code");
28+
}

src/lib.rs

Lines changed: 2 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,8 @@ extern crate std;
2020
#[cfg(feature = "std")]
2121
use std::boxed::Box;
2222

23-
#[cfg(feature = "std")]
24-
use std::os::raw::c_char;
25-
#[cfg(feature = "std")]
26-
use std::ffi::CStr;
23+
#[cfg(all(feature = "std", feature = "c-types"))]
24+
pub mod c;
2725

2826
/// Panic if a pointer is null.
2927
#[inline]
@@ -93,22 +91,3 @@ pub unsafe fn mut_object<'a, T>(pointer: *mut T) -> &'a mut T {
9391
// CAUTION: this is unsafe
9492
&mut *pointer
9593
}
96-
97-
/// Reference to a C string.
98-
///
99-
/// # Safety
100-
///
101-
/// The pointer must be a valid reference to that value with that type.
102-
///
103-
/// # Panics
104-
///
105-
/// This could panic if the C string is not a valid UTF-8 string.
106-
#[cfg(feature = "std")]
107-
#[must_use]
108-
#[inline]
109-
pub unsafe fn ref_str<'a>(string: *const c_char) -> &'a str {
110-
panic_if_null(string);
111-
// CAUTION: this is unsafe
112-
let string = CStr::from_ptr(string);
113-
string.to_str().expect("Invalid UTF-8 string from C or C++ code")
114-
}

0 commit comments

Comments
 (0)