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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
use crate::rust::vec::Vec;
use crate::io;
use super::{Deserialize, Serialize, Error, VarUint32, CountedList, InitExpr, CountedListWriter};

#[cfg(feature="bulk")]
const FLAG_MEMZERO: u32 = 0;
#[cfg(feature="bulk")]
const FLAG_PASSIVE: u32 = 1;
#[cfg(feature="bulk")]
const FLAG_MEM_NONZERO: u32 = 2;

/// Entry in the element section.
#[derive(Debug, Clone, PartialEq)]
pub struct ElementSegment {
	index: u32,
	offset: Option<InitExpr>,
	members: Vec<u32>,

	#[cfg(feature="bulk")]
	passive: bool,
}

impl ElementSegment {
	/// New element segment.
	pub fn new(index: u32, offset: Option<InitExpr>, members: Vec<u32>) -> Self {
		ElementSegment {
			index: index,
			offset: offset,
			members: members,

			#[cfg(feature="bulk")]
			passive: false,
		}
	}

	/// Sequence of function indices.
	pub fn members(&self) -> &[u32] { &self.members }

	/// Sequence of function indices (mutable)
	pub fn members_mut(&mut self) -> &mut Vec<u32> { &mut self.members }

	/// Table index (currently valid only value of `0`)
	pub fn index(&self) -> u32 { self.index }

	/// An i32 initializer expression that computes the offset at which to place the elements.
	///
	/// Note that this return `None` if the segment is `passive`.
	pub fn offset(&self) -> &Option<InitExpr> { &self.offset }

	/// An i32 initializer expression that computes the offset at which to place the elements (mutable)
	///
	/// Note that this return `None` if the segment is `passive`.
	pub fn offset_mut(&mut self) -> &mut Option<InitExpr> { &mut self.offset }
}

#[cfg(feature="bulk")]
impl ElementSegment {
	/// Whether or not this table segment is "passive"
	pub fn passive(&self) -> bool { self.passive }

	/// Whether or not this table segment is "passive"
	pub fn passive_mut(&mut self) -> &mut bool { &mut self.passive }

	/// Set whether or not this table segment is "passive"
	pub fn set_passive(&mut self, passive: bool) {
		self.passive = passive;
	}
}

impl Deserialize for ElementSegment {
	type Error = Error;

	#[cfg(not(feature="bulk"))]
	fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> {
		let index: u32 = VarUint32::deserialize(reader)?.into();
		let offset = InitExpr::deserialize(reader)?;
		let members: Vec<u32> = CountedList::<VarUint32>::deserialize(reader)?
			.into_inner()
			.into_iter()
			.map(Into::into)
			.collect();

		Ok(ElementSegment {
			index,
			offset: Some(offset),
			members,
		})
	}

	#[cfg(feature="bulk")]
	fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> {
		// This piece of data was treated as `index` [of the table], but was repurposed
		// for flags in bulk-memory operations proposal.
		let flags: u32 = VarUint32::deserialize(reader)?.into();
		let index = if flags == FLAG_MEMZERO || flags == FLAG_PASSIVE {
			0u32
		} else if flags == FLAG_MEM_NONZERO {
			VarUint32::deserialize(reader)?.into()
		} else {
			return Err(Error::InvalidSegmentFlags(flags))
		};
		let offset = if flags == FLAG_PASSIVE {
			None
		} else {
			Some(InitExpr::deserialize(reader)?)
		};

		let funcs: Vec<u32> = CountedList::<VarUint32>::deserialize(reader)?
			.into_inner()
			.into_iter()
			.map(Into::into)
			.collect();

		Ok(ElementSegment {
			index: index,
			offset: offset,
			members: funcs,
			passive: flags == FLAG_PASSIVE,
		})
	}
}

impl Serialize for ElementSegment {
	type Error = Error;

	fn serialize<W: io::Write>(self, writer: &mut W) -> Result<(), Self::Error> {
		#[cfg(feature="bulk")]
		{
			if self.passive {
				VarUint32::from(FLAG_PASSIVE).serialize(writer)?;
			} else if self.index != 0 {
				VarUint32::from(FLAG_MEM_NONZERO).serialize(writer)?;
				VarUint32::from(self.index).serialize(writer)?;
			} else {
				VarUint32::from(FLAG_MEMZERO).serialize(writer)?;
			}
		}
		#[cfg(not(feature="bulk"))]
		VarUint32::from(self.index).serialize(writer)?;

		if let Some(offset) = self.offset {
			offset.serialize(writer)?;
		}
		let data = self.members;
		let counted_list = CountedListWriter::<VarUint32, _>(
			data.len(),
			data.into_iter().map(Into::into),
		);
		counted_list.serialize(writer)?;
		Ok(())
	}
}

