1package cmd
2
3import (
4 "bufio"
5 "bytes"
6 "fmt"
7 "io"
8)
9
10type CryptFn func(in io.Reader, inLen int64, out io.Writer) (int, error)
11
12func Handle(in io.Reader, out io.Writer, fn CryptFn) error {
13 reader := bufio.NewReader(in)
14 for {
15 line, err := reader.ReadString('\n')
16 if err != nil {
17 if err == io.EOF {
18 break
19 }
20 return err
21 }
22
23 var numBytes uint
24 n, _ := fmt.Sscanf(line, "data %d\n", &numBytes)
25 if n != 1 || numBytes == 0 {
26 fmt.Fprint(out, line)
27 continue
28 }
29
30 writer := bytes.NewBuffer(nil)
31 n, err = fn(reader, int64(numBytes), writer)
32 if err != nil {
33 return err
34 }
35
36 fmt.Fprintf(out, "data %d\n", n)
37 _, err = writer.WriteTo(out)
38 if err != nil {
39 return err
40 }
41 }
42
43 return nil
44}