From 7e8ee5ed9cad6484e9f13f81731b102ced58402e Mon Sep 17 00:00:00 2001 From: Adam Carpenter Date: Tue, 9 Jul 2019 15:14:04 -0400 Subject: Init. --- meap/meap-code/ch3/ch3-parse-log.rs | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100755 meap/meap-code/ch3/ch3-parse-log.rs (limited to 'meap/meap-code/ch3/ch3-parse-log.rs') diff --git a/meap/meap-code/ch3/ch3-parse-log.rs b/meap/meap-code/ch3/ch3-parse-log.rs new file mode 100755 index 0000000..b675aa1 --- /dev/null +++ b/meap/meap-code/ch3/ch3-parse-log.rs @@ -0,0 +1,35 @@ +#[derive(Debug)] // <1> Enable this enum to be printed to the screen via auto-generated code +enum Event { + Update, // <2> Create three variants of Event, including one value for unrecognized events + Delete, // <2> + Unknown, // <2> +} + +type Message = String; // <3> A convenient name for String for use in this crate's context + +fn parse_log(line: &'static str) -> (Event, Message) { // <4> A function for parsing a line and converting it into semi-structured data + let parts: Vec<&str> = line.splitn(2, ' ').collect(); // <5> `collect()` consumes an iterator (returned from `line.splitn()`) and returns `Vec` + if parts.len() == 1 { // <6> If `line.splitn()` didn't split `log` into two parts, return an error + return (Event::Unknown, String::from(line)) + } + + let event = parts[0]; // <7> Assign each part to a variable for ease of future use + let rest = String::from(parts[1]); // <7> + + match event { + "UPDATE" | "update" => (Event::Update, rest), // <8> When we match a known event, return structured data + "DELETE" | "delete" => (Event::Delete, rest), // <8> + _ => (Event::Unknown, String::from(line)), // <9> If we don't recognize the event type, return the whole line + } +} + +fn main() { + let log = "BEGIN Transaction XK342 +UPDATE 234:LS/32231 {\"price\": 31.00} -> {\"price\": 40.00} +DELETE 342:LO/22111"; + + for line in log.lines(){ + let parse_result = parse_log(line); + println!("{:?}", parse_result); + } +} \ No newline at end of file -- cgit v1.2.3