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
use crate::*;

use std::marker::PhantomData;
use std::os::raw::c_char;

/// DB wraps the libimaged's `Imaged` type
pub struct DB(*mut sys::Imaged);

impl Drop for DB {
    fn drop(&mut self) {
        unsafe { sys::imagedClose(self.0) }
    }
}

/// Handle wraps the `ImagedHandle` type
pub struct Handle<'a>(sys::ImagedHandle, &'a DB);

impl<'a> Drop for Handle<'a> {
    fn drop(&mut self) {
        unsafe { sys::imagedHandleClose(&mut self.0) }
    }
}

impl<'a> Handle<'a> {
    /// Get the underlying image
    pub fn image(&mut self) -> Image {
        Image(&mut self.0.image, false, PhantomData)
    }
}

impl DB {
    /// Open an imaged instance at the given path
    pub fn open<P: AsRef<std::path::Path>>(path: P) -> Result<Self, Error> {
        let path = path.as_ref();
        let path = match path.to_str() {
            Some(x) => x,
            None => return Err(Error::InvalidPath),
        };

        let path = match std::ffi::CString::new(path) {
            Ok(x) => x,
            Err(_) => return Err(Error::InvalidPath),
        };

        let db = unsafe { sys::imagedOpen(path.as_ptr()) };
        if db.is_null() {
            return Err(Error::CannotOpenDB);
        }

        Ok(DB(db))
    }

    /// Destroy all imgd files at the DB's root
    pub fn destroy(self) -> Result<(), Error> {
        let rc = unsafe { sys::imagedDestroy(self.0) };
        if rc != sys::ImagedStatus::IMAGED_OK {
            return Err(Error::Sys(rc));
        }
        Ok(())
    }

    /// Returns a new image iterator
    pub fn iter(&self) -> Result<Iter, Error> {
        let iter = unsafe { sys::imagedIterNew(self.0) };
        if iter.is_null() {
            return Err(Error::NullPointer);
        }

        Ok(Iter(iter, self))
    }

    /// Returns a new key iterator
    pub fn iter_keys(&self) -> Result<KeyIter, Error> {
        let iter = unsafe { sys::imagedIterNew(self.0) };
        if iter.is_null() {
            return Err(Error::NullPointer);
        }

        Ok(KeyIter(iter, self))
    }

    /// Get a key, `editable` determines whether or not the pixels can be edited
    pub fn get<S: AsRef<str>>(&self, key: S, editable: bool) -> Result<Handle, Error> {
        let mut handle = unsafe { std::mem::zeroed() };
        let rc = unsafe {
            sys::imagedGet(
                self.0,
                key.as_ref().as_ptr() as *const c_char,
                key.as_ref().len() as isize,
                editable,
                &mut handle,
            )
        };
        if rc != sys::ImagedStatus::IMAGED_OK {
            return Err(Error::Sys(rc));
        }

        Ok(Handle(handle, self))
    }

    /// Check if a key is in use
    pub fn is_locked(&self, key: &str) -> bool {
        unsafe { sys::imagedKeyIsLocked(self.0, key.as_ptr() as *const c_char, key.len() as isize) }
    }

    /// Check if a key is a valid imgd file
    pub fn file_is_valid(&self, key: &str) -> bool {
        unsafe { sys::imagedIsValidFile(self.0, key.as_ptr() as *const c_char, key.len() as isize) }
    }

    /// Set a key
    pub fn set<'a, S: AsRef<str>>(&'a self, key: S, image: &Image) -> Result<Handle<'a>, Error> {
        self.set_raw(key, image.meta().clone(), Some(image.data_ptr()))
    }

    /// Set a key using metadata and a pointer to the image data
    pub fn set_raw<S: AsRef<str>>(
        &self,
        key: S,
        meta: Meta,
        data: Option<*const c_void>,
    ) -> Result<Handle, Error> {
        let mut handle = unsafe { std::mem::zeroed() };
        let rc = unsafe {
            sys::imagedSet(
                self.0,
                key.as_ref().as_ptr() as *const c_char,
                key.as_ref().len() as isize,
                &meta,
                data.unwrap_or(std::ptr::null()),
                &mut handle,
            )
        };
        if rc != sys::ImagedStatus::IMAGED_OK {
            return Err(Error::Sys(rc));
        }

        Ok(Handle(handle, self))
    }

    /// Remove a key
    pub fn remove<S: AsRef<str>>(&self, key: S) -> Result<(), Error> {
        let rc = unsafe {
            sys::imagedRemove(
                self.0,
                key.as_ref().as_ptr() as *const c_char,
                key.as_ref().len() as isize,
            )
        };
        if rc != sys::ImagedStatus::IMAGED_OK {
            return Err(Error::Sys(rc));
        }

        Ok(())
    }
}