| 1 |
use std::ops::{Deref, DerefMut}; |
| 2 |
use std::ptr; |
| 3 |
use std::slice; |
| 4 |
use std::str; |
| 5 |
|
| 6 |
use crate::raw; |
| 7 |
use crate::util::Binding; |
| 8 |
use crate::Error; |
| 9 |
|
| 10 |
/// A structure to wrap an intermediate buffer used by libgit2. |
| 11 |
/// |
| 12 |
/// A buffer can be thought of a `Vec<u8>`, but the `Vec` type is not used to |
| 13 |
/// avoid copying data back and forth. |
| 14 |
pub struct Buf { |
| 15 |
raw: raw::git_buf, |
| 16 |
} |
| 17 |
|
| 18 |
impl Default for Buf { |
| 19 |
fn default() -> Self { |
| 20 |
Self::new() |
| 21 |
} |
| 22 |
} |
| 23 |
|
| 24 |
impl Buf { |
| 25 |
/// Creates a new empty buffer. |
| 26 |
pub fn new() -> Buf { |
| 27 |
crate::init(); |
| 28 |
unsafe { |
| 29 |
Binding::from_raw(&mut raw::git_buf { |
| 30 |
ptr: ptr::null_mut(), |
| 31 |
size: 0, |
| 32 |
reserved: 0, |
| 33 |
} as *mut _) |
| 34 |
} |
| 35 |
} |
| 36 |
|
| 37 |
/// Attempt to view this buffer as a string slice. |
| 38 |
pub fn as_str(&self) -> Result<&str, Error> { |
| 39 |
str::from_utf8(&**self).map_err(|e| e.into()) |
| 40 |
} |
| 41 |
} |
| 42 |
|
| 43 |
impl Deref for Buf { |
| 44 |
type Target = [u8]; |
| 45 |
fn deref(&self) -> &[u8] { |
| 46 |
if self.raw.ptr.is_null() { |
| 47 |
return &[]; |
| 48 |
} |
| 49 |
unsafe { slice::from_raw_parts(self.raw.ptr as *const u8, self.raw.size as usize) } |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
impl DerefMut for Buf { |
| 54 |
fn deref_mut(&mut self) -> &mut [u8] { |
| 55 |
if self.raw.ptr.is_null() { |
| 56 |
return &mut []; |
| 57 |
} |
| 58 |
unsafe { slice::from_raw_parts_mut(self.raw.ptr as *mut u8, self.raw.size as usize) } |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
impl Binding for Buf { |
| 63 |
type Raw = *mut raw::git_buf; |
| 64 |
unsafe fn from_raw(raw: *mut raw::git_buf) -> Buf { |
| 65 |
Buf { raw: *raw } |
| 66 |
} |
| 67 |
fn raw(&self) -> *mut raw::git_buf { |
| 68 |
&self.raw as *const _ as *mut _ |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
impl Drop for Buf { |
| 73 |
fn drop(&mut self) { |
| 74 |
unsafe { raw::git_buf_dispose(&mut self.raw) } |
| 75 |
} |
| 76 |
} |
| 77 |
|
| 78 |
#[test] |
| 79 |
fn empty_buf() { |
| 80 |
let mut buf = Buf::new(); |
| 81 |
let x: &[u8] = &*buf; |
| 82 |
assert_eq!(x.len(), 0); |
| 83 |
let x: &mut [u8] = &mut *buf; |
| 84 |
assert_eq!(x.len(), 0); |
| 85 |
} |