Skip to main content

gorrosion_gtp/data/
string.rs

1use super::super::messages::WriteGTP;
2use super::*;
3use std::io;
4use std::str::FromStr;
5
6type Byte = u8;
7
8#[derive(Clone, Debug, PartialEq, Eq)]
9pub struct Value {
10	data: Vec<Byte>,
11}
12
13impl From<Value> for Vec<Byte> {
14	fn from(v: Value) -> Vec<Byte> {
15		v.data
16	}
17}
18
19impl WriteGTP for Value {
20	fn write_gtp(&self, f: &mut impl io::Write) -> io::Result<()> {
21		f.write_all(&self.data)
22	}
23}
24
25impl FromStr for Value {
26	// TODO: Better error type
27	type Err = ();
28
29	fn from_str(s: &str) -> Result<Value, Self::Err> {
30		#[allow(clippy::trivially_copy_pass_by_ref)]
31		fn bad_byte(b: &Byte) -> bool {
32			(*b > 32) && (*b != 127)
33		}
34
35		let b = s.as_bytes();
36		if b.iter().any(bad_byte) {
37			Err(())
38		} else {
39			let data = b.to_vec();
40			Ok(Value { data })
41		}
42	}
43}
44
45singleton_type!(String, "string");
46
47impl HasType<Type> for Value {
48	fn has_type(&self, _t: &Type) -> bool {
49		true
50	}
51}
52
53impl Data for Value {
54	type Type = Type;
55
56	fn parse<'a, I: Input<'a>>(i: I, _t: &Self::Type) -> IResult<I, Self> {
57		let result = take_until_either!(i, b" \n");
58		match result {
59			Ok((rem, data)) => {
60				let data = data.iter_elements().collect();
61				Ok((rem, Value { data }))
62			}
63			Err(e) => Err(e),
64		}
65	}
66}