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
//! An atom containing multiple key-value pairs.
//!
//! This module is centered on the [`Object`](struct.Object.html) atom type. An object is the atomized form of an RDF instance: It has an (optional) id, a type and multiple properties declared as URID/Atom pairs. Both the id and the type are URIDs too.
//!
//! # Example
//! ```
//! use lv2_core::prelude::*;
//! use lv2_atom::prelude::*;
//! use urid::*;
//!
//! #[uri("urn:object-class")]
//! struct ObjectClass;
//!
//! #[uri("urn:property-a")]
//! struct PropertyA;
//!
//! #[derive(PortCollection)]
//! struct MyPorts {
//!     input: InputPort<AtomPort>,
//!     output: OutputPort<AtomPort>,
//! }
//!
//! #[derive(URIDCollection)]
//! struct MyURIDs {
//!     atom: AtomURIDCollection,
//!     object_class: URID<ObjectClass>,
//!     property_a: URID<PropertyA>,
//! }
//!
//! fn run(ports: &mut MyPorts, urids: &MyURIDs) {
//!     // Create the reading handle.
//!     // We don't need the header now.
//!     let (_header, object_reader) = ports.input.read(urids.atom.object, ()).unwrap();
//!
//!     /// Iterate through all properties of the object.
//!     for (property_header, atom) in object_reader {
//!         // If the property is an integer...
//!         if let Some(integer) = atom.read(urids.atom.int, ()) {
//!             // Print it!
//!             println!(
//!                 "Property No. {} has integer value {}",
//!                 property_header.key.get(),
//!                 integer
//!             );
//!         } else {
//!             // Print that is not an integer.
//!             println!(
//!                 "Property No. {} is not an integer",
//!                 property_header.key.get()
//!             );
//!         }
//!     }
//!
//!     // Initialize the object.
//!     let mut object_writer = ports.output.init(
//!         urids.atom.object,
//!         ObjectHeader {
//!             id: None,
//!             otype: urids.object_class.into_general(),
//!         }
//!     ).unwrap();
//!
//!     // Write a property to the object.
//!     object_writer.init(urids.property_a, None, urids.atom.int, 42).unwrap();
//! }
//! ```
//!
//! # Specification
//! [http://lv2plug.in/ns/ext/atom/atom.html#Object](http://lv2plug.in/ns/ext/atom/atom.html#Object).
use crate::space::*;
use crate::*;
use std::convert::TryFrom;
use std::iter::Iterator;
use urid::UriBound;
use urid::URID;

/// An atom containing multiple key-value pairs.
///
/// [See also the module documentation.](index.html)
pub struct Object;

unsafe impl UriBound for Object {
    const URI: &'static [u8] = sys::LV2_ATOM__Object;
}

/// Information about an object atom.
pub struct ObjectHeader {
    /// The id of the object to distinguish different objects of the same type.
    ///
    /// If you don't need it, you should set it to `None`.
    pub id: Option<URID>,
    /// The type of the object (same as `rdf:type`).
    pub otype: URID,
}

impl<'a, 'b> Atom<'a, 'b> for Object
where
    'a: 'b,
{
    type ReadParameter = ();
    type ReadHandle = (ObjectHeader, ObjectReader<'a>);
    type WriteParameter = ObjectHeader;
    type WriteHandle = ObjectWriter<'a, 'b>;

    fn read(body: Space<'a>, _: ()) -> Option<(ObjectHeader, ObjectReader<'a>)> {
        let (header, body) = body.split_type::<sys::LV2_Atom_Object_Body>()?;
        let header = ObjectHeader {
            id: URID::try_from(header.id).ok(),
            otype: URID::try_from(header.otype).ok()?,
        };

        let reader = ObjectReader { space: body };

        Some((header, reader))
    }

    fn init(
        mut frame: FramedMutSpace<'a, 'b>,
        header: ObjectHeader,
    ) -> Option<ObjectWriter<'a, 'b>> {
        {
            let frame = &mut frame as &mut dyn MutSpace;
            frame.write(
                &sys::LV2_Atom_Object_Body {
                    id: header.id.map(|urid| urid.get()).unwrap_or(0),
                    otype: header.otype.get(),
                },
                true,
            );
        }
        Some(ObjectWriter { frame })
    }
}

/// Deprecated alias of `Object`
///
/// A blank object is an object that isn't an instance of a class. The [specification recommends](https://lv2plug.in/ns/ext/atom/atom.html#Blank) to use an [`Object`](struct.Object.html) with an id of `None`, but some hosts still use it and therefore, it's included in this library.
#[deprecated]
pub struct Blank;

#[allow(deprecated)]
unsafe impl UriBound for Blank {
    const URI: &'static [u8] = sys::LV2_ATOM__Blank;
}

#[allow(deprecated)]
impl<'a, 'b> Atom<'a, 'b> for Blank
where
    'a: 'b,
{
    type ReadParameter = <Object as Atom<'a, 'b>>::ReadParameter;
    type ReadHandle = <Object as Atom<'a, 'b>>::ReadHandle;
    type WriteParameter = <Object as Atom<'a, 'b>>::WriteParameter;
    type WriteHandle = <Object as Atom<'a, 'b>>::WriteHandle;

    #[allow(clippy::unit_arg)]
    fn read(body: Space<'a>, parameter: Self::ReadParameter) -> Option<Self::ReadHandle> {
        Object::read(body, parameter)
    }

    fn init(
        frame: FramedMutSpace<'a, 'b>,
        parameter: Self::WriteParameter,
    ) -> Option<Self::WriteHandle> {
        Object::init(frame, parameter)
    }
}

/// An iterator over all properties in an object.
///
/// Each iteration item is the header of the property, as well as the space occupied by the value atom. You can use normal `read` methods on the returned space.
pub struct ObjectReader<'a> {
    space: Space<'a>,
}