/// Data segment definition.
#[derive(Clone, Debug, PartialEq)]
pub struct DataSegment {
	index: u32,
	offset: Option<InitExpr>,
	value: Vec<u8>,

	#[cfg(feature="bulk")]
	passive: bool,
}

impl DataSegment {
	/// New data segments.
	pub fn new(index: u32, offset: Option<InitExpr>, value: Vec<u8>) -> Self {
		DataSegment {
			index: index,
			offset: offset,
			value: value,

			#[cfg(feature="bulk")]
			passive: false,
		}
	}

	/// Linear memory index (currently the only valid value is `0`).
	pub fn index(&self) -> u32 { self.index }

	/// An i32 initializer expression that computes the offset at which to place the data.
	///
	/// Note that this return `None` if the segment is `passive`.
	pub fn offset(&self) -> &Option<InitExpr> { &self.offset }

	/// An i32 initializer expression that computes the offset at which to place the data (mutable)
	///
	/// Note that this return `None` if the segment is `passive`.
	pub fn offset_mut(&mut self) -> &mut Option<InitExpr> { &mut self.offset }

	/// Initial value of the data segment.
	pub fn value(&self) -> &[u8] { &self.value }

	/// Initial value of the data segment (mutable).
	pub fn value_mut(&mut self) -> &mut Vec<u8> { &mut self.value }
}

#[cfg(feature="bulk")]
impl DataSegment {
	/// Whether or not this data segment is "passive".
	pub fn passive(&self) -> bool { self.passive }

	/// Whether or not this data segment is "passive" (mutable).
	pub fn passive_mut(&mut self) -> &mut bool { &mut self.passive }

	/// Set whether or not this table segment is "passive"
	pub fn set_passive(&mut self, passive: bool) {
		self.passive = passive;
	}
}

impl Deserialize for DataSegment {
	type Error = Error;

	#[cfg(not(feature="bulk"))]
	fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> {
		let index = VarUint32::deserialize(reader)?;
		let offset = InitExpr::deserialize(reader)?;
		let value_len = u32::from(VarUint32::deserialize(reader)?) as usize;
		let value_buf = buffered_read!(65536, value_len, reader);

		Ok(DataSegment {
			index: index.into(),
			offset: Some(offset),
			value: value_buf,
		})
	}

	#[cfg(feature="bulk")]
	fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> {
		let flags: u32 = VarUint32::deserialize(reader)?.into();
		let index = if flags == FLAG_MEMZERO || flags == FLAG_PASSIVE {
			0u32
		} else if flags == FLAG_MEM_NONZERO {
			VarUint32::deserialize(reader)?.into()
		} else {
			return Err(Error::InvalidSegmentFlags(flags))
		};
		let offset = if flags == FLAG_PASSIVE {
			None
		} else {
			Some(InitExpr::deserialize(reader)?)
		};
		let value_len = u32::from(VarUint32::deserialize(reader)?) as usize;
		let value_buf = buffered_read!(65536, value_len, reader);

		Ok(DataSegment {
			index: index,
			offset: offset,
			value: value_buf,
			passive: flags == FLAG_PASSIVE,
		})
	}
}

impl Serialize for DataSegment {
	type Error = Error;

	fn serialize<W: io::Write>(self, writer: &mut W) -> Result<(), Self::Error> {
		#[cfg(feature="bulk")]
		{
			if self.passive {
				VarUint32::from(FLAG_PASSIVE).serialize(writer)?;
			} else if self.index != 0 {
				VarUint32::from(FLAG_MEM_NONZERO).serialize(writer)?;
				VarUint32::from(self.index).serialize(writer)?;
			} else {
				VarUint32::from(FLAG_MEMZERO).serialize(writer)?;
			}
		}
		#[cfg(not(feature="bulk"))]
		VarUint32::from(self.index).serialize(writer)?;

		if let Some(offset) = self.offset {
			offset.serialize(writer)?;
		}

		let value = self.value;
		VarUint32::from(value.len()).serialize(writer)?;
		writer.write(&value[..])?;
		Ok(())
	}
}