Skip to content

Instantly share code, notes, and snippets.

@psychoss
Last active January 15, 2016 12:31
Show Gist options
  • Select an option

  • Save psychoss/365735897c03365501b2 to your computer and use it in GitHub Desktop.

Select an option

Save psychoss/365735897c03365501b2 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"hash/crc32"
)
var crcTable = crc32.MakeTable(crc32.Castagnoli)
// crc implements the checksum specified in section 3 of
// https://github.com/google/snappy/blob/master/framing_format.txt
func crc(b []byte) uint32 {
c := crc32.Update(0, crcTable, b)
return uint32(c>>15|c<<17) + 0xa282ead8
}
// func update(crc uint32, tab *Table, p []byte) uint32 {
// crc = ^crc
// for _, v := range p {
// crc = tab[byte(crc)^v] ^ (crc >> 8)
// }
// return ^crc
// }
func main() {
fmt.Println(crc([]byte("123")))
//31919054
}
package main
import "fmt";
const (
tagLiteral = 0x00
)
func emitLiteral(dst, lit []byte) int {
i, n := 0, uint(len(lit)-1)
switch {
case n < 60:
dst[0] = uint8(n)<<2 | tagLiteral
i = 1
case n < 1<<8:
dst[0] = 60<<2 | tagLiteral
dst[1] = uint8(n)
i = 2
case n < 1<<16:
dst[0] = 61<<2 | tagLiteral
dst[1] = uint8(n)
dst[2] = uint8(n >> 8)
i = 3
case n < 1<<24:
dst[0] = 62<<2 | tagLiteral
dst[1] = uint8(n)
dst[2] = uint8(n >> 8)
dst[3] = uint8(n >> 16)
i = 4
case int64(n) < 1<<32:
dst[0] = 63<<2 | tagLiteral
dst[1] = uint8(n)
dst[2] = uint8(n >> 8)
dst[3] = uint8(n >> 16)
dst[4] = uint8(n >> 24)
i = 5
default:
panic("snappy: source buffer is too long")
}
if copy(dst[i:], lit) != len(lit) {
panic("snappy: destination buffer is too short")
}
return i + len(lit)
}
func main() {
dst:=make([]byte, 12);
lit:=[]byte("123");
emitLiteral(dst,lit)
fmt.Println(dst,lit)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment