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
// Take a look at the license at the top of the repository in the LICENSE file.

use std::ptr;

use glib::{bool_error, prelude::*, subclass::prelude::*, translate::*, BoolError};

use super::prelude::*;
use crate::{ffi, AllocationParams, Allocator, Memory};

pub trait AllocatorImpl: AllocatorImplExt + GstObjectImpl + Send + Sync {
    /// Use `self` to allocate a new memory block with memory that is at least
    /// `size` big.
    ///
    /// The optional `params` can specify the prefix and padding for the memory. If
    /// [`None`] is passed, no flags, no extra prefix/padding and a default alignment is
    /// used.
    ///
    /// The prefix/padding will be filled with 0 if flags contains
    /// [`MemoryFlags::ZERO_PREFIXED`][crate::MemoryFlags::ZERO_PREFIXED] and [`MemoryFlags::ZERO_PADDED`][crate::MemoryFlags::ZERO_PADDED] respectively.
    ///
    /// When `self` is [`None`], the default allocator will be used.
    ///
    /// The alignment in `params` is given as a bitmask so that `align` + 1 equals
    /// the amount of bytes to align to. For example, to align to 8 bytes,
    /// use an alignment of 7.
    /// ## `size`
    /// size of the visible memory area
    /// ## `params`
    /// optional parameters
    ///
    /// # Returns
    ///
    /// a new [`Memory`][crate::Memory].
    fn alloc(&self, size: usize, params: Option<&AllocationParams>) -> Result<Memory, BoolError> {
        self.parent_alloc(size, params)
    }

    fn free(&self, memory: Memory) {
        self.parent_free(memory)
    }
}

mod sealed {
    pub trait Sealed {}
    impl<T: super::AllocatorImplExt> Sealed for T {}
}

pub trait AllocatorImplExt: sealed::Sealed + ObjectSubclass {
    fn parent_alloc(
        &self,
        size: usize,
        params: Option<&AllocationParams>,
    ) -> Result<Memory, BoolError> {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstAllocatorClass;

            if let Some(f) = (*parent_class).alloc {
                from_glib_full::<*mut ffi::GstMemory, Option<_>>(f(
                    self.obj().unsafe_cast_ref::<Allocator>().to_glib_none().0,
                    size,
                    mut_override(params.to_glib_none().0),
                ))
                .ok_or_else(|| bool_error!("Allocation failed"))
            } else {
                Err(bool_error!("No allocation method on parent class"))
            }
        }
    }

    fn parent_free(&self, memory: Memory) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstAllocatorClass;

            if let Some(f) = (*parent_class).free {
                f(
                    self.obj().unsafe_cast_ref::<Allocator>().to_glib_none().0,
                    memory.into_glib_ptr(),
                )
            }
        }
    }
}

impl<T: AllocatorImpl> AllocatorImplExt for T {}

unsafe impl<T: AllocatorImpl> IsSubclassable<T> for Allocator {
    fn class_init(klass: &mut glib::Class<Self>) {
        Self::parent_class_init::<T>(klass);
        let klass = klass.as_mut();
        klass.alloc = Some(alloc::<T>);
        klass.free = Some(free::<T>);
    }
}

unsafe extern "C" fn alloc<T: AllocatorImpl>(
    ptr: *mut ffi::GstAllocator,
    size: usize,
    params: *mut ffi::GstAllocationParams,
) -> *mut ffi::GstMemory {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();
    let instance = imp.obj();

    let params = if params.is_null() {
        None
    } else {
        Some(&*(params as *mut AllocationParams))
    };

    imp.alloc(size, params)
        .map(|memory| memory.into_glib_ptr())
        .unwrap_or_else(|error| {
            error!(crate::CAT_RUST, obj = instance, "{:?}", error);

            ptr::null_mut()
        })
}

unsafe extern "C" fn free<T: AllocatorImpl>(
    ptr: *mut ffi::GstAllocator,
    memory: *mut ffi::GstMemory,
) {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();
    let memory = from_glib_full(memory);

    imp.free(memory);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::prelude::*;

    pub mod imp {
        use super::*;

        #[derive(Default)]
        pub struct TestAllocator;

        impl ObjectImpl for TestAllocator {}
        impl GstObjectImpl for TestAllocator {}
        impl AllocatorImpl for TestAllocator {
            fn alloc(
                &self,
                size: usize,
                _params: Option<&AllocationParams>,
            ) -> Result<Memory, BoolError> {
                Ok(Memory::from_slice(vec![0; size]))
            }

            fn free(&self, memory: Memory) {
                self.parent_free(memory)
            }
        }

        #[glib::object_subclass]
        impl ObjectSubclass for TestAllocator {
            const NAME: &'static str = "TestAllocator";
            type Type = super::TestAllocator;
            type ParentType = Allocator;
        }
    }

    glib::wrapper! {
        pub struct TestAllocator(ObjectSubclass<imp::TestAllocator>) @extends Allocator, crate::Object;
    }

    impl Default for TestAllocator {
        fn default() -> Self {
            glib::Object::new()
        }
    }

    #[test]
    fn test_allocator_registration() {
        crate::init().unwrap();

        const TEST_ALLOCATOR_NAME: &str = "TestAllocator";

        let allocator = TestAllocator::default();
        Allocator::register(TEST_ALLOCATOR_NAME, allocator);

        let allocator = Allocator::find(Some(TEST_ALLOCATOR_NAME));

        assert!(allocator.is_some());
    }

    #[test]
    fn test_allocator_alloc() {
        crate::init().unwrap();

        const SIZE: usize = 1024;

        let allocator = TestAllocator::default();

        let memory = allocator.alloc(SIZE, None).unwrap();

        assert_eq!(memory.size(), SIZE);
    }
}