Skip to content

Instantly share code, notes, and snippets.

Created March 4, 2016 17:10
Show Gist options
  • Save anonymous/83dbe08d13bcced85a81 to your computer and use it in GitHub Desktop.
Save anonymous/83dbe08d13bcced85a81 to your computer and use it in GitHub Desktop.
Shared via Rust Playground
use std::io::Write;
struct LfIter<I> where I: Iterator {
iter: I,
lf_every: usize,
items: usize
}
impl<I> LfIter<I> where I: Iterator {
fn new(iter: I, lf_every: usize) -> LfIter<I> {
LfIter {
iter: iter,
lf_every: lf_every,
items: 0
}
}
}
impl<I> Iterator for LfIter<I> where I: Iterator<Item=u8> {
type Item = u8;
fn next(&mut self) -> Option<Self::Item> {
if self.items >= self.lf_every {
self.items = 0;
Some(SEP)
} else {
self.items = self.items + 1;
self.iter.next()
}
}
}
const SEP: u8 = 10u8; // LF
const BUF_SIZE: usize = 10; // 64 * 1024
const WRAP_LEN: usize = 4; // 60
fn main() {
let d = "ABCDEFGHIJKLNMOPQRSTUVWXYZ".as_bytes();
let sout = std::io::stdout();
let mut out = sout.lock();
let mut lf_iter = LfIter::new(d.iter().cloned(), WRAP_LEN);
let mut buf = [0 as u8; BUF_SIZE];
loop {
for i in 0..BUF_SIZE {
if let Some(b) = lf_iter.next() {
buf[i] = b;
} else {
let _ = out.write(&buf[0..i]);
return;
}
}
let _ = out.write(&buf);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment