Implementing a Custom Write Trait in Rust
Rust's standard library provides a powerful Write trait for handling output streams. This challenge asks you to implement your own simplified version of this trait to understand trait fundamentals and how they enable polymorphic behavior. You'll create a Write trait and then implement it for different data structures, allowing them to write their contents to a designated output.
Problem Description
Your task is to define a Rust trait named Write. This trait should have a single method, write, that takes a mutable reference to itself (&mut self) and a string slice (&str) as input. The write method should append the provided string slice to the internal buffer of the implementing type.
You will then need to implement this Write trait for two specific types:
StringBuffer: A struct that holds its written content in aString.VecBuffer: A struct that holds its written content as aVec<u8>.
Your implementations should correctly append the input string slice to the respective internal buffers.
Key Requirements:
- Define a trait named
Writewith awrite(&mut self, content: &str)method. - Implement
WriteforStringBuffer. - Implement
WriteforVecBuffer. - The
writemethod should append thecontentto the internal storage of the implementing type.
Expected Behavior:
When write is called on an instance of StringBuffer or VecBuffer, the provided content should be added to the end of its stored data.
Examples
Example 1: StringBuffer
let mut buffer = StringBuffer::new();
buffer.write("Hello, ");
buffer.write("world!");
// Expected internal state: "Hello, world!"
Example 2: VecBuffer
let mut buffer = VecBuffer::new();
buffer.write("Rust");
buffer.write(" ");
buffer.write("is");
buffer.write(" ");
buffer.write("fun!");
// Expected internal state: vec![82, 117, 115, 116, 32, 105, 115, 32, 102, 117, 110, 33] (ASCII for "Rust is fun!")
Example 3: Mixed Usage
fn process_write(writer: &mut dyn Write, data: &str) {
writer.write(data);
}
let mut string_buf = StringBuffer::new();
process_write(&mut string_buf, "First part.");
let mut vec_buf = VecBuffer::new();
process_write(&mut vec_buf, "Second part.");
// At this point, string_buf would contain "First part."
// and vec_buf would contain the bytes for "Second part.".
Constraints
- The
Writetrait must be defined usingtrait Write. - The
writemethod must accept&mut selfandcontent: &str. StringBuffermust store its data in aString.VecBuffermust store its data in aVec<u8>.- The solution should be purely in Rust.
Notes
- Consider how
&strneeds to be converted tou8for theVecBufferimplementation. Theas_bytes()method on strings can be helpful here. - Think about how traits enable polymorphism. The third example demonstrates this by using a trait object (
&mut dyn Write). - You will need to define the structs
StringBufferandVecBufferyourself, along with a way to create new instances (e.g., anew()associated function).