Skip to content

Commit 1916e25

Browse files
committed
feat: create initial nom parser
1 parent c2d6986 commit 1916e25

File tree

2 files changed

+76
-9
lines changed

2 files changed

+76
-9
lines changed

Cargo.toml

+2-3
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
[package]
2-
name = "grid-url"
2+
name = "surf"
33
version = "0.1.0"
44
edition = "2021"
55

6-
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7-
86
[dependencies]
7+
nom = "7.1.3"

src/lib.rs

+74-6
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,82 @@
1-
pub fn add(left: usize, right: usize) -> usize {
2-
left + right
1+
use nom::{
2+
bytes::complete::{tag, take_while},
3+
character::is_alphanumeric,
4+
combinator::map,
5+
multi::separated_list0,
6+
IResult,
7+
};
8+
use std::collections::HashMap;
9+
10+
#[derive(Debug, PartialEq, Eq)]
11+
pub struct Surf<'a> {
12+
host: &'a str,
13+
path: Vec<&'a str>,
14+
query: HashMap<&'a str, &'a str>,
15+
fragment: Option<&'a str>,
16+
}
17+
18+
fn is_letter(c: char) -> bool {
19+
is_alphanumeric(c as u8)
20+
}
21+
22+
fn is_letter_or_dot(c: char) -> bool {
23+
is_alphanumeric(c as u8) || c == '.'
24+
}
25+
26+
pub fn parse_surf<'a>(input: &'a str) -> IResult<&'a str, Surf<'a>> {
27+
let (input, _) = tag("grid!")(input)?;
28+
let (input, host) = take_while(is_letter_or_dot)(input)?;
29+
let (input, path) = map(
30+
separated_list0(tag("/"), take_while(is_letter)),
31+
|mut list| {
32+
list.remove(0);
33+
list
34+
},
35+
)(input)?;
36+
37+
Ok((
38+
input,
39+
Surf {
40+
host,
41+
path,
42+
query: HashMap::default(),
43+
fragment: None,
44+
},
45+
))
346
}
447

548
#[cfg(test)]
649
mod tests {
7-
use super::*;
50+
use super::{parse_surf, Surf};
51+
use std::collections::HashMap;
52+
53+
#[test]
54+
fn simple_surf() {
55+
let (_, surf) = parse_surf("grid!example.com").unwrap();
56+
57+
assert_eq!(
58+
surf,
59+
Surf {
60+
host: "example.com",
61+
path: Vec::default(),
62+
query: HashMap::default(),
63+
fragment: None,
64+
}
65+
);
66+
}
867

968
#[test]
10-
fn it_works() {
11-
let result = add(2, 2);
12-
assert_eq!(result, 4);
69+
fn parse_path() {
70+
let (_, surf) = parse_surf("grid!example.com/with/a/path").unwrap();
71+
72+
assert_eq!(
73+
surf,
74+
Surf {
75+
host: "example.com",
76+
path: ["with", "a", "path"].into(),
77+
query: HashMap::default(),
78+
fragment: None,
79+
}
80+
);
1381
}
1482
}

0 commit comments

Comments
 (0)