Refactored compress method into something more organised

This commit is contained in:
obscuren 2014-11-03 14:59:50 +01:00
parent 76c9c8d653
commit 92c7aca817
1 changed files with 30 additions and 30 deletions

View File

@ -45,39 +45,39 @@ func Decompress(dat []byte) ([]byte, error) {
return buf.Bytes(), nil return buf.Bytes(), nil
} }
func Compress(dat []byte) []byte { func compressBlock(dat []byte) (ret []byte, n int) {
buf := new(bytes.Buffer) switch {
case dat[0] == token:
for i := 0; i < len(dat); i++ { return []byte{token, tokenToken}, 1
if dat[i] == token { case len(dat) > 1 && dat[0] == 0x0 && dat[1] == 0x0:
buf.Write([]byte{token, tokenToken})
} else if i+1 < len(dat) {
if dat[i] == 0x0 && dat[i+1] == 0x0 {
j := 0 j := 0
for j <= 254 && i+j < len(dat) { for j <= 254 && j < len(dat) {
if dat[i+j] != 0 { if dat[j] != 0 {
break break
} }
j++ j++
} }
buf.Write([]byte{token, byte(j + 2)}) return []byte{token, byte(j + 2)}, j
i += (j - 1) case len(dat) >= 32:
} else if len(dat[i:]) >= 32 { if dat[0] == empty[0] && bytes.Compare(dat[:32], empty) == 0 {
if dat[i] == empty[0] && bytes.Compare(dat[i:i+32], empty) == 0 { return []byte{token, emptyShaToken}, 32
buf.Write([]byte{token, emptyShaToken}) } else if dat[0] == emptyList[0] && bytes.Compare(dat[:32], emptyList) == 0 {
i += 31 return []byte{token, emptyListShaToken}, 32
} else if dat[i] == emptyList[0] && bytes.Compare(dat[i:i+32], emptyList) == 0 {
buf.Write([]byte{token, emptyListShaToken})
i += 31
} else {
buf.WriteByte(dat[i])
} }
} else { fallthrough
buf.WriteByte(dat[i]) default:
} return dat[:1], 1
} else {
buf.WriteByte(dat[i])
} }
}
func Compress(dat []byte) []byte {
buf := new(bytes.Buffer)
i := 0
for i < len(dat) {
b, n := compressBlock(dat[i:])
buf.Write(b)
i += n
} }
return buf.Bytes() return buf.Bytes()