use json_minimal::*;
pub fn parse_intent(line: &[u8]) -> (String, f64) {
let json = match Json::parse(line) {
Ok(json) => {
json
},
Err( (position,message) ) => {
panic!("Error on {} at position {}!!!",message, position);
}
};
let search = "intent";
let intent_json = match json.get(search) {
Some(a) => a,
None => panic!("intent not found in the provided json string"),
};
let intent_name =
match intent_json.unbox() {
Json::OBJECT {name: _, value} =>
match value.unbox() {
Json::JSON(values) => {
assert_eq!(values.len(),2);
match &values[0] {
Json::OBJECT {name: _, value} => {
value.unbox()
},
json => {
panic!("Couldn't parse the intent's name, found {:?}!!!",json);
}
}
},
json => {
panic!("Couldn't parse the intent's name, found {:?}!!!",json)
}
}
_ => panic!("Couldn't parse the intent's name, found {:?}!!!",json)
};
let intent_confidence =
match intent_json.unbox() {
Json::OBJECT {name: _, value} =>
match value.unbox() {
Json::JSON(values) => {
match &values[1] {
Json::OBJECT { name: _ , value } => {
value.unbox()
},
json => {
panic!("Couldn't parse the intent's confidence, found {:?}!!!",json);
}
}
},
json => {
panic!("Couldn't parse the intent's confidence, found {:?}!!!",json)
}
}
_ => panic!("Couldn't parse the intent's confidence, found {:?}!!!",json)
};
let intent_name = match intent_name {
Json::STRING(val) => val,
_ => panic!("The intent's name wasn't a string")
};
let intent_confidence = match intent_confidence {
Json::NUMBER(val) => val,
_ => panic!("The intent's confidence wasn't a number")
};
(intent_name.to_string(), *intent_confidence) }
#[cfg(test)]
mod tests {
#[test]
fn test_message_passing() {
use std::io::prelude::*;
use std::net::{TcpListener, TcpStream};
use std::{thread,time};
let thread = thread::spawn(|| {
let listener = TcpListener::bind("127.0.0.1:50000").unwrap();
for stream in listener.incoming().take(1) {
let mut cosa : String = "".to_string();
stream.unwrap()
.read_to_string(&mut cosa).unwrap();
println!("Got: {}", cosa);
assert_eq!(cosa, "hi_bmo,2.5".to_string());
}
});
thread::sleep(time::Duration::from_secs(3));
let mut stream = TcpStream::connect("127.0.0.1:50000").unwrap();
let (name, conf) = ("hi_bmo", 2.5);
stream.write(format!("[{},{}]", name, conf).as_bytes()).unwrap();
println!("wrote to stream");
thread.join().unwrap();
}
}