Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added lifetime parameters to all the writing systems #146

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "base64"
version = "0.13.0"
version = "0.13.1"
authors = ["Alice Maz <[email protected]>", "Marshall Pierce <[email protected]>"]
description = "encodes and decodes base64 as bytes or utf8"
repository = "https://github.com/marshallpierce/rust-base64"
Expand Down
16 changes: 10 additions & 6 deletions src/write/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ const MIN_ENCODE_CHUNK_SIZE: usize = 3;
///
/// It has some minor performance loss compared to encoding slices (a couple percent).
/// It does not do any heap allocation.
pub struct EncoderWriter<W: Write> {
pub struct EncoderWriter<'a, W: Write + 'a> {
config: Config,
/// Where encoded data is written to. It's an Option as it's None immediately before Drop is
/// called so that finish() can return the underlying writer. None implies that finish() has
Expand All @@ -71,9 +71,12 @@ pub struct EncoderWriter<W: Write> {
output_occupied_len: usize,
/// panic safety: don't write again in destructor if writer panicked while we were writing to it
panicked: bool,
/// We in some sense hold a "reference" to the writer inside.
/// tho we actually make it match delegate
_ref_lifetime: std::marker::PhantomData <Option <&'a mut W>>
}

impl<W: Write> fmt::Debug for EncoderWriter<W> {
impl<'a, W: Write + 'a> fmt::Debug for EncoderWriter<'a, W> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
Expand All @@ -86,9 +89,9 @@ impl<W: Write> fmt::Debug for EncoderWriter<W> {
}
}

impl<W: Write> EncoderWriter<W> {
impl<'a, W: Write + 'a> EncoderWriter<'a, W> {
/// Create a new encoder that will write to the provided delegate writer `w`.
pub fn new(w: W, config: Config) -> EncoderWriter<W> {
pub fn new(w: W, config: Config) -> EncoderWriter<'a, W>{
EncoderWriter {
config,
delegate: Some(w),
Expand All @@ -97,6 +100,7 @@ impl<W: Write> EncoderWriter<W> {
output: [0u8; BUF_SIZE],
output_occupied_len: 0,
panicked: false,
_ref_lifetime: core::default::Default::default(),
}
}

Expand Down Expand Up @@ -217,7 +221,7 @@ impl<W: Write> EncoderWriter<W> {
}
}

impl<W: Write> Write for EncoderWriter<W> {
impl<'a, W: Write + 'a> Write for EncoderWriter<'a, W> {
/// Encode input and then write to the delegate writer.
///
/// Under non-error circumstances, this returns `Ok` with the value being the number of bytes
Expand Down Expand Up @@ -371,7 +375,7 @@ impl<W: Write> Write for EncoderWriter<W> {
}
}

impl<W: Write> Drop for EncoderWriter<W> {
impl<'a, W: Write + 'a> Drop for EncoderWriter<'a, W> {
fn drop(&mut self) {
if !self.panicked {
// like `BufWriter`, ignore errors during drop
Expand Down
50 changes: 41 additions & 9 deletions src/write/encoder_string_writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,18 @@ use std::io::Write;
///
/// Because it has to validate that the base64 is UTF-8, it is about 80% as fast as writing plain
/// bytes to a `io::Write`.
pub struct EncoderStringWriter<S: StrConsumer> {
encoder: EncoderWriter<Utf8SingleCodeUnitWriter<S>>,
pub struct EncoderStringWriter<'a, S: StrConsumer + 'a> {
encoder: EncoderWriter<'a, Utf8SingleCodeUnitWriter<'a, S>>,
}

impl<S: StrConsumer> EncoderStringWriter<S> {
impl<'a, S: StrConsumer + 'a> EncoderStringWriter<'a, S> {
/// Create a EncoderStringWriter that will append to the provided `StrConsumer`.
pub fn from(str_consumer: S, config: Config) -> Self {
EncoderStringWriter {
encoder: EncoderWriter::new(Utf8SingleCodeUnitWriter { str_consumer }, config),
encoder: EncoderWriter::new(Utf8SingleCodeUnitWriter::<'a, S> {
str_consumer,
_life: core::default::Default::default()
}, config),
}
}

Expand All @@ -75,14 +78,14 @@ impl<S: StrConsumer> EncoderStringWriter<S> {
}
}

impl EncoderStringWriter<String> {
impl EncoderStringWriter<'static, String> {
/// Create a EncoderStringWriter that will encode into a new String with the provided config.
pub fn new(config: Config) -> Self {
EncoderStringWriter::from(String::new(), config)
}
}

impl<S: StrConsumer> Write for EncoderStringWriter<S> {
impl<'a, S: StrConsumer + 'a> Write for EncoderStringWriter<'a, S> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.encoder.write(buf)
}
Expand All @@ -99,7 +102,7 @@ pub trait StrConsumer {
}

/// As for io::Write, `StrConsumer` is implemented automatically for `&mut S`.
impl<S: StrConsumer + ?Sized> StrConsumer for &mut S {
impl<S: StrConsumer + ?Sized> StrConsumer for &'_ mut S {
fn consume(&mut self, buf: &str) {
(**self).consume(buf)
}
Expand All @@ -115,11 +118,12 @@ impl StrConsumer for String {
/// A `Write` that only can handle bytes that are valid single-byte UTF-8 code units.
///
/// This is safe because we only use it when writing base64, which is always valid UTF-8.
struct Utf8SingleCodeUnitWriter<S: StrConsumer> {
struct Utf8SingleCodeUnitWriter<'a, S: StrConsumer + 'a> {
str_consumer: S,
_life: std::marker::PhantomData <&'a S>
}

impl<S: StrConsumer> io::Write for Utf8SingleCodeUnitWriter<S> {
impl<'a, S: StrConsumer + 'a> io::Write for Utf8SingleCodeUnitWriter<'a, S> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
// Because we expect all input to be valid utf-8 individual bytes, we can encode any buffer
// length
Expand Down Expand Up @@ -173,4 +177,32 @@ mod tests {
assert_eq!(normal_encoded, stream_encoded);
}
}

/// This test should pass even if it just compiles.
#[test]
fn can_use_non_static_ref() {
#[allow(dead_code)]
fn write<'a>(out: &'a mut String, data: &[u8]) {
let mut rng = rand::thread_rng();
let config = random_config(&mut rng);

let mut stream_encoder = EncoderStringWriter::from(out, config);
stream_encoder.write_all(data).unwrap();
}
}


/// This test should pass even if it just compiles.
#[test]
fn can_still_use_without_specifying_lifetime() {
#[allow(dead_code)]
fn write(out: String, data: &[u8]) -> String{
let mut rng = rand::thread_rng();
let config = random_config(&mut rng);

let mut stream_encoder = EncoderStringWriter::from(out, config);
stream_encoder.write_all(data).unwrap();
stream_encoder.into_inner()
}
}
}