How to decode large file without runing out of memory? - rust

I need to convert a ~4GB IBM866 encoded xml file into UTF-8. I tried this
and this crates, but with both of them I run out of memory.
I tried to do it this way:
fn ibm866_to_utf8(ibm866: &[u8]) -> Result<String, MyError> {
use encoding_rs::IBM866;
let (utf8, _, had_error) = IBM866.decode(ibm866);
if (had_error == true) {
Err(MyError::DecodingError)
} else {
Ok(utf8.to_string())
}
}
fn main() {
let path = "ibm866_file";
let mut file = File::open(path).unwrap();
let mut vec: Vec<u8> = Vec::with_capacity(file.metadata().unwrap().len() as usize);
file.read_to_end(&mut vec);
let utf8_string = ibm866_to_utf8(&vec).unwrap();
// write to file
}
I also tried to iterate file by lines like this:
fn main() {
let path = "ibm866_file";
let mut file = File::open(path).unwrap();
let mut reader = BufReader::new(file);
let mut utf8_string = String::new();
for line in reader.lines() {
let utf8_line = ibm866_to_utf8(line.unwrap().as_bytes())
utf8_string = format!("{}{}", utf8_string, utf8_line.unwrap());
}
// write to file
}
But it panics when reader meets non UTF-8 character.
How to decode large files properly?
link to file: https://drive.google.com/file/d/1fHFS5GWPhApoNRl3CRK-pRMNthIakcZY/view?usp=sharing

You need to use the streaming functionality of encoding_rs.
This requires a bit of boilerplate code, though, to properly feed the chunks read from a file into the conversion function.
This code seems to work on a simple example, as well as on your multi-GB large legends.xml file and reports no conversion errors.
use std::{
fs::File,
io::{Read, Write},
};
use encoding_rs::{CoderResult, IBM866};
const BUF_SIZE: usize = 4096;
struct ConversionBuffers {
buf1: [u8; BUF_SIZE],
buf2: [u8; BUF_SIZE],
buf1_active: bool,
content: usize,
}
impl ConversionBuffers {
fn new() -> Self {
Self {
buf1: [0; BUF_SIZE],
buf2: [0; BUF_SIZE],
buf1_active: true,
content: 0,
}
}
fn move_leftovers_and_flip(&mut self, consumed: usize) {
let (src, dst) = if self.buf1_active {
(&mut self.buf1, &mut self.buf2)
} else {
(&mut self.buf2, &mut self.buf1)
};
let leftover = self.content - consumed;
dst[..leftover].clone_from_slice(&src[consumed..self.content]);
self.buf1_active = !self.buf1_active;
self.content = leftover;
}
fn append(&mut self, append_action: impl FnOnce(&mut [u8]) -> usize) {
let buf = if self.buf1_active {
&mut self.buf1[self.content..]
} else {
&mut self.buf2[self.content..]
};
let appended = append_action(buf);
self.content += appended;
}
fn get_data(&mut self) -> &[u8] {
if self.buf1_active {
&self.buf1[..self.content]
} else {
&self.buf2[..self.content]
}
}
}
fn main() {
let mut decoder = IBM866.new_decoder();
let mut file_in = File::open("test_ibm866.txt").unwrap();
let mut file_out = File::create("out_utf8-2.txt").unwrap();
let mut buffer_in = ConversionBuffers::new();
let mut buffer_out = vec![0u8; decoder.max_utf8_buffer_length(BUF_SIZE).unwrap_or(BUF_SIZE)];
let mut file_eof = false;
let mut errors = false;
loop {
if !file_eof {
buffer_in.append(|buf| {
let num_read = file_in.read(buf).unwrap();
if num_read == 0 {
file_eof = true;
}
num_read
});
}
let (result, num_consumed, num_produced, had_error) =
decoder.decode_to_utf8(buffer_in.get_data(), &mut buffer_out, file_eof);
if had_error {
errors = true;
}
let produced_data = &buffer_out[..num_produced];
file_out.write_all(produced_data).unwrap();
if file_eof && result == CoderResult::InputEmpty {
break;
}
buffer_in.move_leftovers_and_flip(num_consumed);
}
println!("Had conversion errors: {:?}", errors);
}
As #BurntSushi5 pointed out, there is the encoding_rs_io crate that allows us to skip all the boilerplate code:
use std::fs::File;
use encoding_rs::IBM866;
use encoding_rs_io::DecodeReaderBytesBuilder;
fn main() {
let file_in = File::open("test_ibm866.txt").unwrap();
let mut file_out = File::create("out_utf8.txt").unwrap();
let mut decoded_stream = DecodeReaderBytesBuilder::new()
.encoding(Some(IBM866))
.build(file_in);
std::io::copy(&mut decoded_stream, &mut file_out).unwrap();
}

