From dcd285e24e41d66f0bfbfc708f3e630a2c01bb82 Mon Sep 17 00:00:00 2001 From: Henri Sivonen Date: Thu, 5 Jan 2017 14:20:35 +0200 Subject: [PATCH] Provide access to the underlying container of writers in the common case. When `StringWriter` is a `String`, provide access to the `String`. When `ByteWriter` is a `Vec`, provide access to the `Vec`. This allows converters that write directly to a slice without virtual method calls inside the conversion loop to work without an intermediate copy in the common case (i.e. with the default trait implementations) while not breaking compatibility with custom implementations of the traits. --- src/types/lib.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/types/lib.rs b/src/types/lib.rs index 435410b4..ff73321b 100644 --- a/src/types/lib.rs +++ b/src/types/lib.rs @@ -83,6 +83,12 @@ pub trait ByteWriter { /// Writes a number of bytes. fn write_bytes(&mut self, v: &[u8]); + + /// If this `ByteWriter` is a `Vec`, returns a mutable reference to + /// `self` as `Some(&mut Vec)`. Returns `None` otherwise. + fn as_mut_vec(&mut self) -> Option<&mut Vec> { + None + } } impl ByteWriter for Vec { @@ -97,6 +103,10 @@ impl ByteWriter for Vec { fn write_bytes(&mut self, v: &[u8]) { self.extend_from_slice(v); } + + fn as_mut_vec(&mut self) -> Option<&mut Vec> { + Some(self) + } } /// String writer used by decoders. In most cases this will be an owned string. @@ -114,6 +124,12 @@ pub trait StringWriter { /// Writes a string. fn write_str(&mut self, s: &str); + + /// If this `StringWriter` is a `String`, returns a mutable reference to + /// `self` as `Some(&mut String)`. Returns `None` otherwise. + fn as_mut_string(&mut self) -> Option<&mut String> { + None + } } impl StringWriter for String { @@ -128,6 +144,10 @@ impl StringWriter for String { fn write_str(&mut self, s: &str) { self.push_str(s); } + + fn as_mut_string(&mut self) -> Option<&mut String> { + Some(self) + } } /// Encoder converting a Unicode string into a byte sequence.