--- /dev/null
+/*
+ * Copyright (c) 2017 Tilman Sauerbeck (tilman at code-monkey de)
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+use buffer::Buffer;
+use crc32::Crc32;
+use fmt::fmt_x32;
+
+pub struct Yencode<'a> {
+ buffer: &'a mut Buffer,
+ crc: Crc32,
+}
+
+impl<'a> Yencode<'a> {
+ pub fn new(buffer: &mut Buffer) -> Yencode {
+ Yencode {
+ buffer: buffer,
+ crc: Crc32::new(),
+ }
+ }
+
+ pub fn start(&mut self, filename: &[u8]) {
+ self.buffer.write(b"=ybegin name=");
+ self.buffer.write(filename);
+ self.buffer.write(b"\n");
+ }
+
+ fn encode_line(&mut self, input_buf: &[u8], output_buf: &mut [u8]) {
+ let mut output_buf_offset = 0;
+
+ for input in input_buf {
+ let mut c : u8 = *input;
+ c += 42;
+
+ match c {
+ b'\0' | b'\n' | b'\r' | b'=' => {
+ output_buf[output_buf_offset] = b'=';
+ output_buf_offset += 1;
+
+ c += 64;
+ },
+ _ => {
+ }
+ }
+
+ output_buf[output_buf_offset] = c;
+ output_buf_offset += 1;
+ }
+
+ output_buf[output_buf_offset] = b'\n';
+ output_buf_offset += 1;
+
+ if output_buf[0] == b'.' {
+ self.buffer.write(b".");
+ }
+
+ self.buffer.write(&output_buf[0..output_buf_offset]);
+ }
+
+ pub fn data(&mut self, buf: &[u8]) {
+ self.crc.update(buf);
+
+ const INPUT_BYTES_PER_LINE : usize = 128;
+
+ for chunk in buf.chunks(INPUT_BYTES_PER_LINE) {
+ let mut linebuf = [0u8; INPUT_BYTES_PER_LINE << 1];
+
+ self.encode_line(chunk, &mut linebuf);
+ }
+ }
+
+ pub fn finish(&mut self) {
+ let mut yend = [b' '; 23];
+
+ yend[0..].copy_from_slice(b"=yend crc32=xxxxxxxx\n.\n");
+
+ fmt_x32(&mut yend[12..], self.crc.finish());
+
+ self.buffer.write(¥d);
+ }
+}