Related

How to traverse and consume a vector in given order? [duplicate]

For example, I have a Vec<String> and an array storing indexes.
let src = vec!["a".to_string(), "b".to_string(), "c".to_string()];
let idx_arr = [2_usize, 0, 1];
The indexes stored in idx_arr comes from the range 0..src.len(), without repetition or omission.
I want to move the elements in src to another container in the given order, until the vector is completely consumed. For example,
let iter = into_iter_in_order(src, &idx_arr);
for s in iter {
// s: String
}
// or
consume_vec_in_order(src, &idx_arr, |s| {
// s: String
});
If the type of src can be changed to Vec<Option<String>>, things will be much easier, just use src[i].take(). However, it cannot.
Edit:
"Another container" refers to any container, such as a queue or hash set. Reordering in place is not the answer to the problem. It introduces the extra time cost of O(n). The ideal method should be 0-cost.
Not sure if my algorithm satisfies your requirements but here I have an algorithm that can consume the provided vector in-order without initializing a new temporary vector, which is more efficient for a memory.
fn main() {
let src = &mut vec!["a".to_string(), "b".to_string(), "c".to_string(), "d".to_string()];
let idx_arr = [2_usize, 3, 1, 0];
consume_vector_in_order(src, idx_arr.to_vec());
println!("{:?}", src); // d , c , a , b
}
// In-place consume vector in order
fn consume_vector_in_order<T>(v: &mut Vec<T>, inds: Vec<usize>) -> &mut Vec<T>
where
T: Default,
{
let mut i: usize = 0;
let mut temp_inds = inds.to_vec();
while i < inds.to_vec().len() {
let s_index = temp_inds[i];
if s_index != i {
let new_index = temp_inds[s_index];
temp_inds.swap(s_index, new_index);
v.swap(s_index, new_index);
} else {
i += 1;
}
}
v
}
You can use the technique found in How to sort a Vec by indices? (using my answer in particular) since that can reorder the data in-place from the indices, and then its just simple iteration:
fn consume_vec_in_order<T>(mut vec: Vec<T>, order: &[usize], mut cb: impl FnMut(T)) {
sort_by_indices(&mut vec, order.to_owned());
for elem in vec {
cb(elem);
}
}
Full example available on the playground.
Edit:
An ideal method, but needs to access unstable features and functions not exposed by the standard library.
use std::alloc::{Allocator, RawVec};
use std::marker::PhantomData;
use std::mem::{self, ManuallyDrop};
use std::ptr::{self, NonNull};
#[inline]
unsafe fn into_iter_in_order<'a, T, A: Allocator>(
vec: Vec<T, A>,
order: &'a [usize],
) -> IntoIter<'a, T, A> {
unsafe {
let mut vec = ManuallyDrop::new(vec);
let cap = vec.capacity();
let alloc = ManuallyDrop::new(ptr::read(vec.allocator()));
let ptr = order.as_ptr();
let end = ptr.add(order.len());
IntoIter {
buf: NonNull::new_unchecked(vec.as_mut_ptr()),
_marker_1: PhantomData,
cap,
alloc,
ptr,
end,
_marker_2: PhantomData,
}
}
}
struct IntoIter<'a, T, A: Allocator> {
buf: NonNull<T>,
_marker_1: PhantomData<T>,
cap: usize,
alloc: ManuallyDrop<A>,
ptr: *const usize,
end: *const usize,
_marker_2: PhantomData<&'a usize>,
}
impl<T, A: Allocator> Iterator for IntoIter<T, A> {
type Item = T;
#[inline]
fn next(&mut self) -> Option<T> {
if self.ptr == self.end {
None
} else {
let idx = unsafe { *self.ptr };
self.ptr = unsafe { self.ptr.add(1) };
if T::IS_ZST {
Some(unsafe { mem::zeroed() })
} else {
Some(unsafe { ptr::read(self.buf.as_ptr().add(idx)) })
}
}
}
}
impl<#[may_dangle] T, A: Allocator> Drop for IntoIter<T, A> {
fn drop(&mut self) {
struct DropGuard<'a, T, A: Allocator>(&'a mut IntoIter<T, A>);
impl<T, A: Allocator> Drop for DropGuard<'_, T, A> {
fn drop(&mut self) {
unsafe {
// `IntoIter::alloc` is not used anymore after this and will be dropped by RawVec
let alloc = ManuallyDrop::take(&mut self.0.alloc);
// RawVec handles deallocation
let _ = RawVec::from_raw_parts_in(self.0.buf.as_ptr(), self.0.cap, alloc);
}
}
}
let guard = DropGuard(self);
// destroy the remaining elements
unsafe {
while self.ptr != self.end {
let idx = *self.ptr;
self.ptr = self.ptr.add(1);
let p = if T::IS_ZST {
self.buf.as_ptr().wrapping_byte_add(idx)
} else {
self.buf.as_ptr().add(idx)
};
ptr::drop_in_place(p);
}
}
// now `guard` will be dropped and do the rest
}
}
Example:
let src = vec![
"0".to_string(),
"1".to_string(),
"2".to_string(),
"3".to_string(),
"4".to_string(),
];
let mut dst = vec![];
let iter = unsafe { into_iter_in_order(src, &[2, 1, 3, 0, 4]) };
for s in iter {
dst.push(s);
}
assert_eq!(dst, vec!["2", "1", "3", "0", "4"]);
My previous answer:
use std::mem;
use std::ptr;
pub unsafe fn consume_vec_in_order<T>(vec: Vec<T>, order: &[usize], mut cb: impl FnMut(T)) {
// Check whether `order` contains all numbers in 0..len without repetition
// or omission.
if cfg!(debug_assertions) {
use std::collections::HashSet;
let n = order.len();
if n != vec.len() {
panic!("The length of `order` is not equal to that of `vec`.");
}
let mut set = HashSet::<usize>::new();
for &idx in order {
if idx >= n {
panic!("`{idx}` in the `order` is out of range (0..{n}).");
} else if set.contains(&idx) {
panic!("`order` contains the repeated element `{idx}`");
} else {
set.insert(idx);
}
}
}
unsafe {
for &idx in order {
let s = ptr::read(vec.get_unchecked(idx));
cb(s);
}
vec.set_len(0);
}
}
Example:
let src = vec![
"0".to_string(),
"1".to_string(),
"2".to_string(),
"3".to_string(),
"4".to_string(),
];
let mut dst = vec![];
consume_vec_in_order(
src,
&[2, 1, 3, 0, 4],
|elem| dst.push(elem),
);
assert_eq!(dst, vec!["2", "1", "3", "0", "4"]);

