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
// Note: This module is called `structbuf` in contrast to `struct` in the C++
// implementation, since Rust does not allow module names to be one of the
// language keywords.
use crate::{
    memory,
    structs::{NoOverlap, RefFactory, Struct},
};

use std::{fmt, marker};

/// A container holding a single flatdata struct in memory, and providing read
/// and write access to it.
///
/// Used in combination with [`ArchiveBuilder`] to serialize single struct
/// resources, cf. [coappearances] example.
///
/// A struct buffer derefs (const and mut) to a reference of the underlying
/// struct, therefore, struct getters and setters can be used directly on
/// buffer.
///
/// # Examples
/// ``` flatdata
/// struct A {
///     x : u32 : 16;
///     y : u32 : 16;
/// }
///
/// archive X {
///    data : A;
/// }
/// ```
///
/// ```
/// # #[macro_use] extern crate flatdata;
/// # fn main() {
/// # use flatdata::{ MemoryResourceStorage, Archive, ArchiveBuilder, StructBuf };
/// #
/// # define_struct!(
/// #     A,
/// #     RefA,
/// #     RefMutA,
/// #     "schema of A",
/// #     4,
/// #     (x, set_x, u32, u32, 0, 16),
/// #     (y, set_y, u32, u32, 16, 16));
/// #
/// # define_archive!(X, XBuilder, "schema of X";
/// #     struct(data, false, "schema of data", set_data, A),
/// # );
/// #
/// let storage = MemoryResourceStorage::new("/root/structbuf");
/// let builder = XBuilder::new(storage.clone()).expect("failed to create builder");
/// let mut a = StructBuf::<A>::new();
/// a.get_mut().set_x(1);
/// a.get_mut().set_y(2);
/// builder.set_data(a.get());
///
/// println!("{:?}", storage);
/// let archive = X::open(storage).expect("failed to open");
/// let view = archive.data();
///
/// assert_eq!(view.x(), 1);
/// assert_eq!(view.y(), 2);
/// # }
/// ```
///
/// [`ArchiveBuilder`]: trait.ArchiveBuilder.html
/// [coappearances]: https://github.com/boxdot/flatdata-rs/blob/master/tests/coappearances_test.rs#L183
pub struct StructBuf<T>
where
    T: RefFactory + NoOverlap,
{
    data: Vec<u8>,
    _phantom: marker::PhantomData<T>,
}

impl<T> StructBuf<T>
where
    T: RefFactory + NoOverlap,
{
    /// Creates an empty struct buffer.
    ///
    /// All fields are set to 0.
    pub fn new() -> Self {
        let data = vec![0; <T as Struct>::SIZE_IN_BYTES + memory::PADDING_SIZE];
        Self {
            data,
            _phantom: marker::PhantomData,
        }
    }

    /// Get the stored object
    pub fn get(&self) -> <T as Struct>::Item {
        <T as Struct>::create(&self.data)
    }

    /// Get the mutable version of the stored object
    pub fn get_mut(&mut self) -> <T as Struct>::ItemMut {
        <T as Struct>::create_mut(&mut self.data)
    }

    /// Returns a raw bytes representation of the buffer.
    pub fn as_bytes(&self) -> &[u8] {
        &self.data[0..<T as Struct>::SIZE_IN_BYTES]
    }
}

impl<T> fmt::Debug for StructBuf<T>
where
    T: RefFactory + NoOverlap,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "StructBuf {{ resource: {:?} }}", self.get())
    }
}

impl<T> Default for StructBuf<T>
where
    T: RefFactory + NoOverlap,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<T> AsRef<[u8]> for StructBuf<T>
where
    T: RefFactory + NoOverlap,
{
    fn as_ref(&self) -> &[u8] {
        self.as_bytes()
    }
}

#[cfg(test)]
#[allow(dead_code)]
mod test {
    use super::*;

    define_struct!(
        A,
        RefA,
        RefMutA,
        "no_schema",
        4,
        (x, set_x, u32, u32, 0, 16),
        (y, set_y, u32, u32, 16, 16)
    );

    #[test]
    fn test_new() {
        let a = StructBuf::<A>::new();
        let b = StructBuf::<A>::default();
        assert_eq!(a.get(), b.get());
    }

    #[test]
    fn test_setter_getter() {
        let mut a = StructBuf::<A>::new();
        a.get_mut().set_x(1);
        a.get_mut().set_y(2);
        assert_eq!(a.get().x(), 1);
        assert_eq!(a.get().y(), 2);
        a.get_mut().set_x(3);
        assert_eq!(a.get().x(), 3);
        assert_eq!(a.get().y(), 2);
        a.get_mut().set_y(4);
        assert_eq!(a.get().x(), 3);
        assert_eq!(a.get().y(), 4);
        let a_ref = a.get();
        assert_eq!(a_ref.x(), 3);
        assert_eq!(a_ref.y(), 4);
    }
}