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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! This module contains traits and macros that are used by generated code to
//! define flatdata's structs, archives and resources.
//!
//! # Archive
//!
//! A flatdata archive is introduced by `define_archive`. It defines two types
//! `ArchiveName` and `ArchiveNameBuilder` for reading resp. writing data.

use crate::{error::ResourceStorageError, storage::ResourceStorage};

use std::{fmt::Debug, rc::Rc};

#[doc(hidden)]
pub use std::marker;

/// A flatdata archive representing serialized data.
///
/// Each archive in generated code implements this trait.
pub trait Archive: Debug + Clone {
    /// Name of the archive.
    const NAME: &'static str;
    /// Schema of the archive.
    ///
    /// Used for verifying the integrity of the archive when opening.
    const SCHEMA: &'static str;

    /// Opens the archive with name `NAME` and schema `SCHEMA` in the given
    /// storage for reading.
    ///
    /// When opening the archive, the schema of the archive and the schema
    /// stored in the storage are compared as strings. If there is a
    /// difference, an Error [`ResourceStorageError::WrongSignature`](enum.
    /// ResourceStorageError.html) is returned containing a detailed diff
    /// of both schemata.
    ///
    /// All resources are in the archive are also opened and their schemata are
    /// verified. If any non-optional resource is missing or has a wrong
    /// signature (unexpected schema), the operation will fail. Therefore,
    /// it is not possible to open partially written archive.
    fn open(storage: Rc<ResourceStorage>) -> Result<Self, ResourceStorageError>;
}

/// A flatdata archive builder for serializing data.
///
/// For each archive in generated code there is a corresponding archive builder
/// which implements this trait.
pub trait ArchiveBuilder: Clone {
    /// Name of the archive associated with this archive builder.
    const NAME: &'static str;
    /// Schema of the archive associated with this archive builder.
    ///
    /// Used only for debug and inspection purposes.
    const SCHEMA: &'static str;

    /// Creates an archive with name `NAME` and schema `SCHEMA` in the given
    /// storage for writing.
    ///
    /// If the archive is successfully created, the storage will contain the
    /// archive and archives schema. Archive's resources need to be written
    /// separately by using the corresponding generated methods:
    ///
    /// * `set_struct`
    /// * `set_vector`
    /// * `start_vector`/`finish_vector`
    /// * `start_multivector`/`finish_multivector`.
    ///
    /// For more information about how to write resources, cf. the
    /// [coappearances] example.
    ///
    /// [coappearances]: https://github.com/boxdot/flatdata-rs/blob/master/tests/coappearances_test.rs#L159
    fn new(storage: Rc<ResourceStorage>) -> Result<Self, ResourceStorageError>;
}