How to provide an enumerated index to a macro interpolation function in quote with proc_macro?

I've implemented the following proc_macro that takes
builtin_method!(hello_world(a, b, c) {
println!("{} {} {}", a, b, c);
}
and should generate
pub fn hello_world(args: Vec<String>) {
let a = args.get(0).unwrap();
let b = args.get(1).unwrap();
let c = args.get(2).unwrap();
println!("{} {} {}", a, b, c);
}
Here's my current code.
use proc_macro::TokenStream;
use quote::quote;
use syn;
struct BuiltinDef {
function: syn::Ident,
arguments: Vec<syn::Ident>,
body: syn::Block,
}
impl syn::parse::Parse for BuiltinDef {
fn parse(stream: syn::parse::ParseStream) -> syn::Result<Self> {
let function: syn::Ident = stream.parse()?;
let content;
let _: syn::token::Paren = syn::parenthesized!(content in stream);
let arguments: syn::punctuated::Punctuated<syn::Ident, syn::Token![,]> =
content.parse_terminated(syn::Ident::parse)?;
let body: syn::Block = stream.parse()?;
Ok(BuiltinDef {
function,
arguments: arguments.into_iter().collect(),
body,
})
}
}
#[proc_macro]
pub fn builtin_method(input: TokenStream) -> TokenStream {
let def = syn::parse_macro_input!(input as BuiltinDef);
let function = def.function;
let arguments = def.arguments;
let body = def.body;
let gen = quote! {
pub fn #function(args: Vec<String>) {
let mut _i = 0;
#(
let mut #arguments = args.get(_i).unwrap().clone();
_i += 1;
)*
#body
}
};
TokenStream::from(gen)
}
Inside the variable interpolation, I need some kind of enumerating variable counting up.
According to the docs there is not such way.
How can I implement this better instead of counting up _i?
let mut _i = 0;
#(
let mut #arguments = args.get(_i).unwrap().clone();
_i += 1;
)*
Use standard Iterator::enumerate():
let arguments = arguments.into_iter().enumerate().map(|(index, arg)| quote! {
let mut #arg = args.get(#index).unwrap().clone();
});
let gen = quote! {
pub fn #function(args: Vec<String>) {
let mut _i = 0;
#(#arguments)*
#body
}
};
Ok after following https://stackoverflow.com/a/70939071/694705 I was able to implement it this way by collecting the arguments back into a Vec<proc_macro2::TokenStream>.
Here's my solution:
let arguments: Vec<proc_macro2::TokenStream> =
arguments
.into_iter()
.enumerate()
.map(|(idx, arg)| {
quote! {
let mut #arg = args.get(#idx).unwrap().clone();
}
})
.collect();
let gen = quote! {
pub fn #function(args: Vec<String>) {
#(#arguments)*
#body
}
};

