Created
December 18, 2018 17:05
-
-
Save juanhuttemann/38cdb70e973ef4d415f5c4e067bfda4a to your computer and use it in GitHub Desktop.
Compresor/Descompresor L4
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "bufio" | |
| "io" | |
| "os" | |
| "github.com/pierrec/lz4" | |
| ) | |
| // Compress a file, then decompress it again! | |
| func main() { | |
| compress("./archivo.sql", "./sql-comprimido") | |
| decompress("./sql-comprimido", "./sql-descomprimido.sql") | |
| } | |
| func compress(inputFile, outputFile string) { | |
| // open input file | |
| fin, err := os.Open(inputFile) | |
| if err != nil { | |
| panic(err) | |
| } | |
| defer func() { | |
| if err := fin.Close(); err != nil { | |
| panic(err) | |
| } | |
| }() | |
| // make a read buffer | |
| r := bufio.NewReader(fin) | |
| // open output file | |
| fout, err := os.Create(outputFile) | |
| if err != nil { | |
| panic(err) | |
| } | |
| defer func() { | |
| if err := fout.Close(); err != nil { | |
| panic(err) | |
| } | |
| }() | |
| // make an lz4 write buffer | |
| w := lz4.NewWriter(fout) | |
| // make a buffer to keep chunks that are read | |
| buf := make([]byte, 1024) | |
| for { | |
| // read a chunk | |
| n, err := r.Read(buf) | |
| if err != nil && err != io.EOF { | |
| panic(err) | |
| } | |
| if n == 0 { | |
| break | |
| } | |
| // write a chunk | |
| if _, err := w.Write(buf[:n]); err != nil { | |
| panic(err) | |
| } | |
| } | |
| if err = w.Flush(); err != nil { | |
| panic(err) | |
| } | |
| } | |
| func decompress(inputFile, outputFile string) { | |
| // open input file | |
| fin, err := os.Open(inputFile) | |
| if err != nil { | |
| panic(err) | |
| } | |
| defer func() { | |
| if err := fin.Close(); err != nil { | |
| panic(err) | |
| } | |
| }() | |
| // make an lz4 read buffer | |
| r := lz4.NewReader(fin) | |
| // open output file | |
| fout, err := os.Create(outputFile) | |
| if err != nil { | |
| panic(err) | |
| } | |
| defer func() { | |
| if err := fout.Close(); err != nil { | |
| panic(err) | |
| } | |
| }() | |
| // make a write buffer | |
| w := bufio.NewWriter(fout) | |
| // make a buffer to keep chunks that are read | |
| buf := make([]byte, 1024) | |
| for { | |
| // read a chunk | |
| n, err := r.Read(buf) | |
| if err != nil && err != io.EOF { | |
| panic(err) | |
| } | |
| if n == 0 { | |
| break | |
| } | |
| // write a chunk | |
| if _, err := w.Write(buf[:n]); err != nil { | |
| panic(err) | |
| } | |
| } | |
| if err = w.Flush(); err != nil { | |
| panic(err) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment