collenchyma/frameworks/opencl/
memory.rs

1#![allow(missing_docs)]
2use super::api::types as cl;
3use super::api::{API, Error};
4use super::Context;
5use memory::*;
6
7use std::{ptr, fmt};
8
9/// Holds a OpenCL memory id and manages its deallocation
10pub struct Memory {
11    /// The underlying memory id>
12    memory: cl::memory_id,
13    memory_flags: MemoryFlags,
14
15    /// Pointer to host memory that is used for pinned host memory.
16    host_ptr: *mut u8,
17}
18
19impl fmt::Debug for Memory {
20    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
21        write!(f, "Memory({:?}, {:?})", self.memory, self.memory_flags)
22    }
23}
24
25impl Drop for Memory {
26    #[allow(unused_must_use)]
27    fn drop(&mut self) {
28        API::release_memory(self);
29        if self.memory_flags.contains(MEM_USE_HOST_PTR) {
30            unsafe {
31                Box::from_raw(self.host_ptr);
32            }
33        }
34    }
35}
36
37bitflags! {
38    flags MemoryFlags: cl::bitfield {
39        const MEM_READ_WRITE       = 1 << 0,
40        const MEM_WRITE_ONLY       = 1 << 1,
41        const MEM_READ_ONLY        = 1 << 2,
42        const MEM_USE_HOST_PTR     = 1 << 3,
43        const MEM_ALLOC_HOST_PTR   = 1 << 4,
44        const MEM_COPY_HOST_PTR    = 1 << 5,
45    }
46}
47
48impl Default for MemoryFlags {
49    fn default() -> MemoryFlags {
50        MEM_READ_WRITE
51    }
52}
53
54#[allow(unused_mut)]
55impl Memory {
56    pub fn new(context: &Context, size: usize) -> Result<Memory, Error> {
57        API::create_buffer(context, MemoryFlags::default(), size, None)
58    }
59
60    pub fn id_c(&self) -> cl::memory_id {
61        self.memory
62    }
63
64    pub fn from_c(id: cl::memory_id) -> Memory {
65        Memory {
66            memory: id,
67            memory_flags: MemoryFlags::default(),
68            host_ptr: ptr::null_mut(),
69        }
70    }
71}
72
73impl IMemory for Memory {}