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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
//! Assets
//!
//! See also [the NDK docs](https://developer.android.com/ndk/reference/group/asset)

use std::ffi::{CStr, CString};
use std::io;
use std::ptr::NonNull;

/// A native `AAssetManager *`.
#[derive(Debug)]
pub struct AssetManager {
    ptr: NonNull<ffi::AAssetManager>,
}

// AAssetManager is thread safe.
// See https://developer.android.com/ndk/reference/group/asset#aassetmanager
unsafe impl Send for AssetManager {}
unsafe impl Sync for AssetManager {}

impl AssetManager {
    /// Create an `AssetManager` from a pointer
    ///
    /// By calling this function, you assert that the pointer is a valid pointer to a native
    /// `AAssetManager`.
    pub unsafe fn from_ptr(ptr: NonNull<ffi::AAssetManager>) -> Self {
        Self { ptr }
    }

    /// Returns the pointer to the native `AAssetManager`.
    pub fn ptr(&self) -> NonNull<ffi::AAssetManager> {
        self.ptr
    }

    /// Open the asset. Returns `None` if opening the asset fails.
    ///
    /// This currently always opens the asset in the streaming mode.
    pub fn open(&self, filename: &CStr) -> Option<Asset> {
        unsafe {
            let ptr = ffi::AAssetManager_open(
                self.ptr.as_ptr(),
                filename.as_ptr(),
                ffi::AASSET_MODE_STREAMING as i32,
            );
            Some(Asset::from_ptr(NonNull::new(ptr)?))
        }
    }

    /// Open an asset directory. Returns `None` if opening the directory fails.
    pub fn open_dir(&self, filename: &CStr) -> Option<AssetDir> {
        unsafe {
            let ptr = ffi::AAssetManager_openDir(self.ptr.as_ptr(), filename.as_ptr());
            Some(AssetDir::from_ptr(NonNull::new(ptr)?))
        }
    }
}

/// A native `AAssetDir *`.
///
/// ```no_run
/// # use std::ffi::CString;
/// # use ndk::asset::AssetManager;
/// # let asset_manager: AssetManager = unimplemented!();
/// use std::io::Read;
///
/// let mut my_dir = asset_manager
///     .open_dir(&CString::new("my_dir").unwrap())
///     .expect("Could not open directory");
///
/// // Use it as an iterator
/// let all_files = my_dir.collect::<Vec<CString>>();
///
/// // Reset the iterator
/// my_dir.rewind();
///
/// // Use .with_next() to iterate without allocating `CString`s
/// while let Some(asset) = my_dir.with_next(|cstr| asset_manager.open(cstr).unwrap()) {
///     let mut text = String::new();
///     asset.read_to_string(&mut text);
///     // ...
/// }
/// ```
#[derive(Debug)]
pub struct AssetDir {
    ptr: NonNull<ffi::AAssetDir>,
}

// It's unclear if AAssetDir is thread safe.
// However, AAsset is not, so there's a good chance that AAssetDir is not either.

impl Drop for AssetDir {
    fn drop(&mut self) {
        unsafe { ffi::AAssetDir_close(self.ptr.as_ptr()) }
    }
}

impl AssetDir {
    /// Construct an `AssetDir` from the native `AAssetDir *`.  This gives ownership of the
    /// `AAssetDir *` to the `AssetDir`, which will handle closing the asset.  Avoid using
    /// the pointer after calling this function.
    ///
    /// By calling this function, you assert that it points to a valid native `AAssetDir`.
    pub unsafe fn from_ptr(ptr: NonNull<ffi::AAssetDir>) -> Self {
        Self { ptr }
    }

    /// The corresponding native `AAssetDir *`
    pub fn ptr(&self) -> NonNull<ffi::AAssetDir> {
        self.ptr
    }

    /// Get the next filename, if any, and process it.  Like `.next()`, but performs no additional
    /// allocation.
    ///
    /// The filenames are in the correct format to be passed to `AssetManager::open`
    pub fn with_next<T>(&mut self, f: impl for<'a> FnOnce(&'a CStr) -> T) -> Option<T> {
        unsafe {
            let next_name = ffi::AAssetDir_getNextFileName(self.ptr.as_ptr());
            if next_name.is_null() {
                None
            } else {
                Some(f(CStr::from_ptr(next_name)))
            }
        }
    }

    /// Reset the iteration state
    pub fn rewind(&mut self) {
        unsafe {
            ffi::AAssetDir_rewind(self.ptr.as_ptr());
        }
    }
}

