Skip to main content

gorrosion_gtp/data/
int.rs

1use super::super::messages::WriteGTP;
2use super::*;
3use std::convert::TryFrom;
4use std::io;
5
6#[derive(Clone, Debug, PartialEq, Eq)]
7pub struct Value {
8	data: u32,
9}
10
11#[derive(Debug)]
12pub struct TryFromIntError(());
13
14impl TryFrom<u32> for Value {
15	type Error = TryFromIntError;
16
17	fn try_from(data: u32) -> Result<Self, Self::Error> {
18		if data < (1 << 31) {
19			Ok(Value { data })
20		} else {
21			Err(TryFromIntError(()))
22		}
23	}
24}
25
26impl From<Value> for u32 {
27	fn from(v: Value) -> u32 {
28		v.data
29	}
30}
31
32impl From<Value> for i32 {
33	fn from(v: Value) -> i32 {
34		// This should be safe to unwrap
35		// as we should not instantiate
36		// a Value with data >= 2^31
37		// in the first place.
38		i32::try_from(v.data).unwrap()
39	}
40}
41
42impl WriteGTP for Value {
43	fn write_gtp(&self, f: &mut impl io::Write) -> io::Result<()> {
44		write!(f, "{}", self.data)
45	}
46}
47
48singleton_type!(Int, "int");
49
50impl HasType<Type> for Value {
51	fn has_type(&self, _t: &Type) -> bool {
52		true
53	}
54}
55
56impl Data for Value {
57	type Type = Type;
58
59	fn parse<'a, I: Input<'a>>(i: I, _t: &Self::Type) -> IResult<I, Self> {
60		flat_map!(i, nom::digit, parse_to!(Self))
61	}
62}