1 // Copyright 2013 The Servo Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9 
10 //! Core Foundation byte buffers.
11 
12 pub use core_foundation_sys::data::*;
13 use core_foundation_sys::base::CFIndex;
14 use core_foundation_sys::base::{kCFAllocatorDefault};
15 use std::ops::Deref;
16 use std::slice;
17 
18 use base::{CFIndexConvertible, TCFType};
19 
20 
21 declare_TCFType!{
22     /// A byte buffer.
23     CFData, CFDataRef
24 }
25 impl_TCFType!(CFData, CFDataRef, CFDataGetTypeID);
26 impl_CFTypeDescription!(CFData);
27 
28 impl CFData {
from_buffer(buffer: &[u8]) -> CFData29     pub fn from_buffer(buffer: &[u8]) -> CFData {
30         unsafe {
31             let data_ref = CFDataCreate(kCFAllocatorDefault,
32                                         buffer.as_ptr(),
33                                         buffer.len().to_CFIndex());
34             TCFType::wrap_under_create_rule(data_ref)
35         }
36     }
37 
38     /// Returns a pointer to the underlying bytes in this data. Note that this byte buffer is
39     /// read-only.
40     #[inline]
bytes<'a>(&'a self) -> &'a [u8]41     pub fn bytes<'a>(&'a self) -> &'a [u8] {
42         unsafe {
43             slice::from_raw_parts(CFDataGetBytePtr(self.0), self.len() as usize)
44         }
45     }
46 
47     /// Returns the length of this byte buffer.
48     #[inline]
len(&self) -> CFIndex49     pub fn len(&self) -> CFIndex {
50         unsafe {
51             CFDataGetLength(self.0)
52         }
53     }
54 }
55 
56 impl Deref for CFData {
57     type Target = [u8];
58 
59     #[inline]
deref(&self) -> &[u8]60     fn deref(&self) -> &[u8] {
61         self.bytes()
62     }
63 }
64