Small performance gain in allocations

As measured in
https://gist.github.com/kirushik/e0d93759b0cd102f814408595c20a9d0,
it's much faster not to iterate over zeroes, and just allocate a
contiguous array of zeroes directly.
This commit is contained in:
Kirill Pimenov
2017-11-14 13:06:50 +01:00
parent 361debd277
commit 6ddabc0f49
2 changed files with 10 additions and 14 deletions

View File

@@ -14,7 +14,6 @@
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::iter::repeat;
use rand::{Rng, OsRng};
use ethkey::{Public, Secret, math};
use crypto;
@@ -32,10 +31,13 @@ pub fn encrypt_document(key: Bytes, document: Bytes) -> Result<Bytes, Error> {
// use symmetric encryption to encrypt document
let iv = initialization_vector();
let mut encrypted_document = Vec::with_capacity(document.len() + iv.len());
encrypted_document.extend(repeat(0).take(document.len()));
crypto::aes::encrypt(&key, &iv, &document, &mut encrypted_document);
encrypted_document.extend_from_slice(&iv);
let mut encrypted_document = vec![0; document.len() + iv.len()];
{
let (mut encryption_buffer, iv_buffer) = encrypted_document.split_at_mut(document.len());
crypto::aes::encrypt(&key, &iv, &document, &mut encryption_buffer);
iv_buffer.copy_from_slice(&iv);
}
Ok(encrypted_document)
}
@@ -53,8 +55,7 @@ pub fn decrypt_document(key: Bytes, mut encrypted_document: Bytes) -> Result<Byt
// use symmetric decryption to decrypt document
let iv = encrypted_document.split_off(encrypted_document_len - INIT_VEC_LEN);
let mut document = Vec::with_capacity(encrypted_document_len - INIT_VEC_LEN);
document.extend(repeat(0).take(encrypted_document_len - INIT_VEC_LEN));
let mut document = vec![0; encrypted_document_len - INIT_VEC_LEN];
crypto::aes::decrypt(&key, &iv, &encrypted_document, &mut document);
Ok(document)