0

I'm trying to implement deserializer for a BERT data which comes from an another program via sockets. For the following code:

use std::io::{self, Read};

#[derive(Clone, Copy)]
pub struct Deserializer<R: Read> {
    reader: R,
    header: Option<u8>,
}

impl<R: Read> Read for Deserializer<R> {
    #[inline]
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.reader.read(buf)
    }
}

impl<R: Read> Deserializer<R> {
    /// Creates the BERT parser from an `std::io::Read`.
    #[inline]
    pub fn new(reader: R) -> Deserializer<R> {
        Deserializer {
            reader: reader,
            header: None,
        }
    }

    #[inline]
    pub fn read_string(&mut self, len: usize) -> io::Result<String> {
        let mut string_buffer = String::with_capacity(len);
        self.reader.take(len as u64).read_to_string(&mut string_buffer);
        Ok(string_buffer)
    }
}

The Rust compiler generates an error, when I'm trying to read a string from a passed data:

error: cannot move out of borrowed content [E0507]
        self.reader.take(len as u64).read_to_string(&mut string_buffer);
        ^~~~
help: run `rustc --explain E0507` to see a detailed explanation

How can I fix this even if my Deserializer<R> struct has had Clone/Copy traits?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Relrin
  • 760
  • 2
  • 10
  • 28
  • 4
    Perhaps you can [edit] your question to expand on how *this* question differs from the [**74** other questions about the same error message](http://stackoverflow.com/search?q=%5Brust%5D+cannot+move+out+of+borrowed+content+is%3Aq)? You are expected to [show a large amount of effort](http://meta.stackoverflow.com/q/261592/155423) when asking a question. – Shepmaster Sep 07 '16 at 19:01
  • 1
    Possible duplicate of [Cannot move out of borrowed content \[E0507\]](http://stackoverflow.com/questions/37797035/cannot-move-out-of-borrowed-content-e0507) – polka Sep 07 '16 at 20:55
  • 2
    Possible duplicate of [Cannot move out of borrowed content](http://stackoverflow.com/questions/28158738/cannot-move-out-of-borrowed-content) – just.ru Sep 07 '16 at 21:33

1 Answers1

6

The take method takes self:

fn take(self, limit: u64) -> Take<Self> where Self: Sized

so you cannot use it on anything borrowed.

Use the by_ref method. Replace the error line with this:

{
      let reference = self.reader.by_ref();
      reference.take(len as u64).read_to_string(&mut string_buffer);
}
Cecilio Pardo
  • 1,717
  • 10
  • 13