Skip to content
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
18 changes: 3 additions & 15 deletions examples/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,23 +1,11 @@
[workspace]
resolver = "3"
members = [
"sse",
"jwt",
"form",
"hello",
"chatgpt",
"websocket",
"basic_auth",
"quick_start",
"static_files",
"json_response",
"derive_from_request",
"multiple-single-threads",
]
members = ["*"]
exclude = ["target"]

[workspace.dependencies]
# set `default-features = false` to assure "DEBUG" feature be off even when DEBUGing `../ohkami`
ohkami = { path = "../ohkami", default-features = false, features = ["rt_tokio", "sse", "ws"] }
tokio = { version = "1", features = ["full"] }
tracing = "0.1"
tracing-subscriber = "0.3"
tracing-subscriber = "0.3"
6 changes: 3 additions & 3 deletions examples/hello/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "hello"
version = "0.1.0"
edition = "2024"
name = "hello"
version = "0.1.0"
edition = "2024"

[dependencies]
ohkami = { workspace = true }
Expand Down
9 changes: 9 additions & 0 deletions examples/html_layout/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[package]
name = "html_layout"
version = "0.0.0"
edition = "2024"

[dependencies]
ohkami = { workspace = true }
tokio = { workspace = true }
uibeam = "0.2"
104 changes: 104 additions & 0 deletions examples/html_layout/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
use ohkami::prelude::*;
use ohkami::serde::Deserialize;
use ohkami::format::{Query, HTML};
use uibeam::{UI, Beam};

struct Layout {
title: String,
children: UI,
}
impl Beam for Layout {
fn render(self) -> UI {
UI! {
<html>
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" />
<title>{&*self.title}</title>
</head>
<body>
{self.children}
</body>
</html>
}
}
}
impl Layout {
fn fang_with_title(title: &str) -> impl FangAction {
#[derive(Clone)]
struct Fang {
title: String,
}

impl FangAction for Fang {
async fn back(&self, res: &mut Response) {
if res.headers.ContentType().is_some_and(|x| x.starts_with("text/html")) {
let content = res.drop_content().into_bytes().unwrap();
let content = std::str::from_utf8(&*content).unwrap();
res.set_html(uibeam::shoot(UI! {
<Layout title={self.title.clone()}>
unsafe {content}
</Layout>
}));
}
}
}

Fang {
title: title.to_string(),
}
}
}

struct Counter {
initial_count: i32,
}
impl Beam for Counter {
fn render(self) -> UI {
UI! {
<div>
<h1 class="text-2xl font-bold">
"count: "<span id="count">{self.initial_count}</span>
</h1>
<button
id="increment"
class="bg-blue-500 text-white px-4 py-2 rounded"
>"+"</button>
<button
id="decrement"
class="bg-red-500 text-white px-4 py-2 rounded"
>"-"</button>

<script>r#"
const count = document.getElementById('count');
document.getElementById('increment').addEventListener('click', () => {
count.innerText = parseInt(count.innerText) + 1;
});
document.getElementById('decrement').addEventListener('click', () => {
count.innerText = parseInt(count.innerText) - 1;
});
"#</script>
</div>
}
}
}

#[derive(Deserialize)]
struct CounterMeta {
init: Option<i32>,
}

async fn index(Query(q): Query<CounterMeta>) -> HTML<std::borrow::Cow<'static, str>> {
let initial_count = q.init.unwrap_or(0);

HTML(uibeam::shoot(UI! {
<Counter initial_count={initial_count} />
}))
}

#[tokio::main]
async fn main() {
Ohkami::new((
Layout::fang_with_title("Counter Example"),
"/".GET(index),
)).howl("localhost:5555").await
}
12 changes: 12 additions & 0 deletions examples/test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,15 @@ cd $EXAMPLES/jwt && \
|| exit 1
cd $EXAMPLES/jwt && \
OHKAMI_REQUEST_BUFSIZE=4096 cargo test

