Efficiently Reading and Writing with Go's bufio Package
The bufio package in Go provides buffered I/O operations, which can significantly improve the performance of reading from and writing to I/O sources like files or network connections. This challenge will test your understanding of how to leverage bufio for efficient data handling.
Problem Description
Your task is to implement a Go program that reads data from a simulated input stream and processes it, then writes the processed data to a simulated output stream. You will need to utilize bufio.Reader for efficient reading and bufio.Writer for efficient writing.
Requirements:
- Simulated Input: Create a way to simulate an input stream. This can be done using
strings.NewReaderfor simplicity. The input will consist of multiple lines of text. - Buffered Reading: Use
bufio.NewReaderto read the input stream line by line. - Data Processing: For each line read, perform a simple transformation. For this challenge, convert the entire line to uppercase.
- Buffered Writing: Use
bufio.NewWriterto write the processed (uppercase) lines to an output stream. Abytes.Bufferis a suitable target for the output stream. - Flushing Output: Ensure that all buffered data is written to the output stream at the end of the process using
Flush(). - Output Verification: After processing all lines, retrieve the content from the output buffer and verify that it contains the correctly processed data.
Expected Behavior:
The program should read each line from the input, convert it to uppercase, and write it to the output. Each line in the output should be terminated by a newline character, mirroring the input structure.
Edge Cases:
- Empty Input: The program should handle cases where the input stream is empty gracefully.
- Lines with Leading/Trailing Whitespace: Whitespace should be preserved within the lines but processed as part of the line.
- Empty Lines: Empty lines in the input should result in empty lines in the output.
Examples
Example 1:
Input:
Hello, Go!
This is a test.
Output:
HELLO, GO!
THIS IS A TEST.
Explanation:
The input lines are read, converted to uppercase, and written to the output. The blank line is also preserved.
Example 2:
Input:
single line
Output:
SINGLE LINE
Explanation:
A single line input is processed correctly.
Example 3:
Input:
Output:
Explanation:
An empty input stream results in an empty output stream.
Constraints
- The input will consist of standard ASCII characters.
- The total size of the input data will not exceed 1MB.
- The program should be efficient and avoid unnecessary memory allocations.
- Use only standard Go libraries.
Notes
- Consider using
reader.ReadString('\n')for reading lines. - Remember to
Flush()thebufio.Writerbefore reading from the output buffer. - The
bufio.Writershould be associated with abytes.Bufferto easily retrieve the written data. - Pay attention to error handling for I/O operations.