When possible, prefer from_buffered_reader to from_reader.

- Objects that work with either a `BufferedReader` or a `Read`er are
    often more efficient when they are directly passed the
    `BufferedReader`.

  - Prefer `from_buffered_reader` to `from_reader` when possible.
This commit is contained in:
Neal H. Walfield 2024-04-12 11:40:03 +02:00
parent c2d5f24782
commit 03c6e57d10
No known key found for this signature in database
GPG Key ID: 6863C9AD5B4D22D3
18 changed files with 30 additions and 32 deletions

4
Cargo.lock generated
View File

@ -344,9 +344,9 @@ dependencies = [
[[package]] [[package]]
name = "buffered-reader" name = "buffered-reader"
version = "1.3.0" version = "1.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b9b0a25eb06e83579bc985d836e1e3b957a7201301b48538764d2b2e78090d4" checksum = "cd098763fdb64579407a8c83cf0d751e6d4a7e161d0114c89cc181a2ca760ec8"
dependencies = [ dependencies = [
"bzip2", "bzip2",
"flate2", "flate2",

View File

@ -29,7 +29,7 @@ gitlab = { repository = "sequoia-pgp/sequoia-sq" }
maintenance = { status = "actively-developed" } maintenance = { status = "actively-developed" }
[dependencies] [dependencies]
buffered-reader = { version = "1.0.0", default-features = false, features = ["compression"] } buffered-reader = { version = "1.3.1", default-features = false, features = ["compression"] }
dirs = "5" dirs = "5"
dot-writer = { version = "0.1.3", optional = true } dot-writer = { version = "0.1.3", optional = true }
sequoia-openpgp = { version = "1.18", default-features = false, features = ["compression"] } sequoia-openpgp = { version = "1.18", default-features = false, features = ["compression"] }

View File

@ -1,13 +1,13 @@
use anyhow::Context; use anyhow::Context;
use buffered_reader::{BufferedReader, Dup, Generic}; use buffered_reader::{BufferedReader, Dup};
use sequoia_openpgp as openpgp; use sequoia_openpgp as openpgp;
use openpgp::{ use openpgp::{
Cert, Cert,
Result, Result,
armor, armor,
packet::UserID, packet::UserID,
parse::{Parse, stream::DecryptorBuilder}, parse::{Cookie, Parse, stream::DecryptorBuilder},
serialize::Serialize, serialize::Serialize,
}; };
use sequoia_autocrypt as autocrypt; use sequoia_autocrypt as autocrypt;
@ -43,8 +43,7 @@ fn import<'store, 'rstore>(mut config: Config<'store, 'rstore>,
let mut acc = Vec::new(); let mut acc = Vec::new();
// First, get the Autocrypt headers from the outside. // First, get the Autocrypt headers from the outside.
let input = Generic::new(input, None); let mut dup = Dup::with_cookie(input, Cookie::default());
let mut dup = Dup::new(input);
let ac = autocrypt::AutocryptHeaders::from_reader(&mut dup)?; let ac = autocrypt::AutocryptHeaders::from_reader(&mut dup)?;
let from = UserID::from( let from = UserID::from(
ac.from.as_ref().ok_or(anyhow::anyhow!("no From: header"))? ac.from.as_ref().ok_or(anyhow::anyhow!("no From: header"))?
@ -102,8 +101,7 @@ fn import<'store, 'rstore>(mut config: Config<'store, 'rstore>,
helper.quiet(true); helper.quiet(true);
let policy = config.policy.clone(); let policy = config.policy.clone();
let mut decryptor = match let mut decryptor = match DecryptorBuilder::from_buffered_reader(input)?
DecryptorBuilder::from_reader(input)?
.with_policy(&policy, None, helper) .with_policy(&policy, None, helper)
.context("Decryption failed") .context("Decryption failed")
{ {
@ -178,7 +176,7 @@ fn encode_sender(config: Config, command: &cli::autocrypt::EncodeSenderCommand)
{ {
let input = command.input.open()?; let input = command.input.open()?;
let mut output = command.output.create_safe(config.force)?; let mut output = command.output.create_safe(config.force)?;
let cert = Cert::from_reader(input)?; let cert = Cert::from_buffered_reader(input)?;
let addr = command.address.clone() let addr = command.address.clone()
.or_else(|| { .or_else(|| {
cert.with_policy(config.policy, None) cert.with_policy(config.policy, None)

View File

@ -36,7 +36,7 @@ where 'store: 'rstore
let inner = || -> Result<()> { let inner = || -> Result<()> {
for input in inputs.into_iter() { for input in inputs.into_iter() {
let input = FileOrStdin::from(input).open()?; let input = FileOrStdin::from(input).open()?;
let raw_certs = RawCertParser::from_reader(input)?; let raw_certs = RawCertParser::from_buffered_reader(input)?;
let policy = config.policy.clone(); let policy = config.policy.clone();
let time = config.time; let time = config.time;

View File

@ -267,7 +267,7 @@ pub fn lint(config: Config, mut args: Command) -> Result<()> {
Some(path) => path.display().to_string(), Some(path) => path.display().to_string(),
None => "/dev/stdin".to_string(), None => "/dev/stdin".to_string(),
}; };
let certp = CertParser::from_reader(&mut input_reader)?; let certp = CertParser::from_buffered_reader(&mut input_reader)?;
'next_cert: for (certi, certo) in certp.enumerate() { 'next_cert: for (certi, certo) in certp.enumerate() {
match certo { match certo {
Err(err) => { Err(err) => {

View File

@ -58,7 +58,7 @@ pub fn dispatch(config: Config, c: inspect::Command)
} }
} }
openpgp::parse::PacketParser::from_reader(input.open()?)? openpgp::parse::PacketParser::from_buffered_reader(input.open()?)?
} else { } else {
let cert_store = config.cert_store_or_else()?; let cert_store = config.cert_store_or_else()?;
for cert in c.cert.into_iter() { for cert in c.cert.into_iter() {

View File

@ -26,7 +26,7 @@ use crate::decrypt_key;
pub fn adopt(config: Config, command: cli::key::AdoptCommand) -> Result<()> pub fn adopt(config: Config, command: cli::key::AdoptCommand) -> Result<()>
{ {
let input = command.certificate.open()?; let input = command.certificate.open()?;
let cert = Cert::from_reader(input)?; let cert = Cert::from_buffered_reader(input)?;
let mut wanted: Vec<( let mut wanted: Vec<(
KeyHandle, KeyHandle,
Option<( Option<(

View File

@ -16,7 +16,7 @@ pub fn attest_certifications(
let all = !command.none; // All is the default. let all = !command.none; // All is the default.
let input = command.key.open()?; let input = command.key.open()?;
let key = Cert::from_reader(input)?; let key = Cert::from_buffered_reader(input)?;
// Get a signer. // Get a signer.
let mut passwords = Vec::new(); let mut passwords = Vec::new();

View File

@ -31,7 +31,7 @@ pub fn dispatch(config: Config, command: cli::key::expire::Command)
}; };
let input = command.input.open()?; let input = command.input.open()?;
let key = Cert::from_reader(input)?; let key = Cert::from_buffered_reader(input)?;
if ! key.is_tsk() { if ! key.is_tsk() {
return Err(anyhow::anyhow!("Certificate has no secrets")); return Err(anyhow::anyhow!("Certificate has no secrets"));
} }

View File

@ -15,7 +15,7 @@ pub fn password(
command: cli::key::PasswordCommand, command: cli::key::PasswordCommand,
) -> Result<()> { ) -> Result<()> {
let input = command.input.open()?; let input = command.input.open()?;
let key = Cert::from_reader(input)?; let key = Cert::from_buffered_reader(input)?;
if !key.is_tsk() { if !key.is_tsk() {
return Err(anyhow::anyhow!("Certificate has no secrets")); return Err(anyhow::anyhow!("Certificate has no secrets"));

View File

@ -228,7 +228,7 @@ fn subkey_add(
command: SubkeyAddCommand, command: SubkeyAddCommand,
) -> Result<()> { ) -> Result<()> {
let input = command.input.open()?; let input = command.input.open()?;
let cert = Cert::from_reader(input)?; let cert = Cert::from_buffered_reader(input)?;
let valid_cert = cert.with_policy(config.policy, config.time)?; let valid_cert = cert.with_policy(config.policy, config.time)?;
let validity = command let validity = command

View File

@ -228,7 +228,7 @@ fn userid_add(
command: cli::key::UseridAddCommand, command: cli::key::UseridAddCommand,
) -> Result<()> { ) -> Result<()> {
let input = command.input.open()?; let input = command.input.open()?;
let key = Cert::from_reader(input)?; let key = Cert::from_buffered_reader(input)?;
// Make sure the user IDs are in canonical form. If not, and // Make sure the user IDs are in canonical form. If not, and
// `--allow-non-canonical-userids` is not set, error out. // `--allow-non-canonical-userids` is not set, error out.
@ -393,7 +393,7 @@ fn userid_strip(
command: cli::key::UseridStripCommand, command: cli::key::UseridStripCommand,
) -> Result<()> { ) -> Result<()> {
let input = command.input.open()?; let input = command.input.open()?;
let key = Cert::from_reader(input)?; let key = Cert::from_buffered_reader(input)?;
let orig_cert_valid = key.with_policy(config.policy, None).is_ok(); let orig_cert_valid = key.with_policy(config.policy, None).is_ok();

View File

@ -924,7 +924,7 @@ pub fn dispatch_keyserver(mut config: Config,
})?, })?,
Publish(c) => rt.block_on(async { Publish(c) => rt.block_on(async {
let mut input = c.input.open()?; let mut input = c.input.open()?;
let cert = Arc::new(Cert::from_reader(&mut input). let cert = Arc::new(Cert::from_buffered_reader(&mut input).
context("Malformed key")?); context("Malformed key")?);
let mut requests = tokio::task::JoinSet::new(); let mut requests = tokio::task::JoinSet::new();
@ -1048,7 +1048,7 @@ pub fn dispatch_wkd(mut config: Config, c: cli::network::wkd::Command)
} else { } else {
wkd::Variant::Advanced wkd::Variant::Advanced
}; };
let parser = CertParser::from_reader(f)?; let parser = CertParser::from_buffered_reader(f)?;
let certs: Vec<Cert> = parser.filter_map(|cert| cert.ok()) let certs: Vec<Cert> = parser.filter_map(|cert| cert.ok())
.collect(); .collect();
for cert in certs { for cert in certs {
@ -1081,7 +1081,7 @@ pub fn dispatch_dane(mut config: Config, c: cli::network::dane::Command)
use crate::cli::network::dane::Subcommands::*; use crate::cli::network::dane::Subcommands::*;
match c.subcommand { match c.subcommand {
Generate(c) => { Generate(c) => {
for cert in CertParser::from_reader(c.input.open()?)? { for cert in CertParser::from_buffered_reader(c.input.open()?)? {
let cert = cert?; let cert = cert?;
let vc = match cert.with_policy(config.policy, config.time) { let vc = match cert.with_policy(config.policy, config.time) {
Ok(vc) => vc, Ok(vc) => vc,

View File

@ -29,7 +29,7 @@ fn detect_armor_kind(
let dup = Dup::with_cookie(input, Cookie::default()); let dup = Dup::with_cookie(input, Cookie::default());
let mut limitor = Limitor::with_cookie( let mut limitor = Limitor::with_cookie(
dup, ARMOR_DETECTION_LIMIT, Cookie::default()).into_boxed(); dup, ARMOR_DETECTION_LIMIT, Cookie::default()).into_boxed();
let kind = match PacketParser::from_reader(&mut limitor) { let kind = match PacketParser::from_buffered_reader(&mut limitor) {
Ok(PacketParserResult::Some(pp)) => match pp.next() { Ok(PacketParserResult::Some(pp)) => match pp.next() {
Ok((Packet::Signature(_), _)) => armor::Kind::Signature, Ok((Packet::Signature(_), _)) => armor::Kind::Signature,
Ok((Packet::SecretKey(_), _)) => armor::Kind::SecretKey, Ok((Packet::SecretKey(_), _)) => armor::Kind::SecretKey,
@ -59,9 +59,9 @@ pub fn dispatch(config: Config, command: cli::toolbox::armor::Command)
dup, ARMOR_DETECTION_LIMIT, Cookie::default()); dup, ARMOR_DETECTION_LIMIT, Cookie::default());
let (already_armored, have_kind) = { let (already_armored, have_kind) = {
let mut reader = let mut reader =
armor::Reader::from_reader( armor::Reader::from_buffered_reader(
&mut limitor, &mut limitor,
armor::ReaderMode::Tolerant(None)); armor::ReaderMode::Tolerant(None))?;
(reader.data(8).is_ok(), reader.kind()) (reader.data(8).is_ok(), reader.kind())
}; };
let mut input = let mut input =
@ -91,9 +91,9 @@ pub fn dispatch(config: Config, command: cli::toolbox::armor::Command)
if already_armored { if already_armored {
// Dearmor and copy to change the type. // Dearmor and copy to change the type.
let mut reader = let mut reader =
armor::Reader::from_reader( armor::Reader::from_buffered_reader(
input, input,
armor::ReaderMode::Tolerant(None)); armor::ReaderMode::Tolerant(None))?;
io::copy(&mut reader, &mut output)?; io::copy(&mut reader, &mut output)?;
} else { } else {
io::copy(&mut input, &mut output)?; io::copy(&mut input, &mut output)?;

View File

@ -14,7 +14,7 @@ pub fn dispatch(config: Config, command: cli::toolbox::dearmor::Command)
let mut input = command.input.open()?; let mut input = command.input.open()?;
let mut output = command.output.create_safe(config.force)?; let mut output = command.output.create_safe(config.force)?;
let mut filter = armor::Reader::from_reader(&mut input, None); let mut filter = armor::Reader::from_buffered_reader(&mut input, None)?;
io::copy(&mut filter, &mut output)?; io::copy(&mut filter, &mut output)?;
Ok(()) Ok(())

View File

@ -16,7 +16,7 @@ pub fn dispatch(
let input = command.input.open()?; let input = command.input.open()?;
let mut output = command.output.create_safe(config.force)?; let mut output = command.output.create_safe(config.force)?;
let cert = Cert::from_reader(input)?; let cert = Cert::from_buffered_reader(input)?;
if command.binary { if command.binary {
cert.serialize(&mut output)?; cert.serialize(&mut output)?;
} else { } else {

View File

@ -110,7 +110,7 @@ pub fn split(_config: Config, c: SplitCommand) -> Result<()>
// We (ab)use the mapping feature to create byte-accurate dumps of // We (ab)use the mapping feature to create byte-accurate dumps of
// nested packets. // nested packets.
let mut ppr = let mut ppr =
openpgp::parse::PacketParserBuilder::from_reader(input)? openpgp::parse::PacketParserBuilder::from_buffered_reader(input)?
.map(true).build()?; .map(true).build()?;
fn join(pos: &[usize], delimiter: &str) -> String { fn join(pos: &[usize], delimiter: &str) -> String {

View File

@ -29,7 +29,7 @@ pub const NULL_POLICY: &NullPolicy = &NullPolicy::new();
pub fn read_cert(input: Option<&Path>) -> Result<Cert> { pub fn read_cert(input: Option<&Path>) -> Result<Cert> {
let input = FileOrStdin::from(input).open()?; let input = FileOrStdin::from(input).open()?;
let cert = CertParser::from_reader(input)?.collect::<Vec<_>>(); let cert = CertParser::from_buffered_reader(input)?.collect::<Vec<_>>();
let cert = match cert.len() { let cert = match cert.len() {
0 => Err(anyhow!("No certificates provided."))?, 0 => Err(anyhow!("No certificates provided."))?,
1 => cert.into_iter().next().expect("have one")?, 1 => cert.into_iter().next().expect("have one")?,