impl<'a> Iterator for ObjectReader<'a> {
    type Item = (PropertyHeader, UnidentifiedAtom<'a>);

    fn next(&mut self) -> Option<(PropertyHeader, UnidentifiedAtom<'a>)> {
        let (header, value, space) = Property::read_body(self.space)?;
        self.space = space;
        Some((header, UnidentifiedAtom::new(value)))
    }
}

/// Writing handle for object properties.
///
/// This handle is a safeguard to assure that a object is always a series of properties.
pub struct ObjectWriter<'a, 'b> {
    frame: FramedMutSpace<'a, 'b>,
}

impl<'a, 'b> ObjectWriter<'a, 'b> {
    /// Initialize a new property.
    ///
    /// This method writes out the header of a property and returns a reference to the space, so the property values can be written.
    pub fn init<'c, G: ?Sized, A: Atom<'a, 'c>>(
        &'c mut self,
        key: URID<G>,
        context: Option<URID>,
        child_urid: URID<A>,
        parameter: A::WriteParameter,
    ) -> Option<A::WriteHandle> {
        Property::write_header(&mut self.frame, key.into_general(), context)?;
        (&mut self.frame as &mut dyn MutSpace).init(child_urid, parameter)
    }
}

/// An atom containing a key-value pair.
///
/// A property represents a single URID -> atom mapping. Additionally and optionally, you may also define a context in which the property is valid. For more information, visit the [specification](http://lv2plug.in/ns/ext/atom/atom.html#Property).
///
/// Most of the time, properties are a part of an [`Object`](struct.Object.html) atom and therefore, you don't need to read or write them directly. However, they could in theory appear on their own too, which is why reading and writing methods are still provided.
pub struct Property;

unsafe impl UriBound for Property {
    const URI: &'static [u8] = sys::LV2_ATOM__Property;
}

/// Information about a property atom.
#[derive(Clone, Copy)]
pub struct PropertyHeader {
    /// The key of the property.
    pub key: URID,
    /// URID of the context (generally `None`).
    pub context: Option<URID>,
}

impl Property {
    /// Read the body of a property atom from a space.
    ///
    /// This method assumes that the space actually contains the body of a property atom, without the header. It returns the property header, containing the key and optional context of the property, the body of the actual atom, and the space behind the atom.
    fn read_body(space: Space) -> Option<(PropertyHeader, Space, Space)> {
        #[repr(C)]
        #[derive(Clone, Copy)]
        /// A custom version of the property body that does not include the value atom header.
        ///
        /// We will retrieve it separately.
        struct StrippedPropertyBody {
            key: u32,
            context: u32,
        }

        let (header, space) = space.split_type::<StrippedPropertyBody>()?;

        let header = PropertyHeader {
            key: URID::try_from(header.key).ok()?,
            context: URID::try_from(header.context).ok(),
        };

        let (atom, space) = space.split_atom()?;
        Some((header, atom, space))
    }

    /// Write out the header of a property atom.
    ///
    /// This method simply writes out the content of the header to the space and returns `Some(())` if it's successful.
    fn write_header(space: &mut dyn MutSpace, key: URID, context: Option<URID>) -> Option<()> {
        space.write(&key.get(), true)?;
        space.write(&context.map(|urid| urid.get()).unwrap_or(0), false)?;
        Some(())
    }
}

