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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
use crate::map_decoder;
use core::num::NonZeroU32;
use minicbor::decode::{Decode, Decoder, Error};

/// Information about a fluid.
///
/// The `'buffer` lifetime is the lifetime of the buffer holding strings to which the object
/// refers.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Fluid<'buffer> {
	/// The internal (Minecraft system) name of the item.
	///
	/// For example, this might be `water`.
	pub name: &'buffer str,

	/// The human-readable name of the item.
	///
	/// For example, this might be `Water`.
	pub label: &'buffer str,

	/// The number of millibuckets of fluid in the container.
	pub amount: NonZeroU32,

	/// Whether the fluid has extra NBT data attached.
	pub has_tag: bool,
}

impl<'buffer> Decode<'buffer> for Fluid<'buffer> {
	fn decode(d: &mut Decoder<'buffer>) -> Result<Self, Error> {
		match OptionFluid::decode(d)?.into() {
			Some(f) => Ok(f),
			None => Err(Error::message("missing fluid")),
		}
	}
}

/// Information about a fluid which may or may not exist.
///
/// This type exists, rather than just using `Option<Fluid>` directly, because `Option` has a
/// blanket `Decode` implementation, and we need a different implementation which also maps a
/// non-null empty map to `None`.
///
/// The `'buffer` lifetime is the lifetime of the buffer holding strings to which the object
/// refers.
#[allow(clippy::module_name_repetitions)]
#[derive(Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[repr(transparent)]
pub struct OptionFluid<'buffer>(pub Option<Fluid<'buffer>>);

impl<'buffer> Decode<'buffer> for OptionFluid<'buffer> {
	fn decode(d: &mut Decoder<'buffer>) -> Result<Self, Error> {
		map_decoder::decode_nullable::<OptionFluidBuilder<'buffer>>(d)
	}
}

impl<'buffer> From<OptionFluid<'buffer>> for Option<Fluid<'buffer>> {
	fn from(x: OptionFluid<'buffer>) -> Option<Fluid<'buffer>> {
		x.0
	}
}

/// A map-decoding builder for an [`OptionFluid`](OptionFluid).
#[derive(Clone, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct OptionFluidBuilder<'buffer> {
	/// The internal (Minecraft system) name of the item.
	///
	/// For example, this might be `water`.
	name: Option<&'buffer str>,

	/// The human-readable name of the item.
	///
	/// For example, this might be `Water`.
	label: Option<&'buffer str>,

	/// The number of millibuckets of fluid in the container.
	amount: Option<u32>,

	/// Whether the fluid has extra NBT data attached.
	has_tag: Option<bool>,
}

impl<'buffer> map_decoder::Builder<'buffer> for OptionFluidBuilder<'buffer> {
	type Output = OptionFluid<'buffer>;

	fn entry(&mut self, key: &str, d: &mut Decoder<'buffer>) -> Result<bool, Error> {
		match key {
			"name" => {
				self.name = Some(d.str()?);
				Ok(true)
			}
			"label" => {
				self.label = Some(d.str()?);
				Ok(true)
			}
			"amount" => {
				self.amount = Some(d.u32()?);
				Ok(true)
			}
			"hasTag" => {
				self.has_tag = Some(d.bool()?);
				Ok(true)
			}
			_ => Ok(false),
		}
	}

	fn build(self) -> Result<Self::Output, Error> {
		// If all the required keys are present, and the amount is nonzero, return a fluid.
		if let Some(name) = self.name {
			if let Some(label) = self.label {
				if let Some(amount) = self.amount {
					if let Some(amount) = NonZeroU32::new(amount) {
						if let Some(has_tag) = self.has_tag {
							return Ok(OptionFluid(Some(Fluid {
								name,
								label,
								amount,
								has_tag,
							})));
						}
					}
				}
			}
		}

		// If all the required keys are absent, return None.
		if (self.name, self.label, self.amount, self.has_tag) == (None, None, None, None) {
			return Ok(OptionFluid(None));
		}

		// If the amount is present but zero, return None.
		if self.amount == Some(0) {
			return Ok(OptionFluid(None));
		}

		// If some but not all of the required keys are present, fail.
		Err(minicbor::decode::Error::message("missing key in fluid"))
	}
}

impl<'buffer> map_decoder::NullableBuilder<'buffer> for OptionFluidBuilder<'buffer> {
	fn build_null() -> OptionFluid<'buffer> {
		OptionFluid(None)
	}
}

/// Information about a fluid tank.
///
/// The `'buffer` lifetime is the lifetime of the buffer holding strings to which the object
/// refers.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Tank<'buffer> {
	/// The fluid contained in the tank, if any.
	pub fluid: Option<Fluid<'buffer>>,

	/// The maximum number of millibuckets the tank can hold.
	pub capacity: u32,
}

impl<'buffer> Decode<'buffer> for Tank<'buffer> {
	fn decode(d: &mut Decoder<'buffer>) -> Result<Self, Error> {
		map_decoder::decode::<TankBuilder<'buffer>>(d)
	}
}

/// A map-decoding builder for a [`Tank`](Tank).
#[derive(Clone, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct TankBuilder<'buffer> {
	/// The fluid.
	fluid: OptionFluidBuilder<'buffer>,

	/// The maximum number of millibuckets the tank can hold.
	capacity: Option<u32>,
}

impl<'buffer> map_decoder::Builder<'buffer> for TankBuilder<'buffer> {
	type Output = Tank<'buffer>;

	fn entry(&mut self, key: &'buffer str, d: &mut Decoder<'buffer>) -> Result<bool, Error> {
		match key {
			"capacity" => {
				self.capacity = Some(d.u32()?);
				Ok(true)
			}
			_ => self.fluid.entry(key, d),
		}
	}

	fn build(self) -> Result<Self::Output, Error> {
		if let Some(capacity) = self.capacity {
			// The capacity is present. The fluid may or may not be; that’s fine, because the tank
			// might be empty.
			Ok(Tank {
				fluid: self.fluid.build()?.into(),
				capacity,
			})
		} else {
			// The capacity is absent, which should not happen.
			Err(Error::message("missing key in tank"))
		}
	}
}