1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//! jsonrpc version field
use serde::de::{self, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use std::fmt;

/// Protocol Version
#[derive(Debug, PartialEq, Clone, Copy, Hash, Eq)]
pub enum Version {
	/// JSONRPC 2.0
	V2,
}

impl Serialize for Version {
	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
	where
		S: Serializer,
	{
		match *self {
			Version::V2 => serializer.serialize_str("2.0"),
		}
	}
}

impl<'a> Deserialize<'a> for Version {
	fn deserialize<D>(deserializer: D) -> Result<Version, D::Error>
	where
		D: Deserializer<'a>,
	{
		deserializer.deserialize_identifier(VersionVisitor)
	}
}

struct VersionVisitor;

impl<'a> Visitor<'a> for VersionVisitor {
	type Value = Version;

	fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
		formatter.write_str("a string")
	}

	fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
	where
		E: de::Error,
	{
		match value {
			"2.0" => Ok(Version::V2),
			_ => Err(de::Error::custom("invalid version")),
		}
	}
}