diff --git a/src/common/mod.rs b/src/common/mod.rs index 0ab876a81..d2d41cef6 100644 --- a/src/common/mod.rs +++ b/src/common/mod.rs @@ -30,3 +30,10 @@ pub trait HasLen { } +pub fn create_vec_with_len(capacity: usize) -> Vec { + let mut v = Vec::with_capacity(capacity); + unsafe { + v.set_len(capacity); + } + v +} \ No newline at end of file diff --git a/src/datastruct/stacker/heap.rs b/src/datastruct/stacker/heap.rs index c3b8d0a27..cd8d16e89 100644 --- a/src/datastruct/stacker/heap.rs +++ b/src/datastruct/stacker/heap.rs @@ -1,5 +1,6 @@ use std::cell::UnsafeCell; use std::mem; +use common::create_vec_with_len; use std::ptr; /// `BytesRef` refers to a slice in tantivy's custom `Heap`. @@ -109,11 +110,7 @@ struct InnerHeap { /// We use this unsafe trick to make unit test /// way faster. fn allocate_fast(num_bytes: usize) -> Vec { - let mut buffer = Vec::with_capacity(num_bytes); - unsafe { - buffer.set_len(num_bytes); - } - buffer + create_vec_with_len(num_bytes) } impl InnerHeap { diff --git a/src/schema/term.rs b/src/schema/term.rs index cc727999a..656c9feeb 100644 --- a/src/schema/term.rs +++ b/src/schema/term.rs @@ -1,6 +1,7 @@ use std::fmt; use common::BinarySerializable; +use common::create_vec_with_len; use byteorder::{BigEndian, ByteOrder}; use super::Field; use std::str; @@ -44,8 +45,7 @@ impl Term { /// The first byte is `1`, and the 4 following bytes are that of the u32. pub fn from_field_u32(field: Field, val: u32) -> Term { const U32_TERM_LEN: usize = 1 + 4; - let mut buffer = Vec::with_capacity(U32_TERM_LEN); - unsafe { buffer.set_len(U32_TERM_LEN) }; + let mut buffer = create_vec_with_len(U32_TERM_LEN); buffer[0] = field.0; // we want BigEndian here to have lexicographic order // match the natural order of vals.