Skip to content

Commit

Permalink
new stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
vincent-thomas committed Jan 16, 2025
1 parent a84e377 commit c78ac31
Show file tree
Hide file tree
Showing 7 changed files with 112 additions and 8 deletions.
18 changes: 14 additions & 4 deletions titan-router/src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,20 @@ pub struct Match<V> {
pub params: HashMap<String, String>,
}

impl<V> IntoIterator for Router<V>
where
V: Clone,
{
type Item = (Segments, V);
type IntoIter = std::vec::IntoIter<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
let mut vec: Vec<(Segments, V)> = self.lookup_cache.into_iter().collect();

vec.extend(self.routes);
vec.into_iter()
}
}

impl<V> Router<V>
where
V: Clone,
Expand All @@ -49,9 +63,6 @@ where

for (key, value) in self.routes.iter() {
if let FindSegmentResult::Match(params) = key.find(&segments.0) {
//if params.is_empty() {
//self.lookup_cache.insert(segments, RouteId(index));
//}
return Some(Match { value, params });
};
}
Expand All @@ -62,7 +73,6 @@ where
let from_request = Segments::from(route.to_string());

if let Some(value) = self.lookup_cache.get(&from_request) {
//let (_, value) = &self.routes[*route_index];
return Some(Match { value, params: HashMap::default() });
};

Expand Down
10 changes: 10 additions & 0 deletions titan-router/src/segment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,16 @@ pub(crate) enum Segment {
Param(String),
}

impl std::fmt::Display for Segment {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Segment::Slash => f.write_str("/"),
Segment::Exact(string) => f.write_str(string),
Segment::Param(param) => f.write_str(format!(":{}", param).as_str()),
}
}
}

pub(crate) trait CompareSegment {
fn eq(&self, may_be_dynamic: &Self) -> CompareSegmentOut;
}
Expand Down
13 changes: 11 additions & 2 deletions titan-router/src/segments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,25 @@ use std::collections::HashMap;
use crate::segment::{CompareSegment, CompareSegmentOut, Segment};

#[derive(Default, Hash, Clone, Debug, Eq, PartialEq)]
pub(crate) struct Segments(pub(crate) Vec<Segment>);
pub struct Segments(pub(crate) Vec<Segment>);

#[derive(PartialEq, Debug)]
pub enum FindSegmentResult {
NoMatch,
Match(HashMap<String, String>),
}

impl std::fmt::Display for Segments {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for item in self.0.iter() {
f.write_str(item.to_string().as_str())?;
}
Ok(())
}
}

impl Segments {
pub(crate) fn num_params(&self) -> usize {
pub fn num_params(&self) -> usize {
let mut count = 0;
for item in &self.0 {
if let Segment::Param(_) = item {
Expand Down
5 changes: 4 additions & 1 deletion titan/examples/hello_world.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,5 +69,8 @@ async fn main() -> io::Result<()> {
let app =
App::default().at("/", web::get(index)).at("/test", web::get(testing));

titan::serve(listener, app).await
titan::build::build_static(app, std::path::PathBuf::from("./dist")).await;
Ok(())

//titan::serve(listener, app).await
}
2 changes: 1 addition & 1 deletion titan/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ macro_rules! tap_inner {
}

impl App {
fn into_inner(self) -> AppInner {
pub(crate) fn into_inner(self) -> AppInner {
match Arc::try_unwrap(self.inner) {
Ok(inner) => inner,
Err(arc) => {
Expand Down
71 changes: 71 additions & 0 deletions titan/src/build/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
use futures_util::StreamExt;
use std::path::PathBuf;
use titan_core::Service;

use titan_http::body::Body;
use titan_http::header;
use titan_http::Request;

pub async fn build_static(app: crate::App, path: PathBuf) {
let inner_app = app.into_inner();

for route in inner_app.router.into_iter() {
if route.0.num_params() != 0 {
panic!("Error: Can't statically build a dynamic path: {}", route.0)
}

println!("Route: {}", route.0);

let request = Request::new(Box::new([]));

let response = match route.1.clone().call(request).await {
Ok(value) => value,
Err(err) => {
panic!("Handler error in path: {:?}", route.0)
}
};

let (parts, body) = response.into_parts();

let bodyv2 = match body {
Body::Full(body) => body,
Body::Stream(mut stream) => {
let mut full_body_message = Vec::default();
while let Some(value) = stream.next().await {
full_body_message.extend(value)
}

full_body_message.into_boxed_slice()
}
};
if let Some(value) = parts.headers.get(header::CONTENT_TYPE) {
if value
!= header::HeaderValue::from_str(titan_http::mime::HTML.as_str())
.unwrap()
{
panic!("only works on html for now");
}
} else {
panic!("wtf");
}

let text_string = String::from_utf8(bodyv2.to_vec()).unwrap();

let mut path = route.0.to_string();

path.push_str(".html");

let mut this_path = path.clone();

this_path.push_str(&path);

let mut nice = std::fs::OpenOptions::new()
.create(true)
.write(true)
.open(this_path)
.unwrap();

use std::io::Write;
nice.write_all(text_string.as_bytes()).unwrap();
}
}
1 change: 1 addition & 0 deletions titan/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
mod app;
pub mod build;
pub mod guard;
pub mod prelude;
pub mod route;
Expand Down

0 comments on commit c78ac31

Please sign in to comment.