Added helper to create Vec with a given size

This commit is contained in:
Paul Masurel
2017-03-29 11:26:18 +09:00
parent 456dd3a60d
commit f0dc0de4b7
3 changed files with 11 additions and 7 deletions

View File

@@ -30,3 +30,10 @@ pub trait HasLen {
}
pub fn create_vec_with_len<T>(capacity: usize) -> Vec<T> {
let mut v = Vec::with_capacity(capacity);
unsafe {
v.set_len(capacity);
}
v
}

View File

@@ -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<u8> {
let mut buffer = Vec::with_capacity(num_bytes);
unsafe {
buffer.set_len(num_bytes);
}
buffer
create_vec_with_len(num_bytes)
}
impl InnerHeap {

View File

@@ -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.