~poldi1405/go-yenc

ref: db8820d1a641a361e795ea23f26415f1c5eec62d go-yenc/encoder.go -rw-r--r-- 1.2 KiB
db8820d1 — Moritz Poldrack started work on encoder 11 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package yenc

import (
	"bytes"
	"fmt"
	"hash"
	"hash/crc32"
	"io"
	"sync"
)

type Encoder struct {
	file     io.Writer
	buffer   bytes.Buffer
	writeMtx sync.Mutex

	LineLength int
	BlockSize  int
	CRC        hash.Hash32
}

func NewEncoder(w io.Writer) *Encoder {
	enc := &Encoder{
		file:       w,
		LineLength: 128,
		BlockSize:  0,
		CRC:        crc32.NewIEEE(),
	}
	return enc
}

func (e *Encoder) Write(slice []byte) (int, error) {
	e.writeMtx.Lock()
	defer e.writeMtx.Unlock()

	var bytesWritten int
	remainder := len(slice) % 8
	parts := getParts(&slice)

	maxindex := len(*parts) - 1

	var err error
	var n int
	var encoded []byte

	for i, p := range *parts {
		encoded = yenc(&p)

		if i == maxindex {
			break
		}

		n, err = e.buffer.Write(encoded)
		if err != nil {
			return bytesWritten, fmt.Errorf("failed writing yenc to output-buffer: %v")
		}
		bytesWritten += n
	}

	n, err = e.buffer.Write(encoded[:len(encoded)-(8-remainder)])
	if err != nil {
		return bytesWritten, fmt.Errorf("failed writing yenc to output-buffer: %v")
	}
	bytesWritten += n

	err = e.writeBlock(false)
	if err != nil {
		return n, err
	}

	return bytesWritten, nil
}

func (e *Encoder) writeBlock(closing bool) error {
	return nil
}