Skip to main content

ffmpeg_the_third/util/dictionary/
owned.rs

1use std::fmt;
2use std::ptr;
3
4use libc::c_int;
5
6use crate::ffi::*;
7use crate::{AsMutPtr, AsPtr};
8
9use super::flag::Flags;
10use super::{DictionaryMut, DictionaryRef};
11
12pub struct Dictionary {
13    ptr: *mut AVDictionary,
14}
15
16impl Default for Dictionary {
17    fn default() -> Self {
18        Self::new()
19    }
20}
21
22impl Dictionary {
23    pub unsafe fn from_raw(ptr: *mut AVDictionary) -> Self {
24        Self { ptr }
25    }
26
27    pub fn into_raw(mut self) -> *mut AVDictionary {
28        let result = self.ptr;
29        self.ptr = ptr::null_mut();
30
31        result
32    }
33
34    pub fn replace_with(&mut self, new: Self) {
35        unsafe { av_dict_free(&mut self.ptr) };
36        self.ptr = new.into_raw();
37    }
38
39    pub fn as_ptr(&self) -> *const AVDictionary {
40        self.ptr
41    }
42
43    pub fn as_mut_ptr(&mut self) -> &mut *mut AVDictionary {
44        &mut self.ptr
45    }
46
47    pub fn as_ref(&self) -> DictionaryRef<'_> {
48        unsafe { DictionaryRef::from_raw(self.as_ptr()) }
49    }
50
51    pub fn as_mut(&mut self) -> DictionaryMut<'_> {
52        unsafe { DictionaryMut::from_raw(self.as_mut_ptr()) }
53    }
54}
55
56impl Dictionary {
57    pub fn new() -> Self {
58        Self {
59            ptr: ptr::null_mut(),
60        }
61    }
62}
63
64impl<S, U> FromIterator<(S, U)> for Dictionary
65where
66    S: AsRef<str>,
67    U: AsRef<str>,
68{
69    fn from_iter<T: IntoIterator<Item = (S, U)>>(iter: T) -> Self {
70        let mut result = Dictionary::new();
71
72        for (key, value) in iter {
73            result.set(key.as_ref(), value.as_ref())
74        }
75
76        result
77    }
78}
79
80impl Clone for Dictionary {
81    fn clone(&self) -> Self {
82        let mut dictionary = Dictionary::new();
83        dictionary.clone_from(self);
84
85        dictionary
86    }
87
88    fn clone_from(&mut self, source: &Self) {
89        unsafe {
90            av_dict_copy(
91                &mut self.ptr,
92                source.as_ptr(),
93                Flags::MULTIKEY.bits() as c_int,
94            );
95        }
96    }
97}
98
99impl Drop for Dictionary {
100    fn drop(&mut self) {
101        unsafe {
102            av_dict_free(&mut self.ptr);
103        }
104    }
105}
106
107impl fmt::Debug for Dictionary {
108    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
109        self.as_ref().fmt(fmt)
110    }
111}
112
113impl AsPtr<AVDictionary> for Dictionary {
114    fn as_ptr(&self) -> *const AVDictionary {
115        self.ptr
116    }
117}
118
119// *mut *mut because this is the common way for FFmpeg APIs to accept
120// a Dictionary reference (empty Dictionaries use an internal nullptr).
121impl AsMutPtr<*mut AVDictionary> for Dictionary {
122    fn as_mut_ptr(&mut self) -> *mut *mut AVDictionary {
123        &mut self.ptr
124    }
125}