Compare commits
7 Commits
Author | SHA1 | Date | |
---|---|---|---|
0898a50166 | |||
e0baff8625 | |||
173bbc2ca5 | |||
cdc8f5e463 | |||
aba28d1612 | |||
752d1a9d10 | |||
83f85f1938 |
196
Cargo.lock
generated
196
Cargo.lock
generated
@ -47,6 +47,7 @@ dependencies = [
|
|||||||
"matchit",
|
"matchit",
|
||||||
"memchr",
|
"memchr",
|
||||||
"mime",
|
"mime",
|
||||||
|
"multer",
|
||||||
"percent-encoding",
|
"percent-encoding",
|
||||||
"pin-project-lite",
|
"pin-project-lite",
|
||||||
"rustversion",
|
"rustversion",
|
||||||
@ -98,6 +99,12 @@ dependencies = [
|
|||||||
"rustc-demangle",
|
"rustc-demangle",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "bitflags"
|
||||||
|
version = "2.6.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "bytes"
|
name = "bytes"
|
||||||
version = "1.6.0"
|
version = "1.6.0"
|
||||||
@ -124,6 +131,15 @@ dependencies = [
|
|||||||
"syn",
|
"syn",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "encoding_rs"
|
||||||
|
version = "0.8.34"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b45de904aa0b010bce2ab45264d0631681847fa7b6f2eaa7dab7619943bc4f59"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "fnv"
|
name = "fnv"
|
||||||
version = "1.0.7"
|
version = "1.0.7"
|
||||||
@ -270,16 +286,27 @@ version = "1.0.11"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b"
|
checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "lazy_static"
|
||||||
|
version = "1.5.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "lib"
|
name = "lib"
|
||||||
version = "1.0.0"
|
version = "1.3.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"axum",
|
"axum",
|
||||||
"derive",
|
"derive",
|
||||||
"nom",
|
"nom",
|
||||||
"serde",
|
"serde",
|
||||||
|
"thiserror",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tokio-util",
|
"tokio-util",
|
||||||
|
"tower",
|
||||||
|
"tower-http",
|
||||||
|
"tracing",
|
||||||
|
"tracing-subscriber",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@ -338,6 +365,23 @@ dependencies = [
|
|||||||
"windows-sys 0.48.0",
|
"windows-sys 0.48.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "multer"
|
||||||
|
version = "3.1.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b"
|
||||||
|
dependencies = [
|
||||||
|
"bytes",
|
||||||
|
"encoding_rs",
|
||||||
|
"futures-util",
|
||||||
|
"http",
|
||||||
|
"httparse",
|
||||||
|
"memchr",
|
||||||
|
"mime",
|
||||||
|
"spin",
|
||||||
|
"version_check",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "nom"
|
name = "nom"
|
||||||
version = "7.1.3"
|
version = "7.1.3"
|
||||||
@ -348,6 +392,16 @@ dependencies = [
|
|||||||
"minimal-lexical",
|
"minimal-lexical",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "nu-ansi-term"
|
||||||
|
version = "0.46.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84"
|
||||||
|
dependencies = [
|
||||||
|
"overload",
|
||||||
|
"winapi",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "object"
|
name = "object"
|
||||||
version = "0.36.0"
|
version = "0.36.0"
|
||||||
@ -363,6 +417,12 @@ version = "1.19.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92"
|
checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "overload"
|
||||||
|
version = "0.1.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "percent-encoding"
|
name = "percent-encoding"
|
||||||
version = "2.3.1"
|
version = "2.3.1"
|
||||||
@ -490,6 +550,15 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "sharded-slab"
|
||||||
|
version = "0.1.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"
|
||||||
|
dependencies = [
|
||||||
|
"lazy_static",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "smallvec"
|
name = "smallvec"
|
||||||
version = "1.13.2"
|
version = "1.13.2"
|
||||||
@ -506,6 +575,12 @@ dependencies = [
|
|||||||
"windows-sys 0.52.0",
|
"windows-sys 0.52.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "spin"
|
||||||
|
version = "0.9.8"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "syn"
|
name = "syn"
|
||||||
version = "2.0.67"
|
version = "2.0.67"
|
||||||
@ -529,6 +604,36 @@ version = "1.0.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "a7065abeca94b6a8a577f9bd45aa0867a2238b74e8eb67cf10d492bc39351394"
|
checksum = "a7065abeca94b6a8a577f9bd45aa0867a2238b74e8eb67cf10d492bc39351394"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "thiserror"
|
||||||
|
version = "1.0.61"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c546c80d6be4bc6a00c0f01730c08df82eaa7a7a61f11d656526506112cc1709"
|
||||||
|
dependencies = [
|
||||||
|
"thiserror-impl",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "thiserror-impl"
|
||||||
|
version = "1.0.61"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "46c3384250002a6d5af4d114f2845d37b57521033f30d5c3f46c4d70e1197533"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "thread_local"
|
||||||
|
version = "1.1.8"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8b9ef9bad013ada3808854ceac7b46812a6465ba368859a37e2100283d2d719c"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
"once_cell",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tokio"
|
name = "tokio"
|
||||||
version = "1.38.0"
|
version = "1.38.0"
|
||||||
@ -584,6 +689,23 @@ dependencies = [
|
|||||||
"tracing",
|
"tracing",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tower-http"
|
||||||
|
version = "0.5.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1e9cd434a998747dd2c4276bc96ee2e0c7a2eadf3cae88e52be55a05fa9053f5"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags",
|
||||||
|
"bytes",
|
||||||
|
"http",
|
||||||
|
"http-body",
|
||||||
|
"http-body-util",
|
||||||
|
"pin-project-lite",
|
||||||
|
"tower-layer",
|
||||||
|
"tower-service",
|
||||||
|
"tracing",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tower-layer"
|
name = "tower-layer"
|
||||||
version = "0.3.2"
|
version = "0.3.2"
|
||||||
@ -604,9 +726,21 @@ checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"log",
|
"log",
|
||||||
"pin-project-lite",
|
"pin-project-lite",
|
||||||
|
"tracing-attributes",
|
||||||
"tracing-core",
|
"tracing-core",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tracing-attributes"
|
||||||
|
version = "0.1.27"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tracing-core"
|
name = "tracing-core"
|
||||||
version = "0.1.32"
|
version = "0.1.32"
|
||||||
@ -614,6 +748,32 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "c06d3da6113f116aaee68e4d601191614c9053067f9ab7f6edbcb161237daa54"
|
checksum = "c06d3da6113f116aaee68e4d601191614c9053067f9ab7f6edbcb161237daa54"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"once_cell",
|
"once_cell",
|
||||||
|
"valuable",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tracing-log"
|
||||||
|
version = "0.2.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"
|
||||||
|
dependencies = [
|
||||||
|
"log",
|
||||||
|
"once_cell",
|
||||||
|
"tracing-core",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tracing-subscriber"
|
||||||
|
version = "0.3.18"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ad0f048c97dbd9faa9b7df56362b8ebcaa52adb06b498c050d2f4e32f90a7a8b"
|
||||||
|
dependencies = [
|
||||||
|
"nu-ansi-term",
|
||||||
|
"sharded-slab",
|
||||||
|
"smallvec",
|
||||||
|
"thread_local",
|
||||||
|
"tracing-core",
|
||||||
|
"tracing-log",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@ -622,12 +782,46 @@ version = "1.0.12"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
|
checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "valuable"
|
||||||
|
version = "0.1.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "830b7e5d4d90034032940e4ace0d9a9a057e7a45cd94e6c007832e39edb82f6d"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "version_check"
|
||||||
|
version = "0.9.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "wasi"
|
name = "wasi"
|
||||||
version = "0.11.0+wasi-snapshot-preview1"
|
version = "0.11.0+wasi-snapshot-preview1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
|
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "winapi"
|
||||||
|
version = "0.3.9"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
|
||||||
|
dependencies = [
|
||||||
|
"winapi-i686-pc-windows-gnu",
|
||||||
|
"winapi-x86_64-pc-windows-gnu",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "winapi-i686-pc-windows-gnu"
|
||||||
|
version = "0.4.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "winapi-x86_64-pc-windows-gnu"
|
||||||
|
version = "0.4.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows-sys"
|
name = "windows-sys"
|
||||||
version = "0.48.0"
|
version = "0.48.0"
|
||||||
|
18
Cargo.toml
18
Cargo.toml
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "lib"
|
name = "lib"
|
||||||
version = "1.0.0"
|
version = "1.3.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
authors = ["Martin Berg Alstad"]
|
authors = ["Martin Berg Alstad"]
|
||||||
|
|
||||||
@ -8,10 +8,17 @@ authors = ["Martin Berg Alstad"]
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
# Api
|
# Api
|
||||||
axum = { version = "0.7.5", optional = true }
|
axum = { version = "0.7.5", optional = true, features = ["multipart"] }
|
||||||
|
tower = { version = "0.4.13", optional = true }
|
||||||
|
tower-http = { version = "0.5.2", optional = true, features = ["trace", "cors", "normalize-path"] }
|
||||||
# Async
|
# Async
|
||||||
tokio = { version = "1.38.0", optional = true, features = ["fs"] }
|
tokio = { version = "1.38.0", optional = true, features = ["fs"] }
|
||||||
tokio-util = { version = "0.7.11", optional = true, features = ["io"] }
|
tokio-util = { version = "0.7.11", optional = true, features = ["io"] }
|
||||||
|
# Error handling
|
||||||
|
thiserror = { version = "1.0.61", optional = true }
|
||||||
|
# Logging
|
||||||
|
tracing = { version = "0.1.40", optional = true }
|
||||||
|
tracing-subscriber = { version = "0.3.18", optional = true }
|
||||||
# Parsing
|
# Parsing
|
||||||
nom = { version = "7.1.3", optional = true }
|
nom = { version = "7.1.3", optional = true }
|
||||||
# Serialization / Deserialization
|
# Serialization / Deserialization
|
||||||
@ -20,9 +27,10 @@ serde = { version = "1.0.203", optional = true, features = ["derive"] }
|
|||||||
derive = { path = "derive", optional = true }
|
derive = { path = "derive", optional = true }
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
axum = ["dep:axum"]
|
axum = ["dep:axum", "dep:tower", "dep:tower-http", "dep:thiserror", "dep:tracing", "dep:tracing-subscriber"]
|
||||||
tokio = ["dep:tokio", "dep:tokio-util"]
|
tokio = ["dep:tokio"]
|
||||||
vec = []
|
io = ["dep:tokio", "dep:tokio-util"]
|
||||||
|
iter = []
|
||||||
nom = ["dep:nom"]
|
nom = ["dep:nom"]
|
||||||
serde = ["dep:serde"]
|
serde = ["dep:serde"]
|
||||||
derive = ["dep:derive", "axum", "serde"]
|
derive = ["dep:derive", "axum", "serde"]
|
||||||
|
155
src/axum/app.rs
155
src/axum/app.rs
@ -1,5 +1,20 @@
|
|||||||
|
use {
|
||||||
|
axum::{extract::Request, handler::Handler, Router, ServiceExt},
|
||||||
|
std::net::Ipv4Addr,
|
||||||
|
tower::layer::Layer,
|
||||||
|
tower_http::{
|
||||||
|
cors::CorsLayer,
|
||||||
|
normalize_path::NormalizePathLayer,
|
||||||
|
trace,
|
||||||
|
trace::{HttpMakeClassifier, TraceLayer},
|
||||||
|
},
|
||||||
|
tracing::{info, Level},
|
||||||
|
};
|
||||||
|
#[cfg(feature = "tokio")]
|
||||||
|
use {std::io, std::net::SocketAddr, tokio::net::TcpListener};
|
||||||
|
|
||||||
|
// TODO trim trailing slash into macro > let _app = NormalizePathLayer::trim_trailing_slash().layer(create_app!(routes));
|
||||||
#[macro_export]
|
#[macro_export]
|
||||||
#[cfg(feature = "axum")]
|
|
||||||
macro_rules! create_app {
|
macro_rules! create_app {
|
||||||
($router:expr) => {
|
($router:expr) => {
|
||||||
$router
|
$router
|
||||||
@ -9,10 +24,146 @@ macro_rules! create_app {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(all(test, feature = "axum"))]
|
#[derive(Default)]
|
||||||
|
pub struct AppBuilder {
|
||||||
|
router: Router,
|
||||||
|
socket: Option<(Ipv4Addr, u16)>,
|
||||||
|
cors: Option<CorsLayer>,
|
||||||
|
normalize_path: Option<bool>,
|
||||||
|
tracing: Option<TraceLayer<HttpMakeClassifier>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AppBuilder {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn route(mut self, route: Router) -> Self {
|
||||||
|
self.router = self.router.merge(route);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn routes(mut self, routes: impl IntoIterator<Item = Router>) -> Self {
|
||||||
|
self.router = routes.into_iter().fold(self.router, Router::merge);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn socket(mut self, socket: impl Into<(Ipv4Addr, u16)>) -> Self {
|
||||||
|
self.socket = Some(socket.into());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fallback<H, T>(mut self, fallback: H) -> Self
|
||||||
|
where
|
||||||
|
H: Handler<T, ()>,
|
||||||
|
T: 'static,
|
||||||
|
{
|
||||||
|
self.router = self.router.fallback(fallback);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn cors(mut self, cors: CorsLayer) -> Self {
|
||||||
|
self.cors = Some(cors);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn normalize_path(mut self, normalize_path: bool) -> Self {
|
||||||
|
self.normalize_path = Some(normalize_path);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn tracing(mut self, tracing: TraceLayer<HttpMakeClassifier>) -> Self {
|
||||||
|
self.tracing = Some(tracing);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "tokio")]
|
||||||
|
pub async fn serve(self) -> io::Result<()> {
|
||||||
|
let _ = fmt_trace(); // Allowed to fail
|
||||||
|
let listener = self.listener().await?;
|
||||||
|
|
||||||
|
if self.normalize_path.unwrap_or(true) {
|
||||||
|
let app = NormalizePathLayer::trim_trailing_slash().layer(self.create_app());
|
||||||
|
axum::serve(listener, ServiceExt::<Request>::into_make_service(app)).await?;
|
||||||
|
} else {
|
||||||
|
let app = self.create_app();
|
||||||
|
axum::serve(listener, app.into_make_service()).await?;
|
||||||
|
};
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "tokio")]
|
||||||
|
async fn listener(&self) -> io::Result<TcpListener> {
|
||||||
|
let addr = SocketAddr::from(self.socket.unwrap_or((Ipv4Addr::UNSPECIFIED, 8000)));
|
||||||
|
info!("Initializing server on: {addr}");
|
||||||
|
TcpListener::bind(&addr).await
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_app(self) -> Router {
|
||||||
|
let mut app = self.router;
|
||||||
|
if let Some(cors) = self.cors {
|
||||||
|
app = app.layer(cors);
|
||||||
|
}
|
||||||
|
app.layer(
|
||||||
|
self.tracing.unwrap_or(
|
||||||
|
TraceLayer::new_for_http()
|
||||||
|
.make_span_with(trace::DefaultMakeSpan::new().level(Level::INFO))
|
||||||
|
.on_response(trace::DefaultOnResponse::new().level(Level::INFO)),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fmt_trace() -> Result<(), String> {
|
||||||
|
tracing_subscriber::fmt()
|
||||||
|
.with_target(false)
|
||||||
|
.compact()
|
||||||
|
.try_init()
|
||||||
|
.map_err(|error| error.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use axum::Router;
|
use axum::Router;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[cfg(feature = "tokio")]
|
||||||
|
mod tokio_tests {
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use tokio::time::sleep;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_app_builder_serve() {
|
||||||
|
let handler = tokio::spawn(async {
|
||||||
|
AppBuilder::new().serve().await.unwrap();
|
||||||
|
});
|
||||||
|
sleep(Duration::from_secs(1)).await;
|
||||||
|
handler.abort();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_app_builder_all() {
|
||||||
|
let handler = tokio::spawn(async {
|
||||||
|
AppBuilder::new()
|
||||||
|
.socket((Ipv4Addr::LOCALHOST, 8080))
|
||||||
|
.routes([Router::new()])
|
||||||
|
.fallback(|| async { "Fallback" })
|
||||||
|
.cors(CorsLayer::new())
|
||||||
|
.normalize_path(true)
|
||||||
|
.tracing(TraceLayer::new_for_http())
|
||||||
|
.serve()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
});
|
||||||
|
sleep(Duration::from_secs(1)).await;
|
||||||
|
handler.abort();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_create_app_router_only() {
|
fn test_create_app_router_only() {
|
||||||
let _app: Router<()> = create_app!(Router::new());
|
let _app: Router<()> = create_app!(Router::new());
|
||||||
|
187
src/axum/extractor.rs
Normal file
187
src/axum/extractor.rs
Normal file
@ -0,0 +1,187 @@
|
|||||||
|
use axum::{
|
||||||
|
async_trait,
|
||||||
|
extract::{
|
||||||
|
multipart::{Field, MultipartError, MultipartRejection},
|
||||||
|
FromRequest, Multipart, Request,
|
||||||
|
},
|
||||||
|
response::IntoResponse,
|
||||||
|
};
|
||||||
|
use thiserror::Error;
|
||||||
|
|
||||||
|
#[derive(PartialEq, Eq, Ord, PartialOrd, Hash, Debug, Clone, Copy)]
|
||||||
|
pub enum ContentType {
|
||||||
|
Json,
|
||||||
|
Form,
|
||||||
|
Multipart,
|
||||||
|
Pdf,
|
||||||
|
Html,
|
||||||
|
Unknown,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<&str> for ContentType {
|
||||||
|
fn from(content_type: &str) -> Self {
|
||||||
|
match content_type {
|
||||||
|
"application/json" => ContentType::Json,
|
||||||
|
"application/x-www-form-urlencoded" => ContentType::Form,
|
||||||
|
"multipart/form-data" => ContentType::Multipart,
|
||||||
|
"application/pdf" => ContentType::Pdf,
|
||||||
|
"text/html" => ContentType::Html,
|
||||||
|
_ => ContentType::Unknown,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<String> for ContentType {
|
||||||
|
fn from(content_type: String) -> Self {
|
||||||
|
ContentType::from(content_type.as_str())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<Option<&str>> for ContentType {
|
||||||
|
fn from(content_type: Option<&str>) -> Self {
|
||||||
|
content_type
|
||||||
|
.map(ContentType::from)
|
||||||
|
.unwrap_or(ContentType::Unknown)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct File {
|
||||||
|
pub filename: String,
|
||||||
|
pub bytes: Vec<u8>,
|
||||||
|
pub content_type: ContentType,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl File {
|
||||||
|
pub fn new(
|
||||||
|
filename: impl Into<String>,
|
||||||
|
bytes: impl Into<Vec<u8>>,
|
||||||
|
content_type: impl Into<ContentType>,
|
||||||
|
) -> Self {
|
||||||
|
Self {
|
||||||
|
filename: filename.into(),
|
||||||
|
bytes: bytes.into(),
|
||||||
|
content_type: content_type.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn from_field(field: Field<'_>) -> Result<Self, MultipartFileRejection> {
|
||||||
|
let filename = field
|
||||||
|
.file_name()
|
||||||
|
.ok_or(MultipartFileRejection::MissingFilename)?
|
||||||
|
.to_string();
|
||||||
|
let content_type: ContentType = field.content_type().into();
|
||||||
|
let bytes = field.bytes().await?;
|
||||||
|
Ok(File::new(filename, bytes, content_type))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Extractor for a single file from a multipart request.
|
||||||
|
/// Expects exactly one file. A file must have a name, bytes and optionally a content type.
|
||||||
|
/// This extractor consumes the request and must ble placed last in the handler.
|
||||||
|
pub struct MultipartFile(pub File);
|
||||||
|
/// Extractor for multiple files from a multipart request.
|
||||||
|
/// Expects at least one file. A file must have a name, bytes and optionally a content type.
|
||||||
|
/// This extractor consumes the request and must ble placed last in the handler.
|
||||||
|
pub struct MultipartFiles(pub Vec<File>);
|
||||||
|
|
||||||
|
#[derive(Debug, Error)]
|
||||||
|
pub enum MultipartFileRejection {
|
||||||
|
#[error(transparent)]
|
||||||
|
MultipartRejection(#[from] MultipartRejection),
|
||||||
|
#[error("Field error: {0}")]
|
||||||
|
FieldError(String),
|
||||||
|
#[error("No files found")]
|
||||||
|
NoFiles,
|
||||||
|
#[error("Expected one file, got several")]
|
||||||
|
SeveralFiles,
|
||||||
|
#[error("Missing filename")]
|
||||||
|
MissingFilename,
|
||||||
|
#[error("Error in body of multipart: {0}")]
|
||||||
|
BodyError(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<MultipartError> for MultipartFileRejection {
|
||||||
|
fn from(error: MultipartError) -> Self {
|
||||||
|
MultipartFileRejection::BodyError(error.body_text())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IntoResponse for MultipartFileRejection {
|
||||||
|
fn into_response(self) -> axum::response::Response {
|
||||||
|
match self {
|
||||||
|
MultipartFileRejection::MultipartRejection(rejection) => rejection.into_response(),
|
||||||
|
MultipartFileRejection::FieldError(error) => {
|
||||||
|
(axum::http::StatusCode::BAD_REQUEST, error).into_response()
|
||||||
|
}
|
||||||
|
MultipartFileRejection::NoFiles => {
|
||||||
|
(axum::http::StatusCode::BAD_REQUEST, "No files found").into_response()
|
||||||
|
}
|
||||||
|
MultipartFileRejection::SeveralFiles => (
|
||||||
|
axum::http::StatusCode::BAD_REQUEST,
|
||||||
|
"Expected one file, got several",
|
||||||
|
)
|
||||||
|
.into_response(),
|
||||||
|
MultipartFileRejection::MissingFilename => {
|
||||||
|
(axum::http::StatusCode::BAD_REQUEST, "Missing filename").into_response()
|
||||||
|
}
|
||||||
|
MultipartFileRejection::BodyError(error) => {
|
||||||
|
(axum::http::StatusCode::BAD_REQUEST, error).into_response()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl<S> FromRequest<S> for MultipartFile
|
||||||
|
where
|
||||||
|
S: Send + Sync,
|
||||||
|
{
|
||||||
|
type Rejection = MultipartFileRejection;
|
||||||
|
|
||||||
|
async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
|
||||||
|
let mut multipart = Multipart::from_request(req, state).await?;
|
||||||
|
let fields = get_fields(&mut multipart).await?;
|
||||||
|
if fields.len() > 1 {
|
||||||
|
Err(MultipartFileRejection::SeveralFiles)
|
||||||
|
} else {
|
||||||
|
let field = fields
|
||||||
|
.into_iter()
|
||||||
|
.next()
|
||||||
|
.ok_or(MultipartFileRejection::NoFiles)?;
|
||||||
|
Ok(MultipartFile(File::from_field(field).await?))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl<S> FromRequest<S> for MultipartFiles
|
||||||
|
where
|
||||||
|
S: Send + Sync,
|
||||||
|
{
|
||||||
|
type Rejection = MultipartFileRejection;
|
||||||
|
|
||||||
|
async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
|
||||||
|
let mut multipart = Multipart::from_request(req, state).await?;
|
||||||
|
let fields = get_fields(&mut multipart).await?;
|
||||||
|
if fields.is_empty() {
|
||||||
|
Err(MultipartFileRejection::NoFiles)
|
||||||
|
} else {
|
||||||
|
let mut files = vec![];
|
||||||
|
for field in fields.into_iter() {
|
||||||
|
files.push(File::from_field(field).await?);
|
||||||
|
}
|
||||||
|
Ok(MultipartFiles(files))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_fields<'a>(
|
||||||
|
multipart: &'a mut Multipart,
|
||||||
|
) -> Result<Vec<Field<'a>>, MultipartFileRejection> {
|
||||||
|
let fields: Vec<Field> = multipart.next_field().await?.into_iter().collect();
|
||||||
|
if fields.is_empty() {
|
||||||
|
Err(MultipartFileRejection::NoFiles)
|
||||||
|
} else {
|
||||||
|
Ok(fields)
|
||||||
|
}
|
||||||
|
}
|
@ -1,4 +1,4 @@
|
|||||||
#[cfg(all(feature = "tokio", feature = "axum"))]
|
#[cfg(feature = "tokio")]
|
||||||
use {crate::io::file, axum::body::Body, axum::response::Html, std::io};
|
use {crate::io::file, axum::body::Body, axum::response::Html, std::io};
|
||||||
|
|
||||||
/// Load an HTML file from the given file path, relative to the current directory.
|
/// Load an HTML file from the given file path, relative to the current directory.
|
||||||
@ -10,7 +10,7 @@ use {crate::io::file, axum::body::Body, axum::response::Html, std::io};
|
|||||||
/// ```
|
/// ```
|
||||||
/// let html = async { lib::axum::load::load_html("openapi.html").await.unwrap() };
|
/// let html = async { lib::axum::load::load_html("openapi.html").await.unwrap() };
|
||||||
/// ```
|
/// ```
|
||||||
#[cfg(all(feature = "tokio", feature = "axum"))]
|
#[cfg(feature = "tokio")]
|
||||||
pub async fn load_html<Path>(file_path: Path) -> Result<Html<Body>, io::Error>
|
pub async fn load_html<Path>(file_path: Path) -> Result<Html<Body>, io::Error>
|
||||||
where
|
where
|
||||||
Path: AsRef<std::path::Path>,
|
Path: AsRef<std::path::Path>,
|
||||||
@ -18,7 +18,7 @@ where
|
|||||||
load_file(file_path).await.map(Html)
|
load_file(file_path).await.map(Html)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(all(feature = "tokio", feature = "axum"))]
|
#[cfg(feature = "tokio")]
|
||||||
pub async fn load_file<Path>(file_path: Path) -> Result<Body, io::Error>
|
pub async fn load_file<Path>(file_path: Path) -> Result<Body, io::Error>
|
||||||
where
|
where
|
||||||
Path: AsRef<std::path::Path>,
|
Path: AsRef<std::path::Path>,
|
||||||
@ -38,7 +38,6 @@ where
|
|||||||
/// ```
|
/// ```
|
||||||
// TODO check platform and use correct path separator
|
// TODO check platform and use correct path separator
|
||||||
#[macro_export]
|
#[macro_export]
|
||||||
#[cfg(feature = "axum")]
|
|
||||||
macro_rules! load_html {
|
macro_rules! load_html {
|
||||||
($filepath:expr) => {
|
($filepath:expr) => {
|
||||||
axum::response::Html(
|
axum::response::Html(
|
||||||
@ -58,7 +57,7 @@ macro_rules! load_html {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(all(test, feature = "axum"))]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
#[test]
|
#[test]
|
||||||
fn test_load_html() {
|
fn test_load_html() {
|
||||||
|
@ -1,4 +1,6 @@
|
|||||||
pub mod app;
|
pub mod app;
|
||||||
|
pub mod extractor;
|
||||||
pub mod load;
|
pub mod load;
|
||||||
|
#[cfg(feature = "serde")]
|
||||||
pub mod response;
|
pub mod response;
|
||||||
pub mod router;
|
pub mod router;
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
#[cfg(all(feature = "axum", feature = "serde"))]
|
|
||||||
use {
|
use {
|
||||||
crate::serde::response::BaseResponse,
|
crate::serde::response::BaseResponse,
|
||||||
axum::{
|
axum::{
|
||||||
@ -8,14 +7,13 @@ use {
|
|||||||
serde::Serialize,
|
serde::Serialize,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[cfg(all(feature = "axum", feature = "serde"))]
|
|
||||||
impl<T: Serialize> IntoResponse for BaseResponse<T> {
|
impl<T: Serialize> IntoResponse for BaseResponse<T> {
|
||||||
fn into_response(self) -> Response {
|
fn into_response(self) -> Response {
|
||||||
Json(self).into_response()
|
Json(self).into_response()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(all(test, feature = "axum", feature = "serde"))]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use axum::http::header::CONTENT_TYPE;
|
use axum::http::header::CONTENT_TYPE;
|
||||||
use axum::http::{HeaderValue, StatusCode};
|
use axum::http::{HeaderValue, StatusCode};
|
||||||
|
@ -18,16 +18,23 @@
|
|||||||
/// ));
|
/// ));
|
||||||
/// ```
|
/// ```
|
||||||
#[macro_export]
|
#[macro_export]
|
||||||
#[cfg(feature = "axum")]
|
|
||||||
macro_rules! router {
|
macro_rules! router {
|
||||||
($body:expr) => {
|
($body:expr) => {
|
||||||
pub(crate) fn router() -> axum::Router<()> {
|
pub(crate) fn router() -> axum::Router {
|
||||||
|
$body
|
||||||
|
}
|
||||||
|
};
|
||||||
|
($body:expr; $state:ty) => {
|
||||||
|
pub(crate) fn router() -> axum::Router<$state> {
|
||||||
$body
|
$body
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
($route:expr, $router:expr) => {
|
($route:expr, $router:expr) => {
|
||||||
router!(axum::Router::new().nest($route, $router));
|
router!(axum::Router::new().nest($route, $router));
|
||||||
};
|
};
|
||||||
|
($route:expr, $router:expr, $state:ty) => {
|
||||||
|
router!(axum::Router::new().nest($route, $router); $state);
|
||||||
|
};
|
||||||
($($method:ident $route:expr => $func:expr),* $(,)?) => {
|
($($method:ident $route:expr => $func:expr),* $(,)?) => {
|
||||||
router!($crate::routes!($($method $route => $func),*));
|
router!($crate::routes!($($method $route => $func),*));
|
||||||
};
|
};
|
||||||
@ -44,7 +51,6 @@ macro_rules! router {
|
|||||||
/// );
|
/// );
|
||||||
/// ```
|
/// ```
|
||||||
#[macro_export]
|
#[macro_export]
|
||||||
#[cfg(feature = "axum")]
|
|
||||||
macro_rules! routes {
|
macro_rules! routes {
|
||||||
($($method:ident $route:expr => $func:expr),* $(,)?) => {
|
($($method:ident $route:expr => $func:expr),* $(,)?) => {
|
||||||
axum::Router::new()
|
axum::Router::new()
|
||||||
@ -55,7 +61,6 @@ macro_rules! routes {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[macro_export]
|
#[macro_export]
|
||||||
#[cfg(feature = "axum")]
|
|
||||||
macro_rules! join_routes {
|
macro_rules! join_routes {
|
||||||
($($route:expr),* $(,)?) => {
|
($($route:expr),* $(,)?) => {
|
||||||
axum::Router::new()$(
|
axum::Router::new()$(
|
||||||
@ -64,8 +69,9 @@ macro_rules! join_routes {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(all(test, feature = "axum"))]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
use axum::extract::State;
|
||||||
use axum::Router;
|
use axum::Router;
|
||||||
|
|
||||||
async fn index() {}
|
async fn index() {}
|
||||||
@ -94,9 +100,21 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_nested_router_with_state() {
|
||||||
|
router!(
|
||||||
|
"/simplify",
|
||||||
|
routes!(
|
||||||
|
get "/:exp" => || async {},
|
||||||
|
get "/table/:exp" => |_state: State<String>| async {}
|
||||||
|
),
|
||||||
|
String
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_routes() {
|
fn test_routes() {
|
||||||
let _router: Router<()> = routes!(
|
let _router: Router = routes!(
|
||||||
get "/" => index,
|
get "/" => index,
|
||||||
post "/" => || async {}
|
post "/" => || async {}
|
||||||
);
|
);
|
||||||
@ -104,6 +122,6 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_join_routes() {
|
fn test_join_routes() {
|
||||||
let _router: Router<()> = join_routes![Router::new(), Router::new()];
|
let _router: Router = join_routes![Router::new(), Router::new()];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,5 @@
|
|||||||
#[cfg(feature = "tokio")]
|
|
||||||
use {std::io::Error, tokio::fs::File, tokio_util::io::ReaderStream};
|
use {std::io::Error, tokio::fs::File, tokio_util::io::ReaderStream};
|
||||||
|
|
||||||
#[cfg(feature = "tokio")]
|
|
||||||
pub async fn load_file<Path>(file_path: Path) -> Result<ReaderStream<File>, Error>
|
pub async fn load_file<Path>(file_path: Path) -> Result<ReaderStream<File>, Error>
|
||||||
where
|
where
|
||||||
Path: AsRef<std::path::Path>,
|
Path: AsRef<std::path::Path>,
|
||||||
@ -9,7 +7,7 @@ where
|
|||||||
File::open(file_path).await.map(ReaderStream::new)
|
File::open(file_path).await.map(ReaderStream::new)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(all(test, feature = "tokio"))]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
@ -1,10 +1,16 @@
|
|||||||
#![allow(dead_code)]
|
#![allow(dead_code)]
|
||||||
|
|
||||||
|
#[cfg(feature = "axum")]
|
||||||
pub mod axum;
|
pub mod axum;
|
||||||
|
#[cfg(feature = "io")]
|
||||||
pub mod io;
|
pub mod io;
|
||||||
|
#[cfg(feature = "nom")]
|
||||||
pub mod nom;
|
pub mod nom;
|
||||||
|
#[cfg(feature = "serde")]
|
||||||
pub mod serde;
|
pub mod serde;
|
||||||
|
pub mod traits;
|
||||||
|
#[cfg(feature = "iter")]
|
||||||
pub mod vector;
|
pub mod vector;
|
||||||
|
|
||||||
#[cfg(feature = "derive")]
|
#[cfg(all(feature = "derive", feature = "serde"))]
|
||||||
pub extern crate derive;
|
pub extern crate derive;
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
#[cfg(feature = "nom")]
|
|
||||||
use {
|
use {
|
||||||
nom::{
|
nom::{
|
||||||
bytes::complete::take_while_m_n,
|
bytes::complete::take_while_m_n,
|
||||||
@ -16,7 +15,6 @@ use {
|
|||||||
/// - Parameters
|
/// - Parameters
|
||||||
/// - `inner`: The parser to trim
|
/// - `inner`: The parser to trim
|
||||||
/// - Returns: A parser that trims leading and trailing whitespace from the input and then runs the value from the inner parser
|
/// - Returns: A parser that trims leading and trailing whitespace from the input and then runs the value from the inner parser
|
||||||
#[cfg(feature = "nom")]
|
|
||||||
pub fn trim<'a, Parser, R>(inner: Parser) -> impl FnMut(&'a str) -> IResult<&'a str, R>
|
pub fn trim<'a, Parser, R>(inner: Parser) -> impl FnMut(&'a str) -> IResult<&'a str, R>
|
||||||
where
|
where
|
||||||
Parser: Fn(&'a str) -> IResult<&'a str, R>,
|
Parser: Fn(&'a str) -> IResult<&'a str, R>,
|
||||||
@ -29,7 +27,6 @@ where
|
|||||||
/// - Parameters
|
/// - Parameters
|
||||||
/// - `inner`: The parser to run inside the parentheses
|
/// - `inner`: The parser to run inside the parentheses
|
||||||
/// - Returns: A parser that parses a parenthesized expression
|
/// - Returns: A parser that parses a parenthesized expression
|
||||||
#[cfg(feature = "nom")]
|
|
||||||
pub fn parenthesized<'a, Parser, R>(inner: Parser) -> impl FnMut(&'a str) -> IResult<&'a str, R>
|
pub fn parenthesized<'a, Parser, R>(inner: Parser) -> impl FnMut(&'a str) -> IResult<&'a str, R>
|
||||||
where
|
where
|
||||||
Parser: Fn(&'a str) -> IResult<&'a str, R>,
|
Parser: Fn(&'a str) -> IResult<&'a str, R>,
|
||||||
@ -42,7 +39,6 @@ where
|
|||||||
/// - `n`: The length of the string to take
|
/// - `n`: The length of the string to take
|
||||||
/// - `predicate`: The predicate to call to validate the input
|
/// - `predicate`: The predicate to call to validate the input
|
||||||
/// - Returns: A parser that takes `n` characters from the input
|
/// - Returns: A parser that takes `n` characters from the input
|
||||||
#[cfg(feature = "nom")]
|
|
||||||
pub fn take_where<F, Input>(n: usize, predicate: F) -> impl Fn(Input) -> IResult<Input, Input>
|
pub fn take_where<F, Input>(n: usize, predicate: F) -> impl Fn(Input) -> IResult<Input, Input>
|
||||||
where
|
where
|
||||||
Input: InputTake + InputIter + InputLength + Slice<RangeFrom<usize>>,
|
Input: InputTake + InputIter + InputLength + Slice<RangeFrom<usize>>,
|
||||||
@ -51,7 +47,6 @@ where
|
|||||||
take_while_m_n(n, n, predicate)
|
take_while_m_n(n, n, predicate)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "nom")]
|
|
||||||
pub fn exhausted<'a, Parser, R>(inner: Parser) -> impl FnMut(&'a str) -> IResult<&'a str, R>
|
pub fn exhausted<'a, Parser, R>(inner: Parser) -> impl FnMut(&'a str) -> IResult<&'a str, R>
|
||||||
where
|
where
|
||||||
Parser: Fn(&'a str) -> IResult<&'a str, R>,
|
Parser: Fn(&'a str) -> IResult<&'a str, R>,
|
||||||
@ -59,7 +54,7 @@ where
|
|||||||
terminated(inner, eof)
|
terminated(inner, eof)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(all(test, feature = "nom"))]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use nom::bytes::streaming::take_while;
|
use nom::bytes::streaming::take_while;
|
||||||
|
|
||||||
|
@ -1,13 +1,8 @@
|
|||||||
#[cfg(feature = "nom")]
|
use {
|
||||||
use nom::{error::Error, IResult};
|
crate::traits::IntoResult,
|
||||||
|
nom::{error::Error, IResult},
|
||||||
|
};
|
||||||
|
|
||||||
#[cfg(feature = "nom")]
|
|
||||||
pub trait IntoResult<T> {
|
|
||||||
type Error;
|
|
||||||
fn into_result(self) -> Result<T, Self::Error>;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "nom")]
|
|
||||||
impl<T, R> IntoResult<T> for IResult<R, T> {
|
impl<T, R> IntoResult<T> for IResult<R, T> {
|
||||||
type Error = nom::Err<Error<R>>;
|
type Error = nom::Err<Error<R>>;
|
||||||
fn into_result(self) -> Result<T, Self::Error> {
|
fn into_result(self) -> Result<T, Self::Error> {
|
||||||
@ -15,11 +10,12 @@ impl<T, R> IntoResult<T> for IResult<R, T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(all(test, feature = "nom"))]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
|
||||||
use nom::character::complete::char as c;
|
use nom::character::complete::char as c;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
fn parse_char(input: &str) -> IResult<&str, char> {
|
fn parse_char(input: &str) -> IResult<&str, char> {
|
||||||
c('A')(input)
|
c('A')(input)
|
||||||
}
|
}
|
||||||
|
@ -1,15 +1,12 @@
|
|||||||
#[cfg(feature = "serde")]
|
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
|
|
||||||
#[derive(Serialize)]
|
#[derive(Serialize)]
|
||||||
#[cfg(feature = "serde")]
|
|
||||||
pub struct BaseResponse<T: Serialize> {
|
pub struct BaseResponse<T: Serialize> {
|
||||||
pub version: String,
|
pub version: String,
|
||||||
#[serde(flatten)]
|
#[serde(flatten)]
|
||||||
pub body: T, // T must be a struct (or enum?)
|
pub body: T, // T must be a struct (or enum?)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "serde")]
|
|
||||||
impl<T: Serialize> BaseResponse<T> {
|
impl<T: Serialize> BaseResponse<T> {
|
||||||
pub fn new(version: impl Into<String>, body: T) -> Self {
|
pub fn new(version: impl Into<String>, body: T) -> Self {
|
||||||
Self {
|
Self {
|
||||||
@ -19,7 +16,7 @@ impl<T: Serialize> BaseResponse<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(all(test, feature = "serde"))]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
5
src/traits.rs
Normal file
5
src/traits.rs
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
/// Converts a type T into a Result<T, E>
|
||||||
|
pub trait IntoResult<T> {
|
||||||
|
type Error;
|
||||||
|
fn into_result(self) -> Result<T, Self::Error>;
|
||||||
|
}
|
@ -1,9 +1,7 @@
|
|||||||
#[cfg(feature = "vec")]
|
|
||||||
pub trait Distinct {
|
pub trait Distinct {
|
||||||
fn distinct(&mut self);
|
fn distinct(&mut self);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "vec")]
|
|
||||||
impl<T: PartialEq + Clone> Distinct for Vec<T> {
|
impl<T: PartialEq + Clone> Distinct for Vec<T> {
|
||||||
fn distinct(&mut self) {
|
fn distinct(&mut self) {
|
||||||
*self = self.iter().fold(vec![], |mut acc, x| {
|
*self = self.iter().fold(vec![], |mut acc, x| {
|
||||||
@ -15,7 +13,7 @@ impl<T: PartialEq + Clone> Distinct for Vec<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(all(test, feature = "vec"))]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
#[macro_export]
|
#[macro_export]
|
||||||
#[cfg(feature = "vec")]
|
|
||||||
macro_rules! map {
|
macro_rules! map {
|
||||||
() => { std::collections::HashMap::new() };
|
() => { std::collections::HashMap::new() };
|
||||||
($($k:expr => $v:expr),* $(,)?) => {
|
($($k:expr => $v:expr),* $(,)?) => {
|
||||||
@ -13,7 +12,7 @@ macro_rules! map {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(all(test, feature = "vec"))]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
#[macro_export]
|
#[macro_export]
|
||||||
#[cfg(feature = "vec")]
|
|
||||||
macro_rules! matrix {
|
macro_rules! matrix {
|
||||||
($x:expr; $m:expr, $n:expr) => {
|
($x:expr; $m:expr, $n:expr) => {
|
||||||
vec![vec![$x; $n]; $m]
|
vec![vec![$x; $n]; $m]
|
||||||
@ -16,7 +15,7 @@ macro_rules! matrix {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(all(test, feature = "vec"))]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
#[macro_export]
|
#[macro_export]
|
||||||
#[cfg(feature = "vec")]
|
|
||||||
macro_rules! set {
|
macro_rules! set {
|
||||||
() => { std::collections::HashSet::new() };
|
() => { std::collections::HashSet::new() };
|
||||||
($($x:expr),* $(,)?) => {
|
($($x:expr),* $(,)?) => {
|
||||||
@ -13,7 +12,7 @@ macro_rules! set {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(all(test, feature = "vec"))]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user