Есть ли способ создать Box из Vecкоторый реализует черту чтения? - PullRequest
0 голосов
/ 23 апреля 2019

Я пишу фрагмент кода, который с помощью ящика lopdf записывает PDF на Vec.Затем я хочу напечатать PDF-файл через ящик IPP, но для этого нужна коробка, которую я не могу создать

Я пробовал много вещей, но я всегда сталкиваюсь с проблемами владения.Еще я попробовал создать Box из необработанного указателя, но он вывел программу из строя.

let mut doc = Document::load("file.pdf").unwrap();
let mut doc_bytes = Vec::new();
//redacted
doc.save_to(&mut doc_bytes);
let doc_slice = doc_bytes.as_slice();
let buffer = std::io::BufReader::new(doc_slice.to_vec().as_slice());
let doc_box = Box::from(buffer);
let client = ipp::IppClient::new("printer URL");
let print_job = ipp::operation::PrintJob::new(doc_box, &"username", None)
client.send(print_job).unwrap();

Она должна напечатать файл на принтере.Это не скомпилирует, говоря, что

temporary value dropped while borrowed

creates a temporary which is freed while still in use rustc(E0716)
main.rs(6, 70): creates a temporary which is freed while still in use
main.rs(6, 100): temporary value is freed at the end of this statement
main.rs(9, 79): cast requires that borrow lasts for `'static`

на doc_slice.to_vec().

По сути, я пытаюсь сделать что-то вроде этого (https://github.com/dremon/ipp.rs/blob/master/ipp-client/examples/print-job.rs),, но без чтения изфайл.

Пример минимального, полного и проверяемого

Cargo.toml

[package]
name = "example"
version = "0.1.0"
authors = ["you <you@example.com>"]
edition = "2018"

[dependencies]
ipp = "0.2.1"

main.rs

fn main(){
  let mut doc_bytes = Vec::<u8>::new();
  doc_bytes.set_len(720000);
  let client = ipp::IppClient::new("http://printer_url");
  let print_job = ipp::operation::PrintJob::new(doc_bytes.into_boxed_slice(), &"user", None);
  client.send(print_job).unwrap();
}

С этим кодом я получаюдве ошибки:

   Compiling example v0.1.0 (/path)
error[E0277]: the trait bound `[u8]: std::io::Read` is not satisfied
 --> src/main.rs:5:49
  |
5 |   let print_job = ipp::operation::PrintJob::new(doc_bytes.into_boxed_slice(), &"username", None);
  |                                                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `std::io::Read` is not implemented for `[u8]`
  |
  = help: the following implementations were found:
            <&'a [u8] as std::io::Read>
  = note: required for the cast to the object type `dyn std::io::Read`

error[E0277]: the size for values of type `[u8]` cannot be known at compilation time
 --> src/main.rs:5:49
  |
5 |   let print_job = ipp::operation::PrintJob::new(doc_bytes.into_boxed_slice(), &"username", None);
  |                                                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
  |
  = help: the trait `std::marker::Sized` is not implemented for `[u8]`
  = note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
  = note: required for the cast to the object type `dyn std::io::Read`

error: aborting due to 2 previous errors

For more information about this error, try `rustc --explain E0277`.
error: Could not compile `pettorine`.

To learn more, run the command again with --verbose.

Я заметил, что получаю новую ошибку!

Заранее спасибо за вашу поддержку

1 Ответ

0 голосов
/ 26 апреля 2019

ок, нашел ответ (https://github.com/dremon/ipp.rs/issues/6)

let mut doc = Document::load("pettorina.pdf").unwrap();
let mut doc_bytes = Vec::new();
let mut num = " ".repeat(((4.0 -(pettorina.numero as f32).log10().floor())/2.0) as usize);
num.push_str(&pettorina.numero.to_string());
doc.version = "1.4".to_string();
doc.replace_text(1, "num", &num);
doc.replace_text(1, "NOME", &pettorina.nome.to_ascii_uppercase());
doc.save_to(&mut doc_bytes);
let client = ipp::IppClient::new("printer_url");
let print_job = ipp::operation::PrintJob::new(Box::new(std::io::Cursor::new(doc_bytes)), &"pettorine", None);
client.send(print_job).unwrap();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...