Why does this program block until someone connects to the FIFO / named pipe?

I found this script in the post Recommended way of IPC in Rust where a server and client are created with named pipes.
I want to understand how it works so I started debugging. When I start the server with cargo run listen, the program reaches the open function and the following happens. I know this is a feature and not a bug, but I do not understand why it happens.
In the main function the listen function is called and then the listen function calls the open function:
use libc::{c_char, mkfifo};
use serde::{Deserialize, Serialize};
use std::env::args;
use std::fs::{File, OpenOptions};
use std::io::{Error, Read, Result, Write};
use std::os::unix::ffi::OsStrExt;
use std::path::{Path, PathBuf};
fn main() -> Result<()> {
let mut args = args();
let _ = args.next();
match args.next().as_ref().map(String::as_str) {
Some("listen") => listen()?,
Some("send") => {
let msg = args.next().unwrap();
send(msg)?;
}
_ => {
eprintln!("Please either listen or send.");
}
}
Ok(())
}
pub struct Fifo {
path: PathBuf,
}
impl Fifo {
pub fn new(path: PathBuf) -> Result<Self> {
let os_str = path.clone().into_os_string();
let slice = os_str.as_bytes();
let mut bytes = Vec::with_capacity(slice.len() + 1);
bytes.extend_from_slice(slice);
bytes.push(0); // zero terminated string
let _ = std::fs::remove_file(&path);
if unsafe { mkfifo((&bytes[0]) as *const u8 as *const c_char, 0o644) } != 0 {
Err(Error::last_os_error())
} else {
Ok(Fifo { path })
}
}
/// Blocks until anyone connects to this fifo.
pub fn open(&self) -> Result<FifoHandle> {
let mut pipe = OpenOptions::new().read(true).open(&self.path)?;
let mut pid_bytes = [0u8; 4];
pipe.read_exact(&mut pid_bytes)?;
let pid = u32::from_ne_bytes(pid_bytes);
drop(pipe);
let read = OpenOptions::new()
.read(true)
.open(format!("/tmp/rust-fifo-read.{}", pid))?;
let write = OpenOptions::new()
.write(true)
.open(format!("/tmp/rust-fifo-write.{}", pid))?;
Ok(FifoHandle { read, write })
}
}
impl Drop for Fifo {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.path);
}
}
#[derive(Serialize, Deserialize)]
pub enum Message {
Print(String),
Ack(),
}
pub struct FifoHandle {
read: File,
write: File,
}
impl FifoHandle {
pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
let pid = std::process::id();
let read_fifo_path = format!("/tmp/rust-fifo-write.{}", pid);
let read_fifo = Fifo::new(read_fifo_path.into())?;
let write_fifo_path = format!("/tmp/rust-fifo-read.{}", pid);
let write_fifo = Fifo::new(write_fifo_path.into())?;
let mut pipe = OpenOptions::new().write(true).open(path.as_ref())?;
let pid_bytes: [u8; 4] = u32::to_ne_bytes(pid);
pipe.write_all(&pid_bytes)?;
pipe.flush()?;
let write = OpenOptions::new().write(true).open(&write_fifo.path)?;
let read = OpenOptions::new().read(true).open(&read_fifo.path)?;
Ok(Self { read, write })
}
pub fn send_message(&mut self, msg: &Message) -> Result<()> {
let msg = bincode::serialize(msg).expect("Serialization failed");
self.write.write_all(&usize::to_ne_bytes(msg.len()))?;
self.write.write_all(&msg[..])?;
self.write.flush()
}
pub fn recv_message(&mut self) -> Result<Message> {
let mut len_bytes = [0u8; std::mem::size_of::<usize>()];
self.read.read_exact(&mut len_bytes)?;
let len = usize::from_ne_bytes(len_bytes);
let mut buf = vec![0; len];
self.read.read_exact(&mut buf[..])?;
Ok(bincode::deserialize(&buf[..]).expect("Deserialization failed"))
}
}
fn listen() -> Result<()> {
let fifo = Fifo::new(PathBuf::from("/tmp/rust-fifo"))?;
loop {
let mut handle = fifo.open()?;
std::thread::spawn(move || {
match handle.recv_message().expect("Failed to recieve message") {
Message::Print(p) => println!("{}", p),
Message::Ack() => panic!("Didn't expect Ack now."),
}
#[allow(deprecated)]
std::thread::sleep_ms(1000);
handle
.send_message(&Message::Ack())
.expect("Send message failed.");
});
}
}
fn send(s: String) -> Result<()> {
let mut handle = FifoHandle::open("/tmp/rust-fifo")?;
#[allow(deprecated)]
std::thread::sleep_ms(1000);
handle.send_message(&Message::Print(s))?;
match handle.recv_message()? {
Message::Print(p) => println!("{}", p),
Message::Ack() => {}
}
Ok(())
}

