Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modernization and cleanup #69

Merged
merged 8 commits into from Sep 5, 2015
Merged

Cleanup string

* Add CFString::new, deprecate FromStr impl
* Implement Display for CFString
* Add wrapping `"`s for Debug impl
  • Loading branch information
sfackler committed Aug 29, 2015
commit 6d5a95cf5e13c3f3cecbe60788260aa141865f54
@@ -16,9 +16,9 @@ use base::{CFRelease, CFRetain, CFTypeID, CFTypeRef, TCFType};
use base::{kCFAllocatorDefault, kCFAllocatorNull};

use libc;
use std::ffi::CStr;
use std::fmt;
use std::str::FromStr;
use std::string::ToString;
use std::str::{self, FromStr};
use std::mem;
use std::ptr;
use std::vec::Vec;
@@ -228,7 +228,6 @@ impl Drop for CFString {
}
}


impl TCFType<CFStringRef> for CFString {
#[inline]
fn as_concrete_TypeRef(&self) -> CFStringRef {
@@ -265,69 +264,84 @@ impl TCFType<CFStringRef> for CFString {
impl FromStr for CFString {
type Err = ();

/// Creates a new `CFString` instance from a Rust string.
/// # Deprecated
///
/// Use CFString::new instead.
#[inline]
fn from_str(string: &str) -> Result<CFString, ()> {
unsafe {
let string_ref = CFStringCreateWithBytes(kCFAllocatorDefault,
string.as_ptr(),
string.len().to_CFIndex(),
kCFStringEncodingUTF8,
false as Boolean,
kCFAllocatorNull);
Some(TCFType::wrap_under_create_rule(string_ref)).ok_or(())
}
Ok(CFString::new(string))
}
}

impl ToString for CFString {
fn to_string(&self) -> String {
impl fmt::Display for CFString {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
unsafe {
let char_len = self.char_len();

// First, ask how big the buffer ought to be.
let mut bytes_required: CFIndex = 0;
CFStringGetBytes(self.obj,
CFRange::init(0, char_len),
kCFStringEncodingUTF8,
0,
false as Boolean,
ptr::null_mut(),
0,
&mut bytes_required);

// Then, allocate the buffer and actually copy.
let mut buffer = Vec::with_capacity(bytes_required as usize);
for _ in (0..bytes_required) { buffer.push('\x00' as u8) }

let mut bytes_used: CFIndex = 0;
let chars_written = CFStringGetBytes(self.obj,
CFRange::init(0, char_len),
kCFStringEncodingUTF8,
0,
false as Boolean,
buffer.as_mut_ptr(),
buffer.len().to_CFIndex(),
&mut bytes_used) as usize;
assert!(chars_written.to_CFIndex() == char_len);

// This is dangerous; we over-allocate and null-terminate the string (during
// initialization).
assert!(bytes_used == buffer.len().to_CFIndex());
String::from_utf8(buffer).unwrap()
// Do this without allocating if we can get away with it
let c_string = CFStringGetCStringPtr(self.obj, kCFStringEncodingUTF8);
if c_string != ptr::null() {
let c_str = CStr::from_ptr(c_string);
fmt.write_str(str::from_utf8_unchecked(c_str.to_bytes()))
} else {
let char_len = self.char_len();

// First, ask how big the buffer ought to be.
let mut bytes_required: CFIndex = 0;
CFStringGetBytes(self.obj,
CFRange::init(0, char_len),
kCFStringEncodingUTF8,
0,
false as Boolean,
ptr::null_mut(),
0,
&mut bytes_required);

// Then, allocate the buffer and actually copy.
let mut buffer = Vec::with_capacity(bytes_required as usize);
for _ in (0..bytes_required) { buffer.push('\x00' as u8) }

let mut bytes_used: CFIndex = 0;
let chars_written = CFStringGetBytes(self.obj,
CFRange::init(0, char_len),
kCFStringEncodingUTF8,
0,
false as Boolean,
buffer.as_mut_ptr(),
buffer.len().to_CFIndex(),
&mut bytes_used) as usize;
assert!(chars_written.to_CFIndex() == char_len);

// This is dangerous; we over-allocate and null-terminate the string (during
// initialization).
assert!(bytes_used == buffer.len().to_CFIndex());
fmt.write_str(str::from_utf8_unchecked(&buffer))
}
}
}
}

impl fmt::Debug for CFString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.to_string())
write!(f, "\"{}\"", self)
}
}


impl CFString {
/// Like `CFString::from_string`, but references a string that can be used as a backing store
/// Creates a new `CFString` instance from a Rust string.
#[inline]
pub fn new(string: &str) -> CFString {
unsafe {
let string_ref = CFStringCreateWithBytes(kCFAllocatorDefault,
string.as_ptr(),
string.len().to_CFIndex(),
kCFStringEncodingUTF8,
false as Boolean,
kCFAllocatorNull);
CFString::wrap_under_create_rule(string_ref)
}
}

/// Like `CFString::new`, but references a string that can be used as a backing store
/// by virtue of being statically allocated.
#[inline]
pub fn from_static_string(string: &'static str) -> CFString {
@@ -420,7 +434,9 @@ extern {
//fn CFStringGetCharactersPtr
//fn CFStringGetCharacterFromInlineBuffer
//fn CFStringGetCString
//fn CFStringGetCStringPtr
fn CFStringGetCStringPtr(theString: CFStringRef,
encoding: CFStringEncoding)
-> *const libc::c_char;
fn CFStringGetLength(theString: CFStringRef) -> CFIndex;
//fn CFStringGetPascalString
//fn CFStringGetPascalStringPtr
ProTip! Use n and p to navigate between commits in a pull request.
You can’t perform that action at this time.