Skip to main content

tree_sitter/
util.rs

1use core::ffi::c_void;
2
3use super::FREE_FN;
4
5/// A raw pointer and a length, exposed as an iterator.
6pub struct CBufferIter<T> {
7    ptr: *mut T,
8    count: usize,
9    i: usize,
10}
11
12impl<T> CBufferIter<T> {
13    pub const unsafe fn new(ptr: *mut T, count: usize) -> Self {
14        Self { ptr, count, i: 0 }
15    }
16}
17
18impl<T: Copy> Iterator for CBufferIter<T> {
19    type Item = T;
20
21    fn next(&mut self) -> Option<Self::Item> {
22        let i = self.i;
23        if i >= self.count {
24            None
25        } else {
26            self.i += 1;
27            Some(unsafe { *self.ptr.add(i) })
28        }
29    }
30
31    fn size_hint(&self) -> (usize, Option<usize>) {
32        let remaining = self.count - self.i;
33        (remaining, Some(remaining))
34    }
35}
36
37impl<T: Copy> ExactSizeIterator for CBufferIter<T> {}
38
39impl<T> Drop for CBufferIter<T> {
40    fn drop(&mut self) {
41        if !self.ptr.is_null() {
42            unsafe { (FREE_FN)(self.ptr.cast::<c_void>()) };
43        }
44    }
45}