Deserializing newline-delimited JSON from a socket using Serde

I am trying to use serde for sending a JSON struct from a client to a server. A newline from the client to the server marks that the socket is done. My server looks like this
#[derive(Serialize, Deserialize, Debug)]
struct Point3D {
x: u32,
y: u32,
z: u32,
}
fn handle_client(mut stream: TcpStream) -> Result<(), Error> {
println!("Incoming connection from: {}", stream.peer_addr()?);
let mut buffer = [0; 512];
loop {
let bytes_read = stream.read(&mut buffer)?;
if bytes_read == 0 {
return Ok(());
}
let buf_str: &str = str::from_utf8(&buffer).expect("Boom");
let input: Point3D = serde_json::from_str(&buf_str)?;
let result: String = (input.x.pow(2) + input.y.pow(2) + input.z.pow(2)).to_string();
stream.write(result.as_bytes())?;
}
}
fn main() {
let args: Vec<_> = env::args().collect();
if args.len() != 2 {
eprintln!("Please provide --client or --server as argument");
std::process::exit(1);
}
if args[1] == "--server" {
let listener = TcpListener::bind("0.0.0.0:8888").expect("Could not bind");
for stream in listener.incoming() {
match stream {
Err(e) => eprintln!("failed: {}", e),
Ok(stream) => {
thread::spawn(move || {
handle_client(stream).unwrap_or_else(|error| eprintln!("{:?}", error));
});
}
}
}
} else if args[1] == "--client" {
let mut stream = TcpStream::connect("127.0.0.1:8888").expect("Could not connect to server");
println!("Please provide a 3D point as three comma separated integers");
loop {
let mut input = String::new();
let mut buffer: Vec<u8> = Vec::new();
stdin()
.read_line(&mut input)
.expect("Failed to read from stdin");
let parts: Vec<&str> = input.trim_matches('\n').split(',').collect();
let point = Point3D {
x: parts[0].parse().unwrap(),
y: parts[1].parse().unwrap(),
z: parts[2].parse().unwrap(),
};
stream
.write(serde_json::to_string(&point).unwrap().as_bytes())
.expect("Failed to write to server");
let mut reader = BufReader::new(&stream);
reader
.read_until(b'\n', &mut buffer)
.expect("Could not read into buffer");
print!(
"{}",
str::from_utf8(&buffer).expect("Could not write buffer as string")
);
}
}
}
How do I know what length of buffer to allocate before reading in the string? If my buffer is too large, serde fails to deserialize it with an error saying that there are invalid characters. Is there a better way to do this?
Place the TcpStream into a BufReader. This allows you to read until a specific byte (in this case a newline). You can then parse the read bytes with Serde:
use std::io::{BufRead, BufReader};
use std::io::Write;
fn handle_client(mut stream: TcpStream) -> Result<(), Error> {
let mut data = Vec::new();
let mut stream = BufReader::new(stream);
loop {
data.clear();
let bytes_read = stream.read_until(b'\n', &mut data)?;
if bytes_read == 0 {
return Ok(());
}
let input: Point3D = serde_json::from_slice(&data)?;
let value = input.x.pow(2) + input.y.pow(2) + input.z.pow(2);
write!(stream.get_mut(), "{}", value)?;
}
}
I'm being a little fancy by reusing the allocation of data, which means it's very important to reset the buffer at the beginning of each loop. I also avoid allocating memory for the result and just print directly to the output stream.