cd $EXAMPLES/html_layout && \
cargo build && \
(timeout -sKILL 5 cargo run &) && \
sleep 1 && \
CONTENT_TYPE_COUNT=$(curl -i 'http://localhost:5555' 2>&1 | grep -i 'content-type' | wc -l) && \
if [ $CONTENT_TYPE_COUNT -eq 1 ]; then
echo '---> ok'
else
echo '---> multiple content-type headers found (or something else went wrong)'
exit 1
fi
100 changes: 95 additions & 5 deletions ohkami/src/header/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,25 +38,35 @@ impl<const N: usize, Value> IndexMap<N, Value> {

#[inline(always)]
pub(crate) unsafe fn delete(&mut self, index: usize) {
unsafe {*self.index.get_unchecked_mut(index) = Self::NULL}
*unsafe {self.index.get_unchecked_mut(index)} = Self::NULL;
}

#[inline(always)]
pub(crate) unsafe fn set(&mut self, index: usize, value: Value) {
unsafe {*self.index.get_unchecked_mut(index) = self.values.len() as u8}
*unsafe {self.index.get_unchecked_mut(index)} = self.values.len() as u8;
self.values.push((index, value));
}

#[inline(always)]
pub(crate) fn iter(&self) -> impl Iterator<Item = &(usize, Value)> {
pub(crate) fn iter(&self) -> impl Iterator<Item = (usize, &Value)> {
self.values.iter()
.filter(|(i, _)| *unsafe {self.index.get_unchecked(*i)} != Self::NULL)
.enumerate()
.filter_map(|(pos, (index, value))| (
// `!= Self::NULL` can't correctly handle *over-set after delete*,
// we MUST check the held index to be equal to the current position
*unsafe {self.index.get_unchecked(*index)} == pos as u8
).then_some((*index, value)))
}

#[inline(always)]
pub(crate) fn into_iter(self) -> impl Iterator<Item = (usize, Value)> {
self.values.into_iter()
.filter(move |(i, _)| *unsafe {self.index.get_unchecked(*i)} != Self::NULL)
.enumerate()
.filter_map(move |(pos, (index, value))| (
// `!= Self::NULL` can't correctly handle *over-set after delete*,
// we MUST check the held index to be equal to the current position
*unsafe {self.index.get_unchecked(index)} == pos as u8
).then_some((index, value)))
}
}

Expand All @@ -80,3 +90,83 @@ const _: () = {
}
}
};

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

#[test]
fn test_index_map_iter_simple() {
let mut map = IndexMap::<8, &'static str>::new();

unsafe {map.set(0, "a")};
unsafe {map.set(1, "b")};
unsafe {map.set(2, "c")};
unsafe {map.set(3, "d")};

assert_eq!(
map.into_iter().collect::<Vec<_>>(),
vec![(0, "a"), (1, "b"), (2, "c"), (3, "d")]
);
}

#[test]
fn test_index_map_iter_with_delete() {
let mut map = IndexMap::<8, &'static str>::new();

unsafe {map.set(0, "a")};
unsafe {map.set(1, "b")};
unsafe {map.set(2, "c")};
unsafe {map.set(3, "d")};

unsafe {map.delete(1)};
unsafe {map.delete(3)};

assert_eq!(
map.into_iter().collect::<Vec<_>>(),
vec![(0, "a"), (2, "c")]
);
}

#[test]
fn test_index_map_iter_with_delete_and_other_set() {
let mut map = IndexMap::<8, &'static str>::new();

unsafe {map.set(0, "a")};
unsafe {map.set(1, "b")};
unsafe {map.set(2, "c")};
unsafe {map.set(3, "d")};

unsafe {map.delete(1)};
unsafe {map.delete(3)};

unsafe {map.set(4, "e")};
unsafe {map.set(5, "f")};

assert_eq!(
map.into_iter().collect::<Vec<_>>(),
vec![(0, "a"), (2, "c"), (4, "e"), (5, "f")]
);
}

#[test]
fn test_index_map_iter_with_delete_and_overset() {
let mut map = IndexMap::<8, &'static str>::new();

unsafe {map.set(0, "a")};
unsafe {map.set(1, "b")};
unsafe {map.set(2, "c")};
unsafe {map.set(3, "d")};

unsafe {map.delete(1)};
unsafe {map.delete(3)};

unsafe {map.set(1, "e")};
unsafe {map.set(3, "f")};

assert_eq!(
map.into_iter().collect::<Vec<_>>(),
vec![(0, "a"), (2, "c"), (1, "e"), (3, "f")]
);
}
}
2 changes: 1 addition & 1 deletion ohkami/src/request/headers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ impl Headers {
pub(crate) fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
self.standard.iter()
.map(|(i, v)| (
unsafe {std::mem::transmute::<_, Header>(*i as u8).as_str()},
unsafe {std::mem::transmute::<_, Header>(i as u8).as_str()},
std::str::from_utf8(v).expect("Non UTF-8 header value")
))
.chain(self.custom.as_ref()
Expand Down
4 changes: 2 additions & 2 deletions ohkami/src/response/headers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -439,7 +439,7 @@ impl Headers {
pub(crate) fn iter_standard(&self) -> impl Iterator<Item = (&str, &str)> {
self.standard.iter()
.map(|(i, v)| (
unsafe {std::mem::transmute::<_, Header>(*i as u8)}.as_str(),
unsafe {std::mem::transmute::<_, Header>(i as u8)}.as_str(),
&**v
))
}
Expand Down Expand Up @@ -481,7 +481,7 @@ impl Headers {
pub(crate) unsafe fn write_unchecked_to(&self, buf: &mut Vec<u8>) {
unsafe {
for (i, v) in self.standard.iter() {
let h = std::mem::transmute::<_, Header>(*i as u8); {
let h = std::mem::transmute::<_, Header>(i as u8); {
crate::push_unchecked!(buf <- h.as_bytes());
crate::push_unchecked!(buf <- b": ");
crate::push_unchecked!(buf <- v.as_bytes());
Expand Down