Advertisement
Guest User

Untitled

a guest
Mar 10th, 2024
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 2.09 KB | None | 0 0
  1. use std::collections::HashMap;
  2. use winnow::combinator::alt;
  3. use winnow::combinator::cut_err;
  4. use winnow::combinator::preceded;
  5. use winnow::combinator::separated;
  6. use winnow::combinator::separated_pair;
  7.  
  8. use winnow::combinator::delimited;
  9. use winnow::combinator::terminated;
  10. use winnow::stream::AsChar;
  11. use winnow::token::take_while;
  12.  
  13. use winnow::{PResult, Parser};
  14.  
  15. struct Object {
  16.     elements: HashMap<String, Value>,
  17. }
  18.  
  19. enum Value {
  20.     Str(String),
  21.     Array(Vec<Value>),
  22.     Object(HashMap<String, Value>),
  23. }
  24.  
  25. fn value<'s>(input: &mut &'s str) -> PResult<Value> {
  26.     alt((string.map(Value::Str),
  27.     array.map(Value::Object),
  28.         object.map(Value:Object),
  29.     )).parse_next(input)
  30. }
  31.  
  32. fn array<'s>(input: &mut &'s str) -> PResult<Vec<Value>> {
  33.   preceded(
  34.         ('[', ws),
  35.         cut_err(terminated(
  36.             separated(0.., value, ws),
  37.             (ws, ']'),
  38.         )),
  39.     )
  40.     .context("array")
  41.     .parse_next(input)
  42. }
  43.  
  44. fn object<'s>(input: &mut &'s str) -> PResult<HashMap<String,Value>> {
  45.  preceded(
  46.         ('{', ws),
  47.         cut_err(terminated(
  48.             separated(0.., value, ws),
  49.             (ws, '}'),
  50.         )),
  51.     )
  52.     .context("object")
  53.     .parse_next(input)
  54. }
  55.  
  56. fn string<'s>(input: &mut &'s str) -> PResult<&'s str> {
  57.    delimited(ws, alphanum_1, ws).parse_next(input)
  58. }
  59.  
  60. fn alphanum_1<'s>(input: &mut &'s str) -> PResult<&'s str> {
  61.     // one_of(('0'..='9', 'a'..='f', 'A'..='F')).parse_next(input)
  62.     take_while(1.., (AsChar::is_alphanum, is_underscore)).parse_next(input)
  63. }
  64.  
  65. fn is_underscore(c: char) -> bool {
  66.     c == '_'
  67. }
  68.  
  69. fn ws<'s>(input: &mut &'s str) -> PResult<&'s str> {
  70.    take_while(0.., &[' ', '\t', '\r', '\n', ',', ':', '=']).parse_next(input)
  71. }
  72.  
  73. fn key_value<'s>(input: &mut &'s str) -> PResult<(String, Value)> {
  74.    separated_pair(string, cut_err(ws), value).parse_next(input)
  75. }
  76.  
  77. fn main() {
  78.    let mut ex1 = "   whirly_widgets 10
  79.    twirly_widgets 15
  80.    girly_widgets 4
  81.    burly_widgets 1
  82. ";
  83.  
  84.    let output = string.parse_next(&mut ex1).unwrap();
  85.    println!("parsed: {}", output);
  86. }
  87.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement