diff options
| author | Corey Richardson <corey@octayn.net> | 2014-01-30 19:10:07 -0500 |
|---|---|---|
| committer | Corey Richardson <corey@octayn.net> | 2014-02-01 18:24:44 -0500 |
| commit | a7f0ecf5626aefc3a269f32d70316654f5b4773f (patch) | |
| tree | 58f43bb92ab8b4d3a313b1b37772c6d03ebc5d76 /src/libstd | |
| parent | 73024e4b858e6c2083f40e8c987acedc22e9672b (diff) | |
| download | rust-a7f0ecf5626aefc3a269f32d70316654f5b4773f.tar.gz rust-a7f0ecf5626aefc3a269f32d70316654f5b4773f.zip | |
impl Eq for CString
Diffstat (limited to 'src/libstd')
| -rw-r--r-- | src/libstd/c_str.rs | 32 |
1 files changed, 28 insertions, 4 deletions
diff --git a/src/libstd/c_str.rs b/src/libstd/c_str.rs index 4940358ddf9..7e79ad97df0 100644 --- a/src/libstd/c_str.rs +++ b/src/libstd/c_str.rs @@ -68,6 +68,7 @@ use iter::{Iterator, range}; use libc; use kinds::marker; use ops::Drop; +use cmp::Eq; use clone::Clone; use option::{Option, Some, None}; use ptr::RawPtr; @@ -109,13 +110,28 @@ impl Clone for CString { if self.buf.is_null() { CString { buf: self.buf, owns_buffer_: self.owns_buffer_ } } else { - let buf = unsafe { malloc_raw(self.len()) } as *mut libc::c_char; - unsafe { ptr::copy_nonoverlapping_memory(buf, self.buf, self.len()); } + let len = self.len() + 1; + let buf = unsafe { malloc_raw(len) } as *mut libc::c_char; + unsafe { ptr::copy_nonoverlapping_memory(buf, self.buf, len); } CString { buf: buf as *libc::c_char, owns_buffer_: true } } } } +impl Eq for CString { + fn eq(&self, other: &CString) -> bool { + if self.buf as uint == other.buf as uint { + true + } else if self.buf.is_null() || other.buf.is_null() { + false + } else { + unsafe { + libc::strcmp(self.buf, other.buf) == 0 + } + } + } +} + impl CString { /// Create a C String from a pointer. pub unsafe fn new(buf: *libc::c_char, owns_buffer: bool) -> CString { @@ -615,8 +631,9 @@ mod tests { #[test] fn test_clone() { - let c_str = "hello".to_c_str(); - assert!(c_str == c_str.clone()); + let a = "hello".to_c_str(); + let b = a.clone(); + assert!(a == b); } #[test] @@ -642,6 +659,13 @@ mod tests { // force a copy, reading the memory c_.as_bytes().to_owned(); } + + #[test] + fn test_clone_eq_null() { + let x = unsafe { CString::new(ptr::null(), false) }; + let y = x.clone(); + assert!(x == y); + } } #[cfg(test)] |
