Skip to content

add std,alloc feature flag to support no_std build #111

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jan 3, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,16 @@ repository.workspace = true
rust-version.workspace = true

[dependencies]
nginx-sys = { path = "nginx-sys", version = "0.5.0"}
nginx-sys = { path = "nginx-sys", default-features=false, version = "0.5.0"}

[features]
default = ["vendored"]
default = ["vendored","std"]
# Enables the components using memory allocation.
# If no `std` flag, `alloc` crate is internally used instead. This flag is mainly for `no_std` build.
alloc = []
# Enables the components using `std` crate.
# Currently the only difference to `alloc` flag is `std::error::Error` implementation.
std = ["alloc"]
# Build our own copy of the NGINX by default.
# This could be disabled with `--no-default-features` to minimize the dependency tree
# when building against an existing copy of the NGINX with the NGX_OBJS variable.
Expand Down
2 changes: 1 addition & 1 deletion examples/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ build = "../build.rs"

[dependencies]
nginx-sys = { path = "../nginx-sys/", default-features = false }
ngx = { path = "../", default-features = false }
ngx = { path = "../", default-features = false, features = ["std"] }

[dev-dependencies]
aws-sign-v4 = "0.3.0"
Expand Down
1 change: 1 addition & 0 deletions nginx-sys/build/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ fn generate_binding(nginx_build_dir: PathBuf) {
.header("build/wrapper.h")
.clang_args(clang_args)
.layout_tests(false)
.use_core()
.generate()
.expect("Unable to generate bindings");

Expand Down
110 changes: 61 additions & 49 deletions nginx-sys/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
#![doc = include_str!("../README.md")]
#![warn(missing_docs)]
#![no_std]

use std::fmt;
use std::ptr::copy_nonoverlapping;
use std::slice;
use core::fmt;
use core::ptr::copy_nonoverlapping;
use core::slice;

#[doc(hidden)]
mod bindings {
Expand Down Expand Up @@ -104,7 +105,7 @@ impl ngx_str_t {
/// # Returns
/// A string slice (`&str`) representing the nginx string.
pub fn to_str(&self) -> &str {
std::str::from_utf8(self.as_bytes()).unwrap()
core::str::from_utf8(self.as_bytes()).unwrap()
}

/// Create an `ngx_str_t` instance from a byte slice.
Expand All @@ -116,27 +117,6 @@ impl ngx_str_t {
bytes_to_uchar(pool, src).map(|data| Self { data, len: src.len() })
}

/// Create an `ngx_str_t` instance from a `String`.
///
/// # Arguments
///
/// * `pool` - A pointer to the nginx memory pool (`ngx_pool_t`).
/// * `data` - The `String` from which to create the nginx string.
///
/// # Safety
/// This function is marked as unsafe because it accepts a raw pointer argument. There is no
/// way to know if `pool` is pointing to valid memory. The caller must provide a valid pool to
/// avoid indeterminate behavior.
///
/// # Returns
/// An `ngx_str_t` instance representing the given `String`.
pub unsafe fn from_string(pool: *mut ngx_pool_t, data: String) -> Self {
ngx_str_t {
data: str_to_uchar(pool, data.as_str()),
len: data.len(),
}
}

/// Create an `ngx_str_t` instance from a string slice (`&str`).
///
/// # Arguments
Expand Down Expand Up @@ -168,26 +148,29 @@ impl From<ngx_str_t> for &[u8] {
}
}

impl TryFrom<ngx_str_t> for String {
type Error = std::string::FromUtf8Error;

fn try_from(s: ngx_str_t) -> Result<Self, Self::Error> {
let bytes: &[u8] = s.into();
String::from_utf8(bytes.into())
}
}

impl fmt::Display for ngx_str_t {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", String::from_utf8_lossy((*self).into()))
// The implementation is similar to an inlined `String::from_utf8_lossy`, with two
// important differences:
//
// - it writes directly to the Formatter instead of allocating a temporary String
// - invalid sequences are represented as escaped individual bytes
for chunk in self.as_bytes().utf8_chunks() {
f.write_str(chunk.valid())?;
for byte in chunk.invalid() {
f.write_str("\\x")?;
fmt::LowerHex::fmt(byte, f)?;
}
}
Ok(())
}
}

impl TryFrom<ngx_str_t> for &str {
type Error = std::str::Utf8Error;
type Error = core::str::Utf8Error;

fn try_from(s: ngx_str_t) -> Result<Self, Self::Error> {
std::str::from_utf8(s.into())
core::str::from_utf8(s.into())
}
}

Expand Down Expand Up @@ -221,18 +204,47 @@ impl TryFrom<ngx_str_t> for &str {
pub unsafe fn add_to_ngx_table(
table: *mut ngx_table_elt_t,
pool: *mut ngx_pool_t,
key: &str,
value: &str,
key: impl AsRef<[u8]>,
value: impl AsRef<[u8]>,
) -> Option<()> {
if table.is_null() {
return None;
if let Some(table) = table.as_mut() {
let key = key.as_ref();
table.key = ngx_str_t::from_bytes(pool, key)?;
table.value = ngx_str_t::from_bytes(pool, value.as_ref())?;
table.lowcase_key = ngx_pnalloc(pool, table.key.len).cast();
if table.lowcase_key.is_null() {
return None;
}
table.hash = ngx_hash_strlow(table.lowcase_key, table.key.data, table.key.len);
return Some(());
}
None
}

#[cfg(test)]
mod tests {
extern crate alloc;
use alloc::string::ToString;

use super::*;

#[test]
fn ngx_str_display() {
let pairs: &[(&[u8], &str)] = &[
(b"", ""),
(b"Ferris the \xf0\x9f\xa6\x80", "Ferris the 🦀"),
(b"\xF0\x90\x80", "\\xf0\\x90\\x80"),
(b"\xF0\x90\x80Hello World", "\\xf0\\x90\\x80Hello World"),
(b"Hello \xF0\x90\x80World", "Hello \\xf0\\x90\\x80World"),
(b"Hello World\xF0\x90\x80", "Hello World\\xf0\\x90\\x80"),
];

for (bytes, expected) in pairs {
let str = ngx_str_t {
data: bytes.as_ptr().cast_mut(),
len: bytes.len(),
};
assert_eq!(str.to_string(), *expected);
}
}
table.as_mut().map(|table| {
table.hash = 1;
table.key.len = key.len();
table.key.data = str_to_uchar(pool, key);
table.value.len = value.len();
table.value.data = str_to_uchar(pool, value);
table.lowcase_key = str_to_uchar(pool, String::from(key).to_ascii_lowercase().as_str());
})
}
2 changes: 1 addition & 1 deletion src/core/buffer.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::slice;
use core::slice;

use crate::ffi::*;

Expand Down
2 changes: 1 addition & 1 deletion src/core/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ macro_rules! ngx_null_command {
set: None,
conf: 0,
offset: 0,
post: ::std::ptr::null_mut(),
post: ::core::ptr::null_mut(),
}
};
}
Expand Down
4 changes: 2 additions & 2 deletions src/core/pool.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::ffi::c_void;
use std::{mem, ptr};
use core::ffi::c_void;
use core::{mem, ptr};

use crate::core::buffer::{Buffer, MemoryBuffer, TemporaryBuffer};
use crate::ffi::*;
Expand Down
2 changes: 1 addition & 1 deletion src/core/status.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::fmt;
use core::fmt;

use crate::ffi::*;

Expand Down
13 changes: 9 additions & 4 deletions src/core/string.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
use std::borrow::Cow;
use std::slice;
use std::str::{self, Utf8Error};
use core::slice;
use core::str::{self, Utf8Error};

#[cfg(all(not(feature = "std"), feature = "alloc"))]
use alloc::{borrow::Cow, string::String};
#[cfg(feature = "std")]
use std::{borrow::Cow, string::String};

use crate::ffi::*;

Expand All @@ -27,7 +31,7 @@ macro_rules! ngx_null_string {
() => {
$crate::ffi::ngx_str_t {
len: 0,
data: ::std::ptr::null_mut(),
data: ::core::ptr::null_mut(),
}
};
}
Expand Down Expand Up @@ -64,6 +68,7 @@ impl NgxStr {
/// Converts an [`NgxStr`] into a [`Cow<str>`], replacing invalid UTF-8 sequences.
///
/// See [`String::from_utf8_lossy`].
#[cfg(feature = "alloc")]
pub fn to_string_lossy(&self) -> Cow<str> {
String::from_utf8_lossy(self.as_bytes())
}
Expand Down
2 changes: 1 addition & 1 deletion src/http/conf.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::ffi::c_void;
use core::ffi::c_void;

use crate::ffi::*;

Expand Down
10 changes: 6 additions & 4 deletions src/http/module.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::ffi::{c_char, c_void};
use std::ptr;
use core::ffi::{c_char, c_void};
use core::fmt;
use core::ptr;

use crate::core::NGX_CONF_ERROR;
use crate::core::*;
Expand All @@ -12,10 +13,11 @@ pub enum MergeConfigError {
NoValue,
}

#[cfg(feature = "std")]
impl std::error::Error for MergeConfigError {}

impl std::fmt::Display for MergeConfigError {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
impl fmt::Display for MergeConfigError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self {
MergeConfigError::NoValue => "no value".fmt(fmt),
}
Expand Down
Loading
Loading