/// Macro used by generator to define a flatdata archive and corresponding
/// archive builder.
#[doc(hidden)]
#[macro_export]
macro_rules! define_archive {
    // prelude of internal helpers (see https://danielkeep.github.io/tlborm/book/pat-internal-rules.html)

    // static if
    (@if, true, $true_block:block, $false_block:block) => {
        $true_block
    };
    (@if, false, $true_block:block, $false_block:block) => {
        $false_block
    };

    // define member types
    (@members, multivector(true $($args:tt)*)) => {
        Option<($crate::MemoryDescriptor, $crate::MemoryDescriptor)>
    };
    (@members, multivector(false $($args:tt)*)) => {
        ($crate::MemoryDescriptor, $crate::MemoryDescriptor)
    };
    (@members, archive(true, $schema:expr, $type:path, $builder_type:path)) => {
        Option<$type>
    };
    (@members, archive(false, $schema:expr, $type:path, $builder_type:path)) => {
        $type
    };
    (@members, $type:ident(true $($args:tt)*)) => {
        Option<$crate::MemoryDescriptor>
    };
    (@members, $type:ident(false $($args:tt)*)) => {
        $crate::MemoryDescriptor
    };

    // check resources
    (@check, $res:expr, false) => {
        $res?
    };
    (@check, $res:expr, true) => {
        $res.ok()
    };

    // read resources
    (@read, $storage:ident, raw_data($name:ident, $optional:ident, $schema:expr, $setter:ident)) => {{
        define_archive!(@check,
            Self::read_resource(&*$storage, stringify!($name), $schema),
            $optional
        )
    }};
    (@read, $storage:ident, struct($name:ident, $optional:ident, $schema:expr, $setter:ident, $type:path)) => {{
        define_archive!(@check,
            Self::read_resource(&*$storage, stringify!($name), $schema),
            $optional
        )
    }};
    (@read, $storage:ident, vector($name:ident, $optional:ident, $schema:expr, $setter:ident, $starter:ident, $type:path)) => {{
        define_archive!(@check,
            Self::read_resource(&*$storage, stringify!($name), $schema),
            $optional
        )
    }};
    (@read, $storage:ident, multivector($name:ident, $optional:ident, $schema:expr, $starter:ident, $variadic_type:path, $index:ident, $index_type:path)) => {{
        let index_schema = &format!("index({})", $schema);
        let index = define_archive!(@check,
            Self::read_resource(&*$storage, stringify!($index), &index_schema),
            $optional
        );
        let data = define_archive!(@check,
            Self::read_resource(&*$storage, stringify!($name), $schema),
            $optional
        );
        define_archive!(@if,
            $optional,
            {
                match (index, data) {
                    (Some(a), Some(b)) => Some((a, b)),
                    _ => None,
                }
            },
            { (index, data) }
        )
    }};
    (@read, $storage:ident, archive($name:ident, $optional:ident, $schema:expr, $type:path, $builder_type:path)) => {{
        type Archive = $type;
        define_archive!(@check,
            Archive::open($storage.subdir(&stringify!($name))),
            $optional
        )
    }};

    // resource getters
    (@get, raw_data($name:ident, true, $schema:expr, $setter:ident)) => {
        pub fn $name(&self) -> Option<$crate::RawData> {
            self.$name.as_ref().map(|mem_desc| $crate::RawData::new({unsafe{mem_desc.as_bytes()}}))
        }
    };
    (@get, raw_data($name:ident, false, $schema:expr, $setter:ident)) => {
        pub fn $name(&self) -> $crate::RawData {
            $crate::RawData::new(unsafe {self.$name.as_bytes()})
        }
    };
    (@get, struct($name:ident, true, $schema:expr, $setter:ident, $type:path)) => {
        pub fn $name(&self) -> Option<<$type as $crate::Struct>::Item>
        {
            self.$name.as_ref().map(|mem_desc| {<$type as $crate::Struct>::create(&unsafe{mem_desc.as_bytes()})})
        }
    };
    (@get, struct($name:ident, false, $schema:expr, $setter:ident, $type:path)) => {
        pub fn $name(&self) -> <$type as $crate::Struct>::Item
        {
            <$type as $crate::Struct>::create(&unsafe{self.$name.as_bytes()})
        }
    };
    (@get, vector($name:ident, true, $schema:expr, $setter:ident, $starter:ident, $type:path)) => {
        pub fn $name(&self) -> Option<$crate::ArrayView<$type>>
        {
            self.$name.as_ref().map(|x|$crate::ArrayView::new(unsafe{x.as_bytes()}))
        }
    };
    (@get, vector($name:ident, false, $schema:expr, $setter:ident, $starter:ident, $type:path)) => {
        pub fn $name(&self) -> $crate::ArrayView<$type>
        {
            $crate::ArrayView::new(&unsafe{self.$name.as_bytes()})
        }
    };
    (@get, multivector($name:ident, true, $schema:expr, $starter:ident, $variadic_type:path, $index:ident, $index_type:path)) => {
        pub fn $name(&self) -> Option<$crate::MultiArrayView<$variadic_type>>
        {
            self.$name.as_ref()
                .map(|(index, data)|{
                    $crate::MultiArrayView::new($crate::ArrayView::new(unsafe{index.as_bytes()}), unsafe{data.as_bytes()})
                })
        }
    };
    (@get, multivector($name:ident, false, $schema:expr, $starter:ident, $variadic_type:path, $index:ident, $index_type:path)) => {
        pub fn $name(&self) -> $crate::MultiArrayView<$variadic_type>
        {
            $crate::MultiArrayView::new(
                $crate::ArrayView::new(&unsafe{self.$name.0.as_bytes()}),
                &unsafe{self.$name.1.as_bytes()},
            )
        }
    };
    (@get, archive($name:ident, true, $schema:expr, $type:path, $builder_type:path)) => {
        pub fn $name(&self) -> Option<&$type>
        {
            self.$name.as_ref()
        }
    };
    (@get, archive($name:ident, false, $schema:expr, $type:path, $builder_type:path)) => {
        pub fn $name(&self) -> &$type
        {
            &self.$name
        }
    };

    // resource setters
    (@set, raw_data($name:ident, $optional:ident, $schema:expr, $setter:ident)) => {
        pub fn $setter(&self, data: &[u8]) -> ::std::io::Result<()> {
            self.storage.write(stringify!($name), $schema, data)
        }
    };
    (@set, struct($name:ident, $optional:ident, $schema:expr, $setter:ident, $type:path)) => {
        pub fn $setter(&self, resource: <$type as $crate::Struct>::Item) -> ::std::io::Result<()> {
            let data = unsafe {
                ::std::slice::from_raw_parts(resource.as_ptr(), <$type as $crate::Struct>::SIZE_IN_BYTES)
            };
            self.storage.write(stringify!($name), $schema, data)
        }
    };
    (@set, vector($name:ident, $optional:ident, $schema:expr, $setter:ident, $starter:ident, $type:path)) => {
        pub fn $setter(&self, vector: &$crate::ArrayView<$type>) -> ::std::io::Result<()> {
            self.storage.write(stringify!($name), $schema, vector.as_ref())
        }

        pub fn $starter(&self) -> ::std::io::Result<$crate::ExternalVector<$type>> {
            $crate::create_external_vector(&*self.storage, stringify!($name), $schema)
        }
    };
    (@set, multivector($name:ident, $optional:ident, $schema:expr, $starter:ident, $variadic_type:path, $index:ident, $index_type:path)) => {
        pub fn $starter(&self) -> ::std::io::Result<$crate::MultiVector<$variadic_type>> {
            $crate::create_multi_vector(&*self.storage, stringify!($name), $schema)
        }
    };
    (@set, archive($name:ident, $optional:ident, $schema:expr, $type:path, $builder_type:path)) => {
        pub fn $name(&self) -> Result<$builder_type, $crate::ResourceStorageError> {
            use $crate::ArchiveBuilder;
            let storage = self.storage.subdir(stringify!($name));
            type Builder = $builder_type;
            Builder::new(storage)
        }
    };

    // main entry point
    ($name:ident, $builder_name:ident, $archive_schema:expr;
        $($resource_type:ident($resource_name:ident, $is_optional:ident $($args:tt)* ),)*
    ) => {
        #[derive(Clone)]
        pub struct $name {
            _storage: ::std::rc::Rc<$crate::ResourceStorage>
            $(, $resource_name: define_archive!(@members, $resource_type($is_optional $($args)*)))*
        }

        impl $name {
            fn read_resource(
                storage: &$crate::ResourceStorage,
                name: &str,
                schema: &str,
            ) -> Result<$crate::MemoryDescriptor, $crate::ResourceStorageError>
            {
                storage.read(name, schema).map(|x| $crate::MemoryDescriptor::new(&x))
            }

            $(define_archive!(@get, $resource_type($resource_name, $is_optional $($args)* ));)*

            fn signature_name(archive_name: &str) -> String {
                format!("{}.archive", archive_name)
            }
        }

        impl ::std::fmt::Debug for $name {
            fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                write!(f,
                    concat!(stringify!($name), " {{ ",
                        flatdata_intersperse!($(concat!(stringify!($resource_name), ": {:?}")),*),
                    " }}"),
                    $(self.$resource_name(), )*
                )
            }
        }

        impl $crate::Archive for $name {
            const NAME: &'static str = stringify!($name);
            const SCHEMA: &'static str = $archive_schema;

            fn open(storage: ::std::rc::Rc<$crate::ResourceStorage>)
                -> ::std::result::Result<Self, $crate::ResourceStorageError>
            {
                storage.read(&Self::signature_name(Self::NAME), Self::SCHEMA)?;

                $(let $resource_name = define_archive!(@read, storage, $resource_type($resource_name, $is_optional $($args)* ));)*

                Ok(Self {
                    _storage: storage
                    $(,$resource_name)*
                })
            }
        }

        #[derive(Clone, Debug)]
        pub struct $builder_name {
            storage: ::std::rc::Rc<$crate::ResourceStorage>
        }

        impl $builder_name {
            $(define_archive!(@set, $resource_type($resource_name, $is_optional $($args)* ));)*
        }

        impl $crate::ArchiveBuilder for $builder_name {
            const NAME: &'static str = stringify!($name);
            const SCHEMA: &'static str = $archive_schema;

            fn new(
                storage: ::std::rc::Rc<$crate::ResourceStorage>,
            ) -> Result<Self, $crate::ResourceStorageError> {
                $crate::create_archive::<Self>(&storage)?;
                Ok(Self { storage })
            }
        }
    }
}

