1 | use cfg_if::cfg_if; |
2 | use libc::c_int; |
3 | use std::marker::PhantomData; |
4 | use std::ptr; |
5 | use std::slice; |
6 | |
7 | use crate::cvt_p; |
8 | use crate::error::ErrorStack; |
9 | |
10 | pub struct MemBioSlice<'a>(*mut ffi::BIO, PhantomData<&'a [u8]>); |
11 | |
12 | impl<'a> Drop for MemBioSlice<'a> { |
13 | fn drop(&mut self) { |
14 | unsafe { |
15 | ffi::BIO_free_all(self.0); |
16 | } |
17 | } |
18 | } |
19 | |
20 | impl<'a> MemBioSlice<'a> { |
21 | pub fn new(buf: &'a [u8]) -> Result<MemBioSlice<'a>, ErrorStack> { |
22 | ffi::init(); |
23 | |
24 | assert!(buf.len() <= c_int::max_value() as usize); |
25 | let bio: *mut BIO = unsafe { |
26 | cvt_p(BIO_new_mem_buf( |
27 | buf:buf.as_ptr() as *const _, |
28 | buf.len() as crate::SLenType, |
29 | ))? |
30 | }; |
31 | |
32 | Ok(MemBioSlice(bio, PhantomData)) |
33 | } |
34 | |
35 | pub fn as_ptr(&self) -> *mut ffi::BIO { |
36 | self.0 |
37 | } |
38 | } |
39 | |
40 | pub struct MemBio(*mut ffi::BIO); |
41 | |
42 | impl Drop for MemBio { |
43 | fn drop(&mut self) { |
44 | unsafe { |
45 | ffi::BIO_free_all(self.0); |
46 | } |
47 | } |
48 | } |
49 | |
50 | impl MemBio { |
51 | pub fn new() -> Result<MemBio, ErrorStack> { |
52 | ffi::init(); |
53 | |
54 | let bio = unsafe { cvt_p(ffi::BIO_new(ffi::BIO_s_mem()))? }; |
55 | Ok(MemBio(bio)) |
56 | } |
57 | |
58 | pub fn as_ptr(&self) -> *mut ffi::BIO { |
59 | self.0 |
60 | } |
61 | |
62 | pub fn get_buf(&self) -> &[u8] { |
63 | unsafe { |
64 | let mut ptr = ptr::null_mut(); |
65 | let len = ffi::BIO_get_mem_data(self.0, &mut ptr); |
66 | slice::from_raw_parts(ptr as *const _ as *const _, len as usize) |
67 | } |
68 | } |
69 | |
70 | #[cfg (not(boringssl))] |
71 | pub unsafe fn from_ptr(bio: *mut ffi::BIO) -> MemBio { |
72 | MemBio(bio) |
73 | } |
74 | } |
75 | |
76 | cfg_if! { |
77 | if #[cfg(any(ossl102, boringssl))] { |
78 | use ffi::BIO_new_mem_buf; |
79 | } else { |
80 | #[allow (bad_style)] |
81 | unsafe fn BIO_new_mem_buf(buf: *const ::libc::c_void, len: ::libc::c_int) -> *mut ffi::BIO { |
82 | ffi::BIO_new_mem_buf(buf as *mut _, len) |
83 | } |
84 | } |
85 | } |
86 | |