From 59ba64d946593a8a98e86f4993d139b0c91c13a1 Mon Sep 17 00:00:00 2001 From: Frank Denis Date: Wed, 18 Sep 2019 01:53:17 +0200 Subject: [PATCH] Avoid useless allocation --- src/crypto.rs | 19 +++++++++++++++---- src/dnscrypt.rs | 3 +-- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/src/crypto.rs b/src/crypto.rs index 54039a9..ba1bb08 100644 --- a/src/crypto.rs +++ b/src/crypto.rs @@ -183,11 +183,22 @@ impl SharedKey { Ok(decrypted) } - pub fn encrypt(&self, nonce: &[u8], mut plaintext: Vec) -> Result, Error> { + pub fn encrypt_into( + &self, + target: &mut Vec, + nonce: &[u8], + mut plaintext: Vec, + ) -> Result<(), Error> { plaintext.push(0x80); let plaintext_len = plaintext.len(); - let mut encrypted = - vec![0u8; plaintext_len + crypto_box_curve25519xchacha20poly1305_MACBYTES as usize]; + let target_header_len = target.len(); + target.resize( + target_header_len + + plaintext_len + + crypto_box_curve25519xchacha20poly1305_MACBYTES as usize, + 0, + ); + let encrypted = &mut target[target_header_len..]; let res = unsafe { libsodium_sys::crypto_box_curve25519xchacha20poly1305_easy_afternm( encrypted.as_mut_ptr(), @@ -198,7 +209,7 @@ impl SharedKey { ) }; ensure!(res == 0, "Unable to encrypt"); - Ok(encrypted) + Ok(()) } } diff --git a/src/dnscrypt.rs b/src/dnscrypt.rs index 568fecf..eae7ff9 100644 --- a/src/dnscrypt.rs +++ b/src/dnscrypt.rs @@ -58,7 +58,6 @@ pub fn encrypt( ) -> Result, Error> { let mut wrapped_packet = vec![0x72u8, 0x36, 0x66, 0x6e, 0x76, 0x57, 0x6a, 0x38]; wrapped_packet.extend_from_slice(nonce); - let encrypted_packet = shared_key.encrypt(nonce, packet)?; - wrapped_packet.extend_from_slice(&encrypted_packet); + shared_key.encrypt_into(&mut wrapped_packet, nonce, packet)?; Ok(wrapped_packet) }