Skip to content

Commit e4da077

Browse files
author
Marcin Radomski
committed
Make allocating the tag safe code
Also remove unnecessary to_owned call, and clean up _owned_tag use.
1 parent 020dedf commit e4da077

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed

src/lib.rs

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,7 @@ impl Log for AndroidLogger {
215215
// tag longer than LOGGING_TAG_MAX_LEN causes allocation
216216
let mut tag_bytes: [MaybeUninit<u8>; LOGGING_TAG_MAX_LEN + 1] = uninit_array();
217217

218-
let module_path = record.module_path().unwrap_or_default().to_owned();
218+
let module_path = record.module_path().unwrap_or_default();
219219

220220
// If no tag was specified, use module name
221221
let custom_tag = &config.tag;
@@ -225,18 +225,21 @@ impl Log for AndroidLogger {
225225
.unwrap_or_else(|| module_path.as_bytes());
226226

227227
// In case we end up allocating, keep the CString alive.
228-
let mut _owned_tag = None;
228+
let _owned_tag;
229229
let tag: &CStr = if tag.len() < tag_bytes.len() {
230230
// use stack array as C string
231231
self.fill_tag_bytes(&mut tag_bytes, tag);
232232
// SAFETY: fill_tag_bytes always puts a nullbyte in tag_bytes.
233233
unsafe { CStr::from_ptr(mem::transmute(tag_bytes.as_ptr())) }
234234
} else {
235235
// Tag longer than available stack buffer; allocate.
236-
// SAFETY: if tag contains nullbytes, the Android logger will just ignore any
237-
// characters that follow it.
238-
_owned_tag = Some(unsafe { CString::from_vec_unchecked(tag.to_vec()) });
239-
_owned_tag.as_ref().unwrap()
236+
// We're using either
237+
// - CString::as_bytes on config.tag, or
238+
// - str::as_bytes on record.module_path()
239+
// Neither of those include the terminating nullbyte.
240+
_owned_tag = CString::new(tag)
241+
.expect("config.tag or record.module_path() should never contain nullbytes");
242+
_owned_tag.as_ref()
240243
};
241244

242245
// message must not exceed LOGGING_MSG_MAX_LEN

0 commit comments

Comments
 (0)