2019-08-27 09:36:16 +07:00
|
|
|
use std::os::raw::c_void;
|
|
|
|
|
|
|
|
|
|
extern "C" {
|
2020-12-02 13:17:13 -08:00
|
|
|
/// Normally, use `free(1)` to free memory allocated from C.
|
|
|
|
|
#[cfg(not(feature = "allocation-tracking"))]
|
2019-11-14 13:34:21 -08:00
|
|
|
#[link_name = "free"]
|
2019-08-27 09:36:16 +07:00
|
|
|
pub fn free_ptr(ptr: *mut c_void);
|
2019-11-14 13:34:21 -08:00
|
|
|
|
2020-12-02 13:17:13 -08:00
|
|
|
/// When the `allocation-tracking` feature is enabled, the C library is compiled with
|
|
|
|
|
/// the `TREE_SITTER_TEST` macro, so all calls to `malloc`, `free`, etc are linked
|
|
|
|
|
/// against wrapper functions called `ts_record_malloc`, `ts_record_free`, etc.
|
|
|
|
|
/// When freeing buffers allocated from C, use the wrapper `free` function.
|
|
|
|
|
#[cfg(feature = "allocation-tracking")]
|
2019-11-14 13:34:21 -08:00
|
|
|
#[link_name = "ts_record_free"]
|
|
|
|
|
pub fn free_ptr(ptr: *mut c_void);
|
|
|
|
|
|
2019-08-27 09:36:16 +07:00
|
|
|
}
|
|
|
|
|
|
2020-12-02 13:17:13 -08:00
|
|
|
/// A raw pointer and a length, exposed as an iterator.
|
2019-08-27 09:36:16 +07:00
|
|
|
pub struct CBufferIter<T> {
|
|
|
|
|
ptr: *mut T,
|
|
|
|
|
count: usize,
|
|
|
|
|
i: usize,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl<T> CBufferIter<T> {
|
|
|
|
|
pub unsafe fn new(ptr: *mut T, count: usize) -> Self {
|
|
|
|
|
Self { ptr, count, i: 0 }
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl<T: Copy> Iterator for CBufferIter<T> {
|
|
|
|
|
type Item = T;
|
|
|
|
|
|
|
|
|
|
fn next(&mut self) -> Option<Self::Item> {
|
|
|
|
|
let i = self.i;
|
|
|
|
|
if i >= self.count {
|
|
|
|
|
None
|
|
|
|
|
} else {
|
2019-08-28 23:28:47 +07:00
|
|
|
self.i += 1;
|
2019-08-27 09:36:16 +07:00
|
|
|
Some(unsafe { *self.ptr.offset(i as isize) })
|
|
|
|
|
}
|
|
|
|
|
}
|
2019-08-28 23:28:47 +07:00
|
|
|
|
|
|
|
|
fn size_hint(&self) -> (usize, Option<usize>) {
|
|
|
|
|
let remaining = self.count - self.i;
|
|
|
|
|
(remaining, Some(remaining))
|
|
|
|
|
}
|
2019-08-27 09:36:16 +07:00
|
|
|
}
|
|
|
|
|
|
2019-08-28 23:28:47 +07:00
|
|
|
impl<T: Copy> ExactSizeIterator for CBufferIter<T> {}
|
|
|
|
|
|
2019-08-27 09:36:16 +07:00
|
|
|
impl<T> Drop for CBufferIter<T> {
|
|
|
|
|
fn drop(&mut self) {
|
2019-11-14 13:34:21 -08:00
|
|
|
unsafe {
|
|
|
|
|
free_ptr(self.ptr as *mut c_void);
|
|
|
|
|
}
|
2019-08-27 09:36:16 +07:00
|
|
|
}
|
|
|
|
|
}
|