#[cfg(test)]
mod test {

    #[test]
    #[allow(warnings)]
    fn test_archive_compilation() {
        // This test checks that the archive definition below compiles.
        use crate::structs::Ref;

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

        mod submodA {
            define_struct!(
                B,
                RefB,
                RefMutB,
                "no_schema",
                4,
                (x, set_x, u32, u32, 0, 16),
                (y, set_y, u32, u32, 16, 16)
            );
        }
        define_index!(
            IndexType32,
            RefIndexType32,
            RefMutIndexType32,
            "IndexType32 schema",
            4,
            32
        );

        define_variadic_struct!(Ts, RefTs, BuilderTs, IndexType32,
            0 => (A, A, add_a),
            1 => (B, submodA::B, add_b));

        define_archive!(SubArch, SubArchBuilder, "SubArch schema";
            raw_data(raw, false, "raw schema", set_raw),
        );

        mod submodB {
            pub const V_SCHEMA: &str = "v schema";
        }

        define_archive!(Arch, ArchBuilder, "Arch schema";
            struct(a, false, "a schema", set_a, A),
            struct(b, true, "b schema", set_b, submodA::B),
            vector(v, false, submodB::V_SCHEMA, set_v, start_v, A),
            vector(w, true, "w schema", set_w, start_w, A),
            multivector(mv, false, "mv schema", start_mv, Ts, mv_index, IndexType32),
            multivector(mw, true, "mw schema", start_mw, Ts, mw_index, IndexType32),
            raw_data(r, false, "r schema", set_r),
            raw_data(s, true, "s schema", set_s),
            archive(arch, false, "arch schema", SubArch, SubArchBuilder),
            archive(opt_arch, true, "opt_arch schema", SubArch, SubArchBuilder),
        );
    }
}