Skip to content

Commit a7f0ecf

Browse files
committed
impl Eq for CString
1 parent 73024e4 commit a7f0ecf

File tree

1 file changed

+28
-4
lines changed

1 file changed

+28
-4
lines changed

src/libstd/c_str.rs

+28-4
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ use iter::{Iterator, range};
6868
use libc;
6969
use kinds::marker;
7070
use ops::Drop;
71+
use cmp::Eq;
7172
use clone::Clone;
7273
use option::{Option, Some, None};
7374
use ptr::RawPtr;
@@ -109,13 +110,28 @@ impl Clone for CString {
109110
if self.buf.is_null() {
110111
CString { buf: self.buf, owns_buffer_: self.owns_buffer_ }
111112
} else {
112-
let buf = unsafe { malloc_raw(self.len()) } as *mut libc::c_char;
113-
unsafe { ptr::copy_nonoverlapping_memory(buf, self.buf, self.len()); }
113+
let len = self.len() + 1;
114+
let buf = unsafe { malloc_raw(len) } as *mut libc::c_char;
115+
unsafe { ptr::copy_nonoverlapping_memory(buf, self.buf, len); }
114116
CString { buf: buf as *libc::c_char, owns_buffer_: true }
115117
}
116118
}
117119
}
118120

121+
impl Eq for CString {
122+
fn eq(&self, other: &CString) -> bool {
123+
if self.buf as uint == other.buf as uint {
124+
true
125+
} else if self.buf.is_null() || other.buf.is_null() {
126+
false
127+
} else {
128+
unsafe {
129+
libc::strcmp(self.buf, other.buf) == 0
130+
}
131+
}
132+
}
133+
}
134+
119135
impl CString {
120136
/// Create a C String from a pointer.
121137
pub unsafe fn new(buf: *libc::c_char, owns_buffer: bool) -> CString {
@@ -615,8 +631,9 @@ mod tests {
615631

616632
#[test]
617633
fn test_clone() {
618-
let c_str = "hello".to_c_str();
619-
assert!(c_str == c_str.clone());
634+
let a = "hello".to_c_str();
635+
let b = a.clone();
636+
assert!(a == b);
620637
}
621638

622639
#[test]
@@ -642,6 +659,13 @@ mod tests {
642659
// force a copy, reading the memory
643660
c_.as_bytes().to_owned();
644661
}
662+
663+
#[test]
664+
fn test_clone_eq_null() {
665+
let x = unsafe { CString::new(ptr::null(), false) };
666+
let y = x.clone();
667+
assert!(x == y);
668+
}
645669
}
646670

647671
#[cfg(test)]

0 commit comments

Comments
 (0)