-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert.go
82 lines (66 loc) · 1.43 KB
/
convert.go
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
77
78
79
80
81
82
package rom
import (
"errors"
"io"
"os"
)
// Converts a ROM to native Z64 format
func ConvertRomFormat(inpath string, outpath string) error {
const bufferSize = 2048
info, err := FromPath(inpath)
if err != nil {
return err
}
fileFormat := info.File.Format.Code
if fileFormat == FormatZ64 {
return errors.New("File is already in the native Z64 format")
}
source, err := os.Open(inpath)
if err != nil {
return err
}
defer source.Close()
dest, err := os.Create(outpath)
if err != nil {
return err
}
defer dest.Close()
for {
buf := make([]byte, bufferSize)
n, err := source.Read(buf)
if err != nil && err != io.EOF {
return err
}
if n == 0 {
break
}
buf = maybeReverseBytes(buf, fileFormat)
if _, err := dest.Write(buf[:n]); err != nil {
return err
}
}
return nil
}
func maybeReverseBytes(bytes []byte, romFormat string) []byte {
if romFormat == FormatV64 {
return reverseBytes(bytes, 2)
}
if romFormat == FormatN64 {
return reverseBytes(bytes, 4)
}
return bytes
}
func reverseBytes(bytes []byte, size int) (reversed []byte) {
for _, chunk := range chunk(bytes, size) {
for i := len(chunk) - 1; i >= 0; i = i - 1 {
reversed = append(reversed, chunk[i])
}
}
return reversed
}
func chunk(bytes []byte, chunkSize int) (chunks [][]byte) {
for chunkSize < len(bytes) {
bytes, chunks = bytes[chunkSize:], append(chunks, bytes[0:chunkSize:chunkSize])
}
return append(chunks, bytes)
}