How can I change the return type of this function?

I'm going through the matasano crypto challenges using rust, with rust-crypto for the AES implementation. I have this function to do basic ECB mode encryption (basically taken nearly verbatim from the rust-crypto repository's example):
pub fn aes_enc_ecb_128(key: &[u8], data: &[u8])
-> Result<Vec<u8>, symmetriccipher::SymmetricCipherError> {
let mut encryptor = aes::ecb_encryptor(
aes::KeySize::KeySize128,
key,
blockmodes::NoPadding);
let mut final_result = Vec::<u8>::new();
let mut read_buffer = buffer::RefReadBuffer::new(data);
let mut buffer = [0; 4096];
let mut write_buffer = buffer::RefWriteBuffer::new(&mut buffer);
loop {
let result = encryptor.encrypt(&mut read_buffer,
&mut write_buffer,
true);
final_result.extend(write_buffer
.take_read_buffer()
.take_remaining().iter().map(|&i| i));
match result {
Ok(BufferResult::BufferUnderflow) => break,
Ok(_) => {},
Err(e) => return Err(e)
}
}
Ok(final_result)
}
The above version compiles with no problem, and works as expected. However, to make it fit with the rest of my error handling scheme I'd like to change the return type to Result<Vec<u8>,&'static str>. This is the function with that change applied:
pub fn aes_enc_ecb_128(key: &[u8], data: &[u8])
-> Result<Vec<u8>, &'static str> {
let mut encryptor = aes::ecb_encryptor(
aes::KeySize::KeySize128,
key,
blockmodes::NoPadding);
let mut final_result = Vec::<u8>::new();
let mut read_buffer = buffer::RefReadBuffer::new(data);
let mut buffer = [0; 4096];
let mut write_buffer = buffer::RefWriteBuffer::new(&mut buffer);
loop {
let result = encryptor.encrypt(&mut read_buffer,
&mut write_buffer,
true);
final_result.extend(write_buffer
.take_read_buffer()
.take_remaining().iter().map(|&i| i));
match result {
Ok(BufferResult::BufferUnderflow) => break,
Ok(_) => {},
Err(_) => return Err("Encryption failed")
}
}
Ok(final_result)
}
When I attempt to compile this version, I get the following error (paths removed for clarity):
error: source trait is private
let result = encryptor.encrypt(&mut read_buffer,
&mut write_buffer,
true);
error: source trait is private
let r = decryptor.decrypt(&mut read_buffer, &mut write_buffer, true);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The only way I've been able to change this type is to wrap the original function in a conversion function like this:
pub fn converted_enc(key: &[u8], data: &[u8])
-> Result<Vec<u8>, &'static str> {
match aes_enc_ecb_128(key,data) {
Ok(v) => Ok(v),
Err(_) => Err("Encryption failed")
}
}
What should I do instead of the above in order to get the return value to fit with the rest of my API, and why is the more direct method failing?
I'm using the following versions of rust/cargo:
rustc 1.2.0-nightly (0cc99f9cc 2015-05-17) (built 2015-05-18)
cargo 0.2.0-nightly (ac61996 2015-05-17) (built 2015-05-17)
I think you have come across a bug of the compiler. Your code should compile
You can use crypto::symmetriccipher::Encryptor; as a workaround:
pub fn aes_enc_ecb_128(key: &[u8], data: &[u8])
-> Result<Vec<u8>, &'static str> {
use crypto::symmetriccipher::Encryptor;
let mut encryptor = aes::ecb_encryptor(
aes::KeySize::KeySize128,
key,
blockmodes::NoPadding);
let mut final_result = Vec::<u8>::new();
let mut read_buffer = buffer::RefReadBuffer::new(data);
let mut buffer = [0; 4096];
let mut write_buffer = buffer::RefWriteBuffer::new(&mut buffer);
loop {
let result = encryptor.encrypt(&mut read_buffer,
&mut write_buffer,
true);
final_result.extend(write_buffer
.take_read_buffer()
.take_remaining().iter().map(|&i| i));
match result {
Ok(BufferResult::BufferUnderflow) => break,
Ok(_) => {},
Err(_) => return Err("Encryption failed")
}
}
Ok(final_result)
}

Resources