impl Iterator for AssetDir {
    type Item = CString;

    fn next(&mut self) -> Option<CString> {
        self.with_next(|cstr| cstr.to_owned())
    }
}

/// A native `AAsset *`, open in the streaming mode
///
/// ```no_run
/// # use std::ffi::CString;
/// # use ndk::asset::AssetManager;
/// # let asset_manager: AssetManager = unimplemented!();
/// use std::io::Read;
///
/// let asset = asset_manager
///     .open(&CString::new("path/to/asset").unwrap())
///     .expect("Could not open asset");
///
/// let mut data = vec![];
/// asset.read_to_end(&mut data);
/// // ... use data ...
/// ```
#[derive(Debug)]
pub struct Asset {
    ptr: NonNull<ffi::AAsset>,
}

// AAsset is *not* thread safe.
// See https://developer.android.com/ndk/reference/group/asset#aasset

impl Drop for Asset {
    fn drop(&mut self) {
        unsafe { ffi::AAsset_close(self.ptr.as_ptr()) }
    }
}

impl Asset {
    /// Construct an `Asset` from the native `AAsset *`.  This gives ownership of the `AAsset *` to
    /// the `Asset`, which will handle closing the asset.  Avoid using the pointer after calling
    /// this function.
    ///
    /// By calling this function, you assert that it points to a valid native `AAsset`, open
    /// in the streaming mode.
    pub unsafe fn from_ptr(ptr: NonNull<ffi::AAsset>) -> Self {
        Self { ptr }
    }

    /// The corresponding native `AAsset *`
    pub fn ptr(&self) -> NonNull<ffi::AAsset> {
        self.ptr
    }

    /// Returns the total length of the asset, in bytes
    pub fn get_length(&self) -> usize {
        unsafe { ffi::AAsset_getLength64(self.ptr.as_ptr()) as usize }
    }

    /// Returns the remaining length of the asset, in bytes
    pub fn get_remaining_length(&self) -> usize {
        unsafe { ffi::AAsset_getRemainingLength64(self.ptr.as_ptr()) as usize }
    }

    /// Reads all data into a buffer and returns it
    pub fn get_buffer(&mut self) -> io::Result<&[u8]> {
        unsafe {
            let buf_ptr = ffi::AAsset_getBuffer(self.ptr.as_ptr());
            if buf_ptr.is_null() {
                Err(io::Error::new(
                    io::ErrorKind::Other,
                    "Android Asset error creating buffer",
                ))
            } else {
                Ok(std::slice::from_raw_parts(
                    buf_ptr as *const u8,
                    self.get_remaining_length(),
                ))
            }
        }
    }

    //pub fn open_file_descriptor(&self) -> TODO
}

impl io::Read for Asset {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        unsafe {
            let res = ffi::AAsset_read(
                self.ptr.as_ptr(),
                buf.as_mut_ptr() as *mut _,
                buf.len() as ffi::size_t,
            );
            if res >= 0 {
                Ok(res as usize)
            } else {
                Err(io::Error::new(
                    io::ErrorKind::Other,
                    "Android Asset read error",
                ))
            }
        }
    }
}

impl io::Seek for Asset {
    fn seek(&mut self, seek: io::SeekFrom) -> io::Result<u64> {
        unsafe {
            let res = match seek {
                io::SeekFrom::Start(x) => {
                    ffi::AAsset_seek64(self.ptr.as_ptr(), x as i64, ffi::SEEK_SET as i32)
                }
                io::SeekFrom::Current(x) => {
                    ffi::AAsset_seek64(self.ptr.as_ptr(), x, ffi::SEEK_CUR as i32)
                }
                io::SeekFrom::End(x) => {
                    ffi::AAsset_seek64(self.ptr.as_ptr(), x, ffi::SEEK_END as i32)
                }
            };
            if res < 0 {
                Err(io::Error::new(
                    io::ErrorKind::Other,
                    "Android Asset seek error",
                ))
            } else {
                Ok(res as u64)
            }
        }
    }
}