Skip to content

Commit 2bf5f22

Browse files
committed
Implement more reference traits
1 parent 3b72afb commit 2bf5f22

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/c_string.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
33
use crate::{vec::Vec, CapacityError};
44
use core::{
5+
borrow::Borrow,
56
error::Error,
67
ffi::{c_char, CStr},
78
fmt,
@@ -271,6 +272,18 @@ impl<const N: usize> CString<N> {
271272
}
272273
}
273274

275+
impl<const N: usize> Borrow<CStr> for CString<N> {
276+
fn borrow(&self) -> &CStr {
277+
self.as_c_str()
278+
}
279+
}
280+
281+
impl<const N: usize> AsRef<CStr> for CString<N> {
282+
fn as_ref(&self) -> &CStr {
283+
self.as_c_str()
284+
}
285+
}
286+
274287
impl<const N: usize> Deref for CString<N> {
275288
type Target = CStr;
276289

@@ -402,4 +415,18 @@ mod tests {
402415

403416
assert_eq!(string.deref(), c"ABC");
404417
}
418+
419+
#[test]
420+
fn as_ref() {
421+
let mut string = CString::<4>::new();
422+
string.extend_from_bytes(b"foo").unwrap();
423+
assert_eq!(string.as_ref(), c"foo");
424+
}
425+
426+
#[test]
427+
fn borrow() {
428+
let mut string = CString::<4>::new();
429+
string.extend_from_bytes(b"foo").unwrap();
430+
assert_eq!(Borrow::<CStr>::borrow(&string), c"foo");
431+
}
405432
}

0 commit comments

Comments
 (0)