#[cfg(test)]
mod tests {
    use crate::prelude::*;
    use crate::space::*;
    use std::mem::size_of;
    use urid::*;

    #[test]
    fn test_object() {
        let map = HashURIDMapper::new();
        let urids = AtomURIDCollection::from_map(&map).unwrap();

        let object_type = map
            .map_uri(Uri::from_bytes_with_nul(b"urn:my-type\0").unwrap())
            .unwrap();

        let first_key = map
            .map_uri(Uri::from_bytes_with_nul(b"urn:value-a\0").unwrap())
            .unwrap();
        let first_value: i32 = 17;

        let second_key = map
            .map_uri(Uri::from_bytes_with_nul(b"urn:value-b\0").unwrap())
            .unwrap();
        let second_value: f32 = 42.0;

        let mut raw_space: Box<[u8]> = Box::new([0; 256]);

        // writing
        {
            let mut space = RootMutSpace::new(raw_space.as_mut());
            let frame = FramedMutSpace::new(&mut space as &mut dyn MutSpace, urids.object).unwrap();
            let mut writer = Object::init(
                frame,
                ObjectHeader {
                    id: None,
                    otype: object_type,
                },
            )
            .unwrap();
            {
                writer
                    .init(first_key, None, urids.int, first_value)
                    .unwrap();
            }
            {
                writer
                    .init(second_key, None, urids.float, second_value)
                    .unwrap();
            }
        }

        // verifying
        {
            // Header
            let (atom, space) = raw_space.split_at(size_of::<sys::LV2_Atom>());
            let atom = unsafe { &*(atom.as_ptr() as *const sys::LV2_Atom) };
            assert_eq!(atom.type_, urids.object);
            assert_eq!(
                atom.size as usize,
                size_of::<sys::LV2_Atom_Object_Body>()
                    + size_of::<sys::LV2_Atom_Property_Body>()
                    + 2 * size_of::<i32>()
                    + size_of::<sys::LV2_Atom_Property_Body>()
                    + size_of::<f32>()
            );

            // Object.
            let (object, space) = space.split_at(size_of::<sys::LV2_Atom_Object_Body>());
            let object = unsafe { &*(object.as_ptr() as *const sys::LV2_Atom_Object_Body) };
            assert_eq!(object.id, 0);
            assert_eq!(object.otype, object_type);

            // First property.
            let (property, space) = space.split_at(size_of::<sys::LV2_Atom_Property_Body>());
            let property = unsafe { &*(property.as_ptr() as *const sys::LV2_Atom_Property_Body) };
            assert_eq!(property.key, first_key);
            assert_eq!(property.context, 0);
            assert_eq!(property.value.type_, urids.int);
            assert_eq!(property.value.size as usize, size_of::<i32>());

            let (value, space) = space.split_at(size_of::<i32>());
            let value = unsafe { *(value.as_ptr() as *const i32) };
            assert_eq!(value, first_value);
            let (_, space) = space.split_at(size_of::<i32>());

            // Second property.
            let (property, space) = space.split_at(size_of::<sys::LV2_Atom_Property_Body>());
            let property = unsafe { &*(property.as_ptr() as *const sys::LV2_Atom_Property_Body) };
            assert_eq!(property.key, second_key);
            assert_eq!(property.context, 0);
            assert_eq!(property.value.type_, urids.float);
            assert_eq!(property.value.size as usize, size_of::<f32>());

            let (value, _) = space.split_at(size_of::<f32>());
            let value = unsafe { *(value.as_ptr() as *const f32) };
            assert_eq!(value, second_value);
        }

        // reading
        {
            let space = Space::from_slice(raw_space.as_ref());
            let (body, _) = space.split_atom_body(urids.object).unwrap();

            let (header, iter) = Object::read(body, ()).unwrap();
            assert_eq!(header.otype, object_type);
            assert_eq!(header.id, None);

            let properties: Vec<(PropertyHeader, UnidentifiedAtom)> = iter.collect();
            let (header, atom) = properties[0];
            assert_eq!(header.key, first_key);
            assert_eq!(atom.read::<Int>(urids.int, ()).unwrap(), first_value);
            let (header, atom) = properties[1];
            assert_eq!(header.key, second_key);
            assert_eq!(atom.read::<Float>(urids.float, ()).unwrap(), second_value);
        }
    }
}