Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
16 changes: 3 additions & 13 deletions examples/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,21 +1,11 @@
[workspace]
resolver = "2"
members = [
"sse",
"form",
"hello",
"chatgpt",
"websocket",
"basic_auth",
"quick_start",
"static_files",
"json_response",
"derive_from_request",
]
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"
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:5000").await
}
96 changes: 93 additions & 3 deletions ohkami/src/header/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,25 @@ impl<const N: usize, Value> IndexMap<N, 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
2 changes: 1 addition & 1 deletion ohkami/src/response/headers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -438,7 +438,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
Loading