Skip to main content

vapoursynth4_rs/
map.rs

1use std::{
2    ffi::{CStr, c_char, c_int},
3    mem::ManuallyDrop,
4};
5
6use thiserror::Error;
7
8use crate::{
9    api::Api,
10    ffi,
11    frame::{AudioFrame, Frame, VideoFrame, internal::FrameFromPtr},
12    function::Function,
13    node::{AudioNode, Node, VideoNode},
14};
15
16mod key;
17pub use key::*;
18
19// MARK: MapRef
20
21/// A read-only borrowed reference to a [`ffi::VSMap`].
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
23pub struct MapRef<'m> {
24    handle: *const ffi::VSMap,
25    api: Api,
26    marker: std::marker::PhantomData<&'m ()>,
27}
28
29unsafe impl Send for MapRef<'_> {}
30
31impl MapRef<'_> {
32    // The map must remain valid and immutable for the view's lifetime.
33    #[inline]
34    pub(crate) unsafe fn from_ptr(ptr: *const ffi::VSMap, api: Api) -> Self {
35        debug_assert!(!ptr.is_null());
36        Self {
37            handle: ptr,
38            api,
39            marker: std::marker::PhantomData,
40        }
41    }
42
43    /// Returns a raw pointer to the wrapped value.
44    #[must_use]
45    #[inline]
46    pub fn as_ptr(&self) -> *const ffi::VSMap {
47        self.handle
48    }
49}
50
51/// An exclusive borrowed map. It cannot be copied or converted into an owner.
52#[derive(Debug, PartialEq, Eq, Hash)]
53pub struct MapMut<'m> {
54    handle: *const ffi::VSMap,
55    api: Api,
56    marker: std::marker::PhantomData<&'m mut ()>,
57}
58
59unsafe impl Send for MapMut<'_> {}
60
61impl MapMut<'_> {
62    // The map must remain valid and exclusively borrowed for the view's lifetime.
63    pub(crate) unsafe fn from_ptr(ptr: *mut ffi::VSMap, api: Api) -> Self {
64        debug_assert!(!ptr.is_null());
65        Self {
66            handle: ptr,
67            api,
68            marker: std::marker::PhantomData,
69        }
70    }
71
72    #[must_use]
73    pub fn as_ptr(&self) -> *mut ffi::VSMap {
74        self.handle.cast_mut()
75    }
76
77    #[must_use]
78    pub fn as_ref(&self) -> MapRef<'_> {
79        unsafe { MapRef::from_ptr(self.handle, self.api) }
80    }
81
82    #[must_use]
83    pub fn reborrow(&mut self) -> MapMut<'_> {
84        unsafe { MapMut::from_ptr(self.as_ptr(), self.api) }
85    }
86}
87
88// MARK: Map
89
90/// An owned [`ffi::VSMap`].
91#[derive(Debug, PartialEq, Eq, Hash)]
92pub struct Map {
93    handle: *const ffi::VSMap,
94    api: Api,
95}
96
97unsafe impl Send for Map {}
98
99impl Map {
100    // Safety: `ptr` must be a valid, owned instance created by `api`.
101    #[must_use]
102    pub(crate) unsafe fn from_ptr(ptr: *mut ffi::VSMap, api: Api) -> Self {
103        debug_assert!(!ptr.is_null());
104        Self { handle: ptr, api }
105    }
106
107    /// Returns a raw pointer to the wrapped value.
108    #[must_use]
109    pub fn as_ptr(&self) -> *mut ffi::VSMap {
110        self.handle.cast_mut()
111    }
112}
113
114macro_rules! map_read_methods {
115    () => {
116        #[must_use]
117        pub fn get_error(&self) -> Option<&CStr> {
118            let ptr = unsafe { (self.api.mapGetError)(self.as_ptr()) };
119            if ptr.is_null() {
120                None
121            } else {
122                Some(unsafe { CStr::from_ptr(ptr) })
123            }
124        }
125
126        #[must_use]
127        pub fn len(&self) -> i32 {
128            // safety: `self.handle` is a valid pointer
129            unsafe { (self.api.mapNumKeys)(self.as_ptr()) }
130        }
131
132        #[must_use]
133        pub fn is_empty(&self) -> bool {
134            self.len() == 0
135        }
136
137        // MARK: Get
138
139        /// # Panics
140        ///
141        /// Panics if `index` is out of bounds.
142        #[must_use]
143        pub fn get_key(&self, index: i32) -> &KeyStr {
144            assert!(!(index < 0 || index >= self.len()), "index out of bounds");
145
146            // safety: `self.handle` is a valid pointer
147            unsafe { KeyStr::from_ptr((self.api.mapGetKey)(self.as_ptr(), index)) }
148        }
149
150        #[must_use]
151        pub fn num_elements(&self, key: &KeyStr) -> Option<i32> {
152            // safety: `self.handle` is a valid pointer
153            let res = unsafe { (self.api.mapNumElements)(self.as_ptr(), key.as_ptr()) };
154            if res == -1 { None } else { Some(res) }
155        }
156
157        unsafe fn get_internal<T>(
158            &self,
159            func: unsafe extern "system-unwind" fn(
160                *const ffi::VSMap,
161                *const c_char,
162                c_int,
163                *mut ffi::VSMapPropertyError,
164            ) -> T,
165            key: &KeyStr,
166            index: i32,
167        ) -> Result<T, MapPropertyError> {
168            let mut error = ffi::VSMapPropertyError::Success;
169            handle_get_error(
170                unsafe { func(self.as_ptr(), key.as_ptr(), index, &raw mut error) },
171                error,
172            )
173        }
174
175        /// # Errors
176        ///
177        /// Return [`MapPropertyError`] if the underlying API does not success
178        pub fn get_int(&self, key: &KeyStr, index: i32) -> Result<i64, MapPropertyError> {
179            unsafe { self.get_internal(self.api.mapGetInt, key, index) }
180        }
181
182        /// # Errors
183        ///
184        /// Return [`MapPropertyError`] if the underlying API does not success
185        pub fn get_float(&self, key: &KeyStr, index: i32) -> Result<f64, MapPropertyError> {
186            unsafe { self.get_internal(self.api.mapGetFloat, key, index) }
187        }
188
189        /// # Errors
190        ///
191        /// Return [`MapPropertyError`] if the underlying API does not success
192        #[allow(clippy::cast_sign_loss)]
193        pub fn get_binary(&self, key: &KeyStr, index: i32) -> Result<&[u8], MapPropertyError> {
194            use ffi::VSDataTypeHint as dt;
195
196            unsafe {
197                if let dt::Unknown | dt::Binary =
198                    self.get_internal(self.api.mapGetDataTypeHint, key, index)?
199                {
200                    let size = self.get_internal(self.api.mapGetDataSize, key, index)?;
201                    let ptr = self.get_internal(self.api.mapGetData, key, index)?;
202
203                    Ok(std::slice::from_raw_parts(ptr.cast(), size as _))
204                } else {
205                    Err(MapPropertyError::InvalidType)
206                }
207            }
208        }
209
210        /// # Errors
211        ///
212        /// Return [`MapPropertyError`] if the underlying API does not success
213        #[allow(clippy::cast_sign_loss)]
214        pub fn get_utf8(&self, key: &KeyStr, index: i32) -> Result<&str, MapPropertyError> {
215            unsafe {
216                if let ffi::VSDataTypeHint::Utf8 =
217                    self.get_internal(self.api.mapGetDataTypeHint, key, index)?
218                {
219                    let size = self.get_internal(self.api.mapGetDataSize, key, index)?;
220                    let ptr = self.get_internal(self.api.mapGetData, key, index)?;
221
222                    std::str::from_utf8(std::slice::from_raw_parts(ptr.cast(), size as _))
223                        .map_err(|_| MapPropertyError::InvalidType)
224                } else {
225                    Err(MapPropertyError::InvalidType)
226                }
227            }
228        }
229
230        /// # Errors
231        ///
232        /// Return [`MapPropertyError`] if the underlying API does not success
233        pub fn get_function(&self, key: &KeyStr, index: i32) -> Result<Function, MapPropertyError> {
234            unsafe {
235                self.get_internal(self.api.mapGetFunction, key, index)
236                    .map(|p| Function::from_ptr(p, self.api))
237            }
238        }
239
240        /// # Errors
241        ///
242        /// Return [`MapPropertyError`] if the underlying API does not success
243        pub fn get_video_node(
244            &self,
245            key: &KeyStr,
246            index: i32,
247        ) -> Result<VideoNode, MapPropertyError> {
248            unsafe {
249                if (self.api.mapGetType)(self.as_ptr(), key.as_ptr())
250                    == ffi::VSPropertyType::AudioNode
251                {
252                    return Err(MapPropertyError::InvalidType);
253                }
254                self.get_internal(self.api.mapGetNode, key, index)
255                    .map(|p| VideoNode::from_ptr(p, self.api))
256            }
257        }
258
259        /// # Errors
260        ///
261        /// Return [`MapPropertyError`] if the underlying API does not success
262        pub fn get_audio_node(
263            &self,
264            key: &KeyStr,
265            index: i32,
266        ) -> Result<AudioNode, MapPropertyError> {
267            unsafe {
268                if (self.api.mapGetType)(self.as_ptr(), key.as_ptr())
269                    == ffi::VSPropertyType::VideoNode
270                {
271                    return Err(MapPropertyError::InvalidType);
272                }
273                self.get_internal(self.api.mapGetNode, key, index)
274                    .map(|p| AudioNode::from_ptr(p, self.api))
275            }
276        }
277
278        /// # Errors
279        ///
280        /// Return [`MapPropertyError`] if the underlying API does not success
281        pub fn get_video_frame(
282            &self,
283            key: &KeyStr,
284            index: i32,
285        ) -> Result<VideoFrame, MapPropertyError> {
286            unsafe {
287                if (self.api.mapGetType)(self.as_ptr(), key.as_ptr())
288                    == ffi::VSPropertyType::AudioFrame
289                {
290                    return Err(MapPropertyError::InvalidType);
291                }
292                self.get_internal(self.api.mapGetFrame, key, index)
293                    .map(|p| VideoFrame::from_ptr(p, self.api))
294            }
295        }
296
297        /// # Errors
298        ///
299        /// Return [`MapPropertyError`] if the underlying API does not success
300        pub fn get_audio_frame(
301            &self,
302            key: &KeyStr,
303            index: i32,
304        ) -> Result<AudioFrame, MapPropertyError> {
305            unsafe {
306                if (self.api.mapGetType)(self.as_ptr(), key.as_ptr())
307                    == ffi::VSPropertyType::VideoFrame
308                {
309                    return Err(MapPropertyError::InvalidType);
310                }
311                self.get_internal(self.api.mapGetFrame, key, index)
312                    .map(|p| AudioFrame::from_ptr(p, self.api))
313            }
314        }
315
316        /// # Errors
317        ///
318        /// Return [`MapPropertyError`] if the underlying API does not success
319        pub fn get(&self, key: &KeyStr, index: i32) -> Result<Value<'_>, MapPropertyError> {
320            use ffi::VSPropertyType as t;
321
322            unsafe {
323                match (self.api.mapGetType)(self.as_ptr(), key.as_ptr()) {
324                    t::Unset => Err(MapPropertyError::KeyNotFound),
325                    t::Int => self.get_int(key, index).map(Value::Int),
326                    t::Float => self.get_float(key, index).map(Value::Float),
327                    t::Data => {
328                        use ffi::VSDataTypeHint as dt;
329
330                        match self.get_internal(self.api.mapGetDataTypeHint, key, index)? {
331                            dt::Unknown | dt::Binary => {
332                                self.get_binary(key, index).map(Value::Data)
333                            }
334                            dt::Utf8 => self.get_utf8(key, index).map(Value::Utf8),
335                        }
336                    }
337                    t::Function => self.get_function(key, index).map(Value::Function),
338                    t::VideoNode => self.get_video_node(key, index).map(Value::VideoNode),
339                    t::AudioNode => self.get_audio_node(key, index).map(Value::AudioNode),
340                    t::VideoFrame => self.get_video_frame(key, index).map(Value::VideoFrame),
341                    t::AudioFrame => self.get_audio_frame(key, index).map(Value::AudioFrame),
342                }
343            }
344        }
345
346        /// # Errors
347        ///
348        /// Return [`MapPropertyError`] if the underlying API does not success
349        pub fn get_int_saturated(&self, key: &KeyStr, index: i32) -> Result<i32, MapPropertyError> {
350            unsafe { self.get_internal(self.api.mapGetIntSaturated, key, index) }
351        }
352
353        /// # Errors
354        ///
355        /// Return [`MapPropertyError`] if the underlying API does not success
356        pub fn get_int_array(&self, key: &KeyStr) -> Result<&[i64], MapPropertyError> {
357            let mut error = ffi::VSMapPropertyError::Success;
358            unsafe {
359                let size = self
360                    .num_elements(key)
361                    .ok_or(MapPropertyError::KeyNotFound)?;
362                let ptr = handle_get_error(
363                    (self.api.mapGetIntArray)(self.as_ptr(), key.as_ptr(), &raw mut error),
364                    error,
365                )?;
366
367                #[allow(clippy::cast_sign_loss)]
368                Ok(std::slice::from_raw_parts(ptr, size as _))
369            }
370        }
371
372        /// # Errors
373        ///
374        /// Return [`MapPropertyError`] if the underlying API does not success
375        pub fn get_float_saturated(
376            &self,
377            key: &KeyStr,
378            index: i32,
379        ) -> Result<f32, MapPropertyError> {
380            // safety: `self.handle` is a valid pointer
381            unsafe { self.get_internal(self.api.mapGetFloatSaturated, key, index) }
382        }
383
384        /// # Errors
385        ///
386        /// Return [`MapPropertyError`] if the underlying API does not success
387        pub fn get_float_array(&self, key: &KeyStr) -> Result<&[f64], MapPropertyError> {
388            let mut error = ffi::VSMapPropertyError::Success;
389            unsafe {
390                let size = self
391                    .num_elements(key)
392                    .ok_or(MapPropertyError::KeyNotFound)?;
393                let ptr = handle_get_error(
394                    (self.api.mapGetFloatArray)(self.as_ptr(), key.as_ptr(), &raw mut error),
395                    error,
396                )?;
397
398                #[allow(clippy::cast_sign_loss)]
399                Ok(std::slice::from_raw_parts(ptr, size as _))
400            }
401        }
402    };
403}
404
405macro_rules! map_write_methods {
406    () => {
407        pub fn clear(&mut self) {
408            // safety: `self.handle` is a valid pointer
409            unsafe { (self.api.clearMap)(self.as_ptr()) }
410        }
411
412        pub fn set_error(&mut self, msg: &CStr) {
413            // safety: `self.handle` and `msg` are valid pointers
414            unsafe { (self.api.mapSetError)(self.as_ptr(), msg.as_ptr()) }
415        }
416
417        pub fn delete_key(&mut self, key: &KeyStr) {
418            // safety: `self.handle` and `key` are valid pointers
419            unsafe { (self.api.mapDeleteKey)(self.as_ptr(), key.as_ptr()) };
420        }
421
422        // MARK: Set
423
424        /// # Panics
425        ///
426        /// Panics if the key exists or is invalid
427        pub fn set_empty(&mut self, key: &KeyStr, type_: ffi::VSPropertyType) {
428            // safety: `self.handle` is a valid pointer
429            let res = unsafe { (self.api.mapSetEmpty)(self.as_ptr(), key.as_ptr(), type_) };
430            assert_eq!(res, 0);
431        }
432
433        unsafe fn set_internal<T>(
434            &mut self,
435            func: unsafe extern "system-unwind" fn(
436                *mut ffi::VSMap,
437                *const c_char,
438                T,
439                ffi::VSMapAppendMode,
440            ) -> c_int,
441            key: &KeyStr,
442            val: T,
443            append: ffi::VSMapAppendMode,
444        ) -> Result<(), MapPropertyError> {
445            handle_set_error(unsafe { func(self.as_ptr(), key.as_ptr(), val, append) })
446        }
447
448        /// # Errors
449        ///
450        /// Return [`MapPropertyError::InvalidType`] if the `key`'s type is not the same with `val`
451        ///
452        /// # Panics
453        ///
454        /// Panic if the [`Value::Data`]'s or [`Value::Utf8`]'s len is larger than [`i32::MAX`]
455        pub fn set(
456            &mut self,
457            key: &KeyStr,
458            val: Value,
459            append: AppendMode,
460        ) -> Result<(), MapPropertyError> {
461            unsafe {
462                match val {
463                    Value::Int(val) => self.set_internal(self.api.mapSetInt, key, val, append),
464                    Value::Float(val) => self.set_internal(self.api.mapSetFloat, key, val, append),
465                    Value::Data(val) => handle_set_error((self.api.mapSetData)(
466                        self.as_ptr(),
467                        key.as_ptr(),
468                        val.as_ptr().cast(),
469                        val.len().try_into().unwrap(),
470                        ffi::VSDataTypeHint::Binary,
471                        append,
472                    )),
473                    Value::Utf8(val) => handle_set_error((self.api.mapSetData)(
474                        self.as_ptr(),
475                        key.as_ptr(),
476                        val.as_ptr().cast(),
477                        val.len().try_into().unwrap(),
478                        ffi::VSDataTypeHint::Utf8,
479                        append,
480                    )),
481                    Value::VideoNode(val) => {
482                        self.set_internal(self.api.mapSetNode, key, val.as_ptr(), append)
483                    }
484                    Value::AudioNode(val) => {
485                        self.set_internal(self.api.mapSetNode, key, val.as_ptr(), append)
486                    }
487                    Value::VideoFrame(val) => {
488                        self.set_internal(self.api.mapSetFrame, key, val.as_ptr(), append)
489                    }
490                    Value::AudioFrame(val) => {
491                        self.set_internal(self.api.mapSetFrame, key, val.as_ptr(), append)
492                    }
493                    Value::Function(val) => {
494                        self.set_internal(self.api.mapSetFunction, key, val.as_ptr(), append)
495                    }
496                }
497            }
498        }
499
500        /// # Errors
501        ///
502        /// Return [`MapPropertyError`] if the underlying API does not success
503        ///
504        /// # Panics
505        ///
506        /// Panic if the `val.len()` is larger than [`i32::MAX`]
507        pub fn set_int_array(&mut self, key: &KeyStr, val: &[i64]) -> Result<(), MapPropertyError> {
508            unsafe {
509                handle_set_error((self.api.mapSetIntArray)(
510                    self.as_ptr(),
511                    key.as_ptr(),
512                    val.as_ptr(),
513                    val.len().try_into().unwrap(),
514                ))
515            }
516        }
517
518        /// # Errors
519        ///
520        /// Return [`MapPropertyError`] if the underlying API does not success
521        ///
522        /// # Panics
523        ///
524        /// Panic if the `val.len()` is larger than [`i32::MAX`]
525        pub fn set_float_array(
526            &mut self,
527            key: &KeyStr,
528            val: &[f64],
529        ) -> Result<(), MapPropertyError> {
530            unsafe {
531                handle_set_error((self.api.mapSetFloatArray)(
532                    self.as_ptr(),
533                    key.as_ptr(),
534                    val.as_ptr(),
535                    val.len().try_into().unwrap(),
536                ))
537            }
538        }
539
540        /// # Errors
541        ///
542        /// Return [`MapPropertyError`] if the underlying API does not success
543        pub fn consume_node(
544            &mut self,
545            key: &KeyStr,
546            node: impl Node,
547            append: AppendMode,
548        ) -> Result<(), MapPropertyError> {
549            let node = ManuallyDrop::new(node);
550            unsafe {
551                handle_set_error((self.api.mapConsumeNode)(
552                    self.as_ptr(),
553                    key.as_ptr(),
554                    node.as_ptr(),
555                    append,
556                ))
557            }
558        }
559
560        /// # Errors
561        ///
562        /// Return [`MapPropertyError`] if the underlying API does not success
563        pub fn consume_frame(
564            &mut self,
565            key: &KeyStr,
566            frame: impl Frame,
567            append: AppendMode,
568        ) -> Result<(), MapPropertyError> {
569            let frame = ManuallyDrop::new(frame);
570            unsafe {
571                handle_set_error((self.api.mapConsumeFrame)(
572                    self.as_ptr(),
573                    key.as_ptr(),
574                    frame.as_ptr(),
575                    append,
576                ))
577            }
578        }
579
580        /// # Errors
581        ///
582        /// Return [`MapPropertyError`] if the underlying API does not success
583        pub fn consume_function(
584            &mut self,
585            key: &KeyStr,
586            function: Function,
587            append: AppendMode,
588        ) -> Result<(), MapPropertyError> {
589            let function = ManuallyDrop::new(function);
590            unsafe {
591                handle_set_error((self.api.mapConsumeFunction)(
592                    self.as_ptr(),
593                    key.as_ptr(),
594                    function.as_ptr(),
595                    append,
596                ))
597            }
598        }
599    };
600}
601
602impl MapRef<'_> {
603    map_read_methods!();
604}
605
606impl MapMut<'_> {
607    map_read_methods!();
608    map_write_methods!();
609}
610
611impl Map {
612    map_read_methods!();
613    map_write_methods!();
614
615    #[must_use]
616    pub fn as_ref(&self) -> MapRef<'_> {
617        unsafe { MapRef::from_ptr(self.handle, self.api) }
618    }
619
620    #[must_use]
621    pub fn as_mut(&mut self) -> MapMut<'_> {
622        unsafe { MapMut::from_ptr(self.as_ptr(), self.api) }
623    }
624}
625
626impl Drop for Map {
627    fn drop(&mut self) {
628        // safety: `self.handle` is a valid pointer
629        unsafe { (self.api.freeMap)(self.as_ptr()) }
630    }
631}
632
633impl Clone for Map {
634    fn clone(&self) -> Self {
635        // safety: `self` and `map` are both valid
636        unsafe {
637            let ptr = (self.api.createMap)();
638            (self.api.copyMap)(self.as_ptr(), ptr);
639            Self::from_ptr(ptr, self.api)
640        }
641    }
642}
643
644#[cfg(feature = "link-vs")]
645impl Default for Map {
646    fn default() -> Self {
647        unsafe {
648            let api = Api::default();
649            let ptr = (api.createMap)();
650            Self::from_ptr(ptr, api)
651        }
652    }
653}
654
655// MARK: Helper
656
657fn handle_get_error<T>(res: T, error: ffi::VSMapPropertyError) -> Result<T, MapPropertyError> {
658    use MapPropertyError as pe;
659    use ffi::VSMapPropertyError as e;
660
661    match error {
662        e::Success => Ok(res),
663        e::Unset => Err(pe::KeyNotFound),
664        e::Type => Err(pe::InvalidType),
665        e::Index => Err(pe::IndexOutOfBound),
666        e::Error => Err(pe::MapError),
667    }
668}
669
670fn handle_set_error(res: i32) -> Result<(), MapPropertyError> {
671    if res == 0 {
672        Ok(())
673    } else {
674        Err(MapPropertyError::InvalidType)
675    }
676}
677
678// MARK: Types
679
680#[derive(Clone, Debug)]
681pub enum Value<'m> {
682    Int(i64),
683    Float(f64),
684    /// Arbitrary binary data
685    ///
686    /// # Notes
687    ///
688    /// Could still be UTF-8 strings because of the API3 compatibility
689    Data(&'m [u8]),
690    Utf8(&'m str),
691    VideoNode(VideoNode),
692    AudioNode(AudioNode),
693    VideoFrame(VideoFrame),
694    AudioFrame(AudioFrame),
695    Function(Function),
696}
697
698#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Error)]
699pub enum MapPropertyError {
700    #[error("The requested key was not found in the map")]
701    KeyNotFound,
702    #[error("The wrong function was used to retrieve the property")]
703    InvalidType,
704    #[error("The requested index was out of bound")]
705    IndexOutOfBound,
706    #[error("The map has errors. Use [`Map::get_error`] to retrieve the message")]
707    MapError,
708}
709
710pub type AppendMode = ffi::VSMapAppendMode;
711
712// MARK: Tests
713
714#[cfg(test)]
715#[cfg(feature = "link-vs")]
716mod tests {
717    use core::panic;
718
719    use const_str::cstr;
720    use testresult::TestResult;
721
722    use super::*;
723
724    #[test]
725    fn typed_empty_arrays_and_property_errors() {
726        let mut map = Map::default();
727        let key = crate::key!(c"items");
728        assert_eq!(map.get_int(key, 0), Err(MapPropertyError::KeyNotFound));
729        map.as_mut().set_empty(key, ffi::VSPropertyType::Int);
730        assert_eq!(map.num_elements(key), Some(0));
731        assert_eq!(
732            map.get_int_array(key),
733            Err(MapPropertyError::IndexOutOfBound)
734        );
735        assert_eq!(map.get_int(key, 0), Err(MapPropertyError::IndexOutOfBound));
736        map.set_int_array(key, &[42]).unwrap();
737        assert_eq!(map.get_float(key, 0), Err(MapPropertyError::InvalidType));
738    }
739
740    #[test]
741    fn utf8_hint_does_not_guarantee_valid_utf8() {
742        let map = Map::default();
743        let key = crate::key!(c"data");
744        let bytes = [0xff_u8];
745        let status = unsafe {
746            (map.api.mapSetData)(
747                map.as_ptr(),
748                key.as_ptr(),
749                bytes.as_ptr().cast(),
750                1,
751                ffi::VSDataTypeHint::Utf8,
752                AppendMode::Replace,
753            )
754        };
755        assert_eq!(status, 0);
756        assert_eq!(map.get_utf8(key, 0), Err(MapPropertyError::InvalidType));
757        assert!(matches!(
758            map.get(key, 0),
759            Err(MapPropertyError::InvalidType)
760        ));
761    }
762
763    #[test]
764    #[allow(clippy::float_cmp)]
765    fn scalar_views_return_values_and_validate_data_hints() -> TestResult {
766        let mut map = Map::default();
767        let mut writable = map.as_mut();
768        assert!(writable.is_empty());
769        let int = crate::key!(c"i");
770        let float = crate::key!(c"f");
771        let bytes = crate::key!(c"b");
772        let text = crate::key!(c"s");
773        writable.set_int_array(int, &[1, 2])?;
774        writable.set_float_array(float, &[1.25, 2.5])?;
775        writable.set(bytes, Value::Data(b"bytes"), AppendMode::Replace)?;
776        writable.set(text, Value::Utf8("a\0b"), AppendMode::Replace)?;
777
778        macro_rules! check {
779            ($view:expr) => {{
780                let view = $view;
781                assert_eq!(view.len(), 4);
782                assert_eq!(view.get_key(0), bytes);
783                assert_eq!(view.num_elements(int), Some(2));
784                assert_eq!(view.get_int_array(int)?, &[1, 2]);
785                assert_eq!(view.get_int_saturated(int, 1)?, 2);
786                assert!(matches!(view.get(int, 0)?, Value::Int(1)));
787                assert_eq!(view.get_float_array(float)?, &[1.25, 2.5]);
788                assert_eq!(view.get_float_saturated(float, 1)?, 2.5);
789                assert!(matches!(view.get(float, 0)?, Value::Float(1.25)));
790                assert_eq!(view.get_binary(bytes, 0)?, b"bytes");
791                assert!(matches!(view.get(bytes, 0)?, Value::Data(b"bytes")));
792                assert_eq!(view.get_utf8(text, 0)?, "a\0b");
793                assert!(matches!(view.get(text, 0)?, Value::Utf8("a\0b")));
794                assert_eq!(view.get_binary(text, 0), Err(MapPropertyError::InvalidType));
795                assert_eq!(view.get_utf8(bytes, 0), Err(MapPropertyError::InvalidType));
796            }};
797        }
798
799        check!(&writable);
800        check!(writable.as_ref());
801        assert_eq!(writable.get_error(), None);
802        writable.delete_key(int);
803        assert_eq!(writable.num_elements(int), None);
804        writable.set_error(c"failed");
805        assert_eq!(writable.as_ref().get_error(), Some(c"failed"));
806        writable.clear();
807        assert!(writable.as_ref().is_empty());
808        Ok(())
809    }
810
811    #[test]
812    fn borrowed_views() -> TestResult {
813        let mut map = Map::default();
814        let key = crate::key!(c"values");
815        {
816            let mut view = map.as_mut();
817            view.reborrow().set_int_array(key, &[1, 2, 3])?;
818            assert_eq!(view.as_ref().get_int_array(key)?, &[1, 2, 3]);
819        }
820        let view = map.as_ref();
821        let copy = view;
822        assert_eq!(copy.get_int_array(key)?, &[1, 2, 3]);
823        let owned = map.clone();
824        map.as_mut().clear();
825        assert!(map.is_empty());
826        drop(map);
827        assert_eq!(owned.get_int_array(key)?, &[1, 2, 3]);
828        Ok(())
829    }
830
831    #[test]
832    fn clear() -> TestResult {
833        let mut map = Map::default();
834        let key = crate::key!(c"what");
835        map.set(key, Value::Int(42), AppendMode::Replace)?;
836
837        map.clear();
838        match map.get(key, 0) {
839            Err(MapPropertyError::KeyNotFound) => Ok(()),
840            _ => panic!("Map is not cleared"),
841        }
842    }
843
844    #[test]
845    fn error() -> TestResult {
846        let mut map = Map::default();
847        let key = crate::key!(c"what");
848        map.set(key, Value::Float(42.0), AppendMode::Replace)?;
849
850        map.set_error(cstr!("Yes"));
851        match map.get_error() {
852            Some(msg) => assert_eq!(msg, cstr!("Yes"), "Error message is not match"),
853            None => panic!("Error is not set"),
854        }
855        let res = map.get(key, 0);
856        match res {
857            Err(MapPropertyError::KeyNotFound) => {}
858            _ => panic!("Map is not cleared after setting error"),
859        }
860
861        map.set(key, Value::Float(42.0), AppendMode::Replace)?;
862        let res = map.get(key, 0);
863        match res {
864            Err(MapPropertyError::MapError) => {}
865            _ => panic!(
866                "Map after setting error can only be freed, \
867                cleared, or queried for error"
868            ),
869        }
870
871        Ok(())
872    }
873
874    #[test]
875    fn len() -> TestResult {
876        let mut map = Map::default();
877        let key = crate::key!(c"what");
878
879        map.set(key, Value::Data(&[42, 43, 44, 45]), AppendMode::Replace)?;
880        assert_eq!(1, map.len(), "Number of keys is not correct");
881
882        assert!(!map.is_empty(), "Map is not empty");
883
884        Ok(())
885    }
886
887    #[test]
888    fn key() -> TestResult {
889        let mut map = Map::default();
890        let key = crate::key!(c"what");
891
892        map.set(key, Value::Float(42.0), AppendMode::Append)?;
893
894        assert_eq!(key, map.get_key(0), "Key is not correct");
895
896        match map.num_elements(key) {
897            Some(num) => assert_eq!(1, num),
898            None => panic!("Key `{key}` not found "),
899        }
900
901        map.delete_key(key);
902        assert_eq!(
903            0,
904            map.len(),
905            "Number of keys is not correct after deleting `{key}`"
906        );
907
908        Ok(())
909    }
910
911    #[test]
912    #[allow(clippy::float_cmp)]
913    fn get_set() -> TestResult {
914        let mut map = Map::default();
915        macro_rules! check_values {
916            ($map:ident) => {{
917                let key = crate::key!(c"what");
918                let source = i64::from(i32::MAX) + 1;
919                $map.set(key, Value::Int(source), AppendMode::Replace)?;
920                let res = $map.get(key, 0)?;
921                match res {
922                    Value::Int(val) => assert_eq!(val, source, "Value of `{key}` is not correct"),
923                    _ => panic!("Invalid type of `{key}`"),
924                }
925                let res = $map.get_int_saturated(key, 0)?;
926                assert_eq!(res, i32::MAX, "Value of `{key}` is not correct");
927                $map.set(key, Value::Int(source), AppendMode::Append)?;
928                assert_eq!(&[source, source], $map.get_int_array(key)?);
929                $map.set_int_array(key, &[1, 2, 3])?;
930                assert_eq!(&[1, 2, 3], $map.get_int_array(key)?);
931                $map.set(key, Value::Float(1e25), AppendMode::Replace)?;
932                let res = $map.get(key, 0)?;
933                match res {
934                    Value::Float(val) => {
935                        assert_eq!(val, 1e25, "Value of `{key}` is not correct");
936                    }
937                    _ => panic!("Invalid type of `{key}`"),
938                }
939                let res = $map.get_float_saturated(key, 0)?;
940                assert_eq!(
941                    res, 9_999_999_562_023_526_247_432_192.0,
942                    "Value of `{key}` is not correct"
943                );
944                $map.set(key, Value::Float(f64::MAX), AppendMode::Append)?;
945                assert_eq!(&[1e25, f64::MAX], $map.get_float_array(key)?);
946                $map.set_float_array(key, &[1.0, 2.0, 3.0])?;
947                assert_eq!(&[1.0, 2.0, 3.0], $map.get_float_array(key)?);
948                $map.set(key, Value::Data(&[42, 43]), AppendMode::Replace)?;
949                let res = $map.get(key, 0)?;
950                match res {
951                    Value::Data(val) => {
952                        assert_eq!(val, &[42, 43], "Value of `{key}` is not correct");
953                    }
954                    _ => panic!("Invalid type of `{key}`"),
955                }
956                $map.set(key, Value::Utf8("good"), AppendMode::Replace)?;
957                let res = $map.get(key, 0)?;
958                match res {
959                    Value::Utf8(val) => {
960                        assert_eq!(val, "good", "Value of `{key}` is not correct");
961                    }
962                    _ => panic!("Invalid type of `{key}`"),
963                }
964            }};
965        }
966
967        check_values!(map);
968        let mut view = map.as_mut();
969        check_values!(view);
970
971        Ok(())
972    }
973}