flatdata/vector.rs
1use crate::{
2 error::ResourceStorageError,
3 structs::{NoOverlap, Overlap, Struct},
4 SliceExt,
5};
6
7use crate::storage::ResourceHandle;
8
9use std::{borrow::BorrowMut, fmt, io, slice::SliceIndex};
10
11/// A container holding a contiguous sequence of flatdata structs of the same
12/// type `T` in memory, and providing read and write access to it.
13///
14/// Vector data is fully stored and populated in memory before it is
15/// serialized. This container is often used for data which needs to be changed
16/// or updated after insertion in the container. When data can be incrementally
17/// serialized without later updates, [`ExternalVector`] is usually a
18/// better choice since it may decrease the memory footprint of serialization
19/// significantly.
20///
21/// An archive builder provides a setter for each vector resource. Use
22/// [`as_view`] and the corresponding setter to write a `Vector` to storage.
23///
24/// # Examples
25/// ``` flatdata
26/// struct A {
27/// x : u32 : 16;
28/// y : u32 : 16;
29/// }
30///
31/// archive X {
32/// data : vector< A >;
33/// }
34/// ```
35///
36/// ```
37/// use flatdata::{ MemoryResourceStorage, Vector };
38/// use flatdata::test::{A, X, XBuilder};
39///
40/// let storage = MemoryResourceStorage::new("/root/extvec");
41/// let builder = XBuilder::new(storage.clone()).expect("failed to create builder");
42/// let mut v: Vector<A> = Vector::new();
43/// let mut a = v.grow();
44/// a.set_x(1);
45/// a.set_y(2);
46///
47/// let mut b = v.grow();
48/// b.set_x(3);
49/// b.set_y(4);
50///
51/// assert_eq!(v.len(), 2);
52/// builder.set_data(&v.as_view());
53///
54/// let archive = X::open(storage).expect("failed to open");
55/// let view = archive.data();
56/// assert_eq!(view[1].x(), 3);
57/// ```
58///
59/// [`ExternalVector`]: struct.ExternalVector.html
60/// [`as_view`]: #method.as_view
61pub struct Vector<T>
62where
63 T: Struct,
64{
65 data: Vec<T>,
66}
67
68impl<T> Vector<T>
69where
70 T: Struct,
71{
72 /// Creates an empty `Vector<T>`.
73 #[inline]
74 pub fn new() -> Self {
75 Self::with_len(0)
76 }
77
78 /// Resets the 'Vector<T>' to its initial empty state.
79 #[inline]
80 pub fn clear(&mut self) {
81 self.data.clear();
82 self.data.push(unsafe { T::create_unchecked() });
83 }
84
85 /// Creates a `Vector<T>` with `len` many elements.
86 ///
87 /// `T`'s fields are all filled with zeroes.
88 #[inline]
89 pub fn with_len(len: usize) -> Self {
90 let mut data = Vec::with_capacity(len + 1);
91 data.resize_with(len + 1, || unsafe { T::create_unchecked() });
92 Self { data }
93 }
94
95 /// Reserves capacity for at least `additional` more elements to be
96 /// inserted in the given vector. The collection may reserve more space
97 /// to avoid frequent reallocations. After calling reserve, capacity
98 /// will be greater than or equal to `self.len() + additional`. Does nothing
99 /// if capacity is already sufficient.
100 #[inline]
101 pub fn reserve(&mut self, additional: usize) {
102 self.data.reserve(self.data.len() + additional)
103 }
104
105 /// Returns a slice for the vector contents.
106 ///
107 /// Hides sentinels in case T IS_OVERLAPPING_WITH_NEXT,
108 /// i.e. a vector of size 4 get's converted into a slice of size 3
109 #[inline]
110 pub fn as_view(&self) -> &[T] {
111 if T::IS_OVERLAPPING_WITH_NEXT {
112 &self.data[0..self.data.len().saturating_sub(2)]
113 } else {
114 &self.data[0..self.data.len() - 1]
115 }
116 }
117
118 /// Appends an element to the end of this vector and returns a mutable
119 /// handle to it.
120 #[inline]
121 pub fn grow(&mut self) -> &mut T {
122 let next = self.len();
123 self.data.push(unsafe { T::create_unchecked() });
124 &mut self.data[next]
125 }
126}
127
128impl<T> std::ops::Deref for Vector<T>
129where
130 T: Struct,
131{
132 type Target = [T];
133
134 fn deref(&self) -> &[T] {
135 let len = self.data.len() - 1;
136 &self.data[0..len]
137 }
138}
139
140/// Safety: We must not implement DerefMut if T is not NoOverlap,
141/// since it would allow getting a mutable refernce to one element,
142/// and refernece to the next: Both use the same memory address for data of ranges
143impl<T> std::ops::DerefMut for Vector<T>
144where
145 T: Struct + NoOverlap,
146{
147 fn deref_mut(&mut self) -> &mut [T] {
148 let len = self.data.len() - 1;
149 &mut self.data[0..len]
150 }
151}
152
153impl<T, Idx> std::ops::Index<Idx> for Vector<T>
154where
155 T: Struct + Overlap,
156 Idx: SliceIndex<[T]>,
157{
158 type Output = Idx::Output;
159 fn index(&self, index: Idx) -> &Idx::Output {
160 &self.data[index]
161 }
162}
163
164/// Manually implement IndexMut, since DerefMut is not always implemented
165/// Safety: We must not implement IndexMut for ranges if T is not NoOverlap
166impl<T> std::ops::IndexMut<usize> for Vector<T>
167where
168 T: Struct + Overlap,
169{
170 fn index_mut(&mut self, index: usize) -> &mut T {
171 &mut self.data[index]
172 }
173}
174
175impl<T> Default for Vector<T>
176where
177 T: Struct,
178{
179 /// Creates an empty `Vector<T>`.
180 fn default() -> Self {
181 Vector::new()
182 }
183}
184
185impl<T> fmt::Debug for Vector<T>
186where
187 T: Struct + std::fmt::Debug,
188{
189 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
190 self.as_view().fmt(f)
191 }
192}
193
194/// Vector which flushes its content when growing.
195///
196/// Useful for serialization of data which does not fully fit in memory.
197///
198/// External vector does not provide access to elements previously added to it.
199/// Only the last element added to the vector using the result of the method
200/// [`grow`] can be accessed and written.
201///
202/// An external vector *must* be closed, after the last element was written to
203/// it. After closing, it can not be used anymore.
204///
205/// # Examples
206/// ``` flatdata
207/// struct A {
208/// x : u32 : 16;
209/// y : u32 : 16;
210/// }
211///
212/// archive X {
213/// data : vector< A >;
214/// }
215/// ```
216///
217/// ```
218/// use flatdata::MemoryResourceStorage;
219/// use flatdata::test::{A, X, XBuilder};
220///
221/// let storage = MemoryResourceStorage::new("/root/extvec");
222/// let builder = XBuilder::new(storage.clone()).expect("failed to create builder");
223/// {
224/// let mut v = builder.start_data().expect("failed to start");
225/// let mut a = v.grow().expect("grow failed");
226/// a.set_x(0);
227/// a.set_y(1);
228///
229/// let mut a = v.grow().expect("grow failed");
230/// a.set_x(2);
231/// a.set_y(3);
232///
233/// let view = v.close().expect("close failed");
234///
235/// // data can also be inspected directly after closing
236/// assert_eq!(view.len(), 2);
237/// assert_eq!(view[0].x(), 0);
238/// assert_eq!(view[0].y(), 1);
239/// }
240///
241/// let archive = X::open(storage).expect("failed to open");
242/// let view = archive.data();
243/// assert_eq!(view[1].x(), 2);
244/// assert_eq!(view[1].y(), 3);
245/// ```
246///
247/// [`grow`]: #method.grow
248pub struct ExternalVector<'a, T>
249where
250 T: Struct,
251{
252 data: Vector<T>,
253 len: usize,
254 resource_handle: ResourceHandle<'a>,
255}
256
257impl<'a, T> ExternalVector<'a, T>
258where
259 T: Struct,
260{
261 /// Creates an empty `ExternalVector<T>` in the given resource storage.
262 pub fn new(resource_handle: ResourceHandle<'a>) -> Self {
263 Self {
264 data: Vector::new(),
265 len: 0,
266 resource_handle,
267 }
268 }
269
270 /// Number of elements that where added to this vector.
271 pub fn len(&self) -> usize {
272 self.len
273 }
274
275 /// Returns `true` if no element were added to this vector yet.
276 pub fn is_empty(&self) -> bool {
277 self.len() == 0
278 }
279
280 /// Appends an element to the end of this vector and returns a mutable
281 /// handle to it.
282 ///
283 /// Calling this method may flush data to storage (cf. [`flush`]), which
284 /// may fail due to different IO reasons.
285 ///
286 /// [`flush`]: #method.flush
287 pub fn grow(&mut self) -> io::Result<&mut T> {
288 if self.data.as_view().as_bytes().len() > 1024 * 1024 * 32 {
289 self.flush()?;
290 }
291 self.len += 1;
292 Ok(self.data.grow())
293 }
294
295 /// Flushes the not yet flushed content in this vector to storage.
296 fn flush(&mut self) -> io::Result<()> {
297 self.resource_handle
298 .borrow_mut()
299 .write(self.data.as_view().as_bytes())?;
300 self.data.clear();
301 Ok(())
302 }
303
304 /// Flushes the remaining not yet flushed elements in this vector and
305 /// finalizes the data inside the storage.
306 ///
307 /// An external vector *must* be closed
308 pub fn close(mut self) -> Result<&'a [T], ResourceStorageError> {
309 if self.data.len() > 0 || self.len == 0 {
310 self.flush().map_err(|e| {
311 ResourceStorageError::from_io_error(e, self.resource_handle.name().into())
312 })?;
313 }
314 self.resource_handle
315 .close()
316 .map(|data| <&[T]>::from_bytes(data).expect("Corrupted data"))
317 }
318}
319
320impl<T> fmt::Debug for ExternalVector<'_, T>
321where
322 T: Struct,
323{
324 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
325 write!(f, "ExternalVector {{ len: {} }}", self.len())
326 }
327}
328
329#[cfg(test)]
330#[allow(dead_code)]
331mod tests {
332 // Note: ExternalVector is tested in the corresponding example.
333
334 use super::*;
335 use crate::test::{A, R};
336
337 #[test]
338 fn test_vector_new() {
339 let v: Vector<A> = Vector::new();
340 assert_eq!(v.len(), 0);
341 }
342
343 #[test]
344 fn test_vector_range() {
345 let mut v: Vector<R> = Vector::with_len(3);
346 v[0].set_first_x(10);
347 v[1].set_first_x(20);
348 v[2].set_first_x(30);
349
350 assert_eq!(v[0].x(), 10..20);
351 assert_eq!(v[1].x(), 20..30);
352 assert_eq!(v[2].x(), 30..0);
353 }
354
355 #[test]
356 fn test_vector_index() {
357 let mut v: Vector<A> = Vector::with_len(2);
358 assert_eq!(v.len(), 2);
359 {
360 let a = &mut v[0];
361 a.set_x(1);
362 a.set_y(2);
363 assert_eq!(a.x(), 1);
364 assert_eq!(a.y(), 2);
365 }
366 {
367 let b = &mut v[1];
368 b.set_x(3);
369 b.set_y(4);
370 assert_eq!(b.x(), 3);
371 assert_eq!(b.y(), 4);
372 }
373 let a = &mut v[0];
374 assert_eq!(a.x(), 1);
375 assert_eq!(a.y(), 2);
376 let b = &mut v[1];
377 assert_eq!(b.x(), 3);
378 assert_eq!(b.y(), 4);
379 }
380
381 #[test]
382 fn test_vector_as_view() {
383 let mut v: Vector<A> = Vector::with_len(1);
384 assert_eq!(v.len(), 1);
385 {
386 let a = &mut v[0];
387 a.set_x(1);
388 assert_eq!(a.x(), 1);
389 a.set_y(2);
390 assert_eq!(a.y(), 2);
391 }
392 let view = v.as_view();
393 let a = &view[0];
394 assert_eq!(a.x(), 1);
395 assert_eq!(a.y(), 2);
396 }
397
398 #[test]
399 fn test_vector_grow() {
400 let mut v: Vector<A> = Vector::with_len(1);
401 assert_eq!(v.len(), 1);
402 {
403 let a = &mut v[0];
404 a.set_x(1);
405 a.set_y(2);
406 assert_eq!(a.x(), 1);
407 assert_eq!(a.y(), 2);
408 }
409 {
410 let b = v.grow();
411 b.set_x(3);
412 b.set_y(4);
413 assert_eq!(b.x(), 3);
414 assert_eq!(b.y(), 4);
415 }
416 {
417 assert_eq!(v.len(), 2);
418 let a = &v[0];
419 assert_eq!(a.x(), 1);
420 assert_eq!(a.y(), 2);
421 let b = &v[1];
422 assert_eq!(b.x(), 3);
423 assert_eq!(b.y(), 4);
424 }
425 v.grow();
426 assert_eq!(v.len(), 3);
427 }
428
429 #[test]
430 fn test_ability_to_get_mut_and_const_for_non_overlap() {
431 let mut v: Vector<A> = Vector::with_len(10);
432 let mut_v_ref = &mut v[..];
433 let (left, right) = mut_v_ref.split_at_mut(5);
434 let x = &mut left[4];
435 let y = &mut right[0];
436 y.set_x(10);
437 assert_eq!(y.x(), 10);
438 assert_eq!(x.x(), 0);
439 }
440}