Skip to content

Commit 73ac0ba

Browse files
authored
add as_slice (#202)
* add as_slice * reuse string_as_slice code
1 parent a3c97ff commit 73ac0ba

File tree

1 file changed

+13
-8
lines changed

1 file changed

+13
-8
lines changed

src/redismodule.rs

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -119,10 +119,7 @@ impl RedisString {
119119

120120
#[allow(clippy::not_unsafe_ptr_arg_deref)]
121121
pub fn from_ptr<'a>(ptr: *const raw::RedisModuleString) -> Result<&'a str, Utf8Error> {
122-
let mut len: libc::size_t = 0;
123-
let bytes = unsafe { raw::RedisModule_StringPtrLen.unwrap()(ptr, &mut len) };
124-
125-
str::from_utf8(unsafe { slice::from_raw_parts(bytes.cast::<u8>(), len) })
122+
str::from_utf8(Self::string_as_slice(ptr))
126123
}
127124

128125
pub fn append(&mut self, s: &str) -> raw::Status {
@@ -145,6 +142,17 @@ impl RedisString {
145142
Self::from_ptr(self.inner).map_err(|_| RedisError::Str("Couldn't parse as UTF-8 string"))
146143
}
147144

145+
pub fn as_slice<'a>(&self) -> &[u8] {
146+
Self::string_as_slice(self.inner)
147+
}
148+
149+
fn string_as_slice<'a>(ptr: *const raw::RedisModuleString) -> &'a [u8] {
150+
let mut len: libc::size_t = 0;
151+
let bytes = unsafe { raw::RedisModule_StringPtrLen.unwrap()(ptr, &mut len) };
152+
153+
unsafe { slice::from_raw_parts(bytes.cast::<u8>(), len) }
154+
}
155+
148156
/// Performs lossy conversion of a `RedisString` into an owned `String. This conversion
149157
/// will replace any invalid UTF-8 sequences with U+FFFD REPLACEMENT CHARACTER, which
150158
/// looks like this: �.
@@ -153,10 +161,7 @@ impl RedisString {
153161
///
154162
/// Will panic if `RedisModule_StringPtrLen` is missing in redismodule.h
155163
pub fn to_string_lossy(&self) -> String {
156-
let mut len: libc::size_t = 0;
157-
let bytes = unsafe { raw::RedisModule_StringPtrLen.unwrap()(self.inner, &mut len) };
158-
let bytes = unsafe { slice::from_raw_parts(bytes.cast::<u8>(), len) };
159-
String::from_utf8_lossy(bytes).into_owned()
164+
String::from_utf8_lossy(self.as_slice()).into_owned()
160165
}
161166

162167
pub fn parse_unsigned_integer(&self) -> Result<u64, RedisError> {

0 commit comments

Comments
 (0)