]> Sergey Matveev's repositories - glocate.git/blob - writer.go
Unify copyright comment format
[glocate.git] / writer.go
1 // glocate -- ZFS-diff-friendly locate-like utility
2 // Copyright (C) 2022-2024 Sergey Matveev <stargrave@stargrave.org>
3 //
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, version 3 of the License.
7 //
8 // This program is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 // GNU General Public License for more details.
12 //
13 // You should have received a copy of the GNU General Public License
14 // along with this program.  If not, see <http://www.gnu.org/licenses/>.
15
16 package main
17
18 import (
19         "bufio"
20         "encoding/binary"
21         "io"
22         "log"
23
24         "github.com/klauspost/compress/zstd"
25 )
26
27 func mustWrite(w io.Writer, buf []byte) {
28         if _, err := w.Write(buf); err != nil {
29                 log.Fatalln(err)
30         }
31 }
32
33 func writer(dst io.Writer, sink chan Ent) {
34         comp, err := zstd.NewWriter(dst)
35         if err != nil {
36                 log.Fatalln(err)
37         }
38         bw := bufio.NewWriterSize(comp, 1<<17)
39         num := make([]byte, 8)
40         var name string
41         for ent := range sink {
42                 name = ent.name[len(ent.name)-1]
43                 if len(ent.name) >= 1<<16 {
44                         panic("too long")
45                 }
46                 binary.BigEndian.PutUint16(num[:2], uint16(len(name)))
47                 mustWrite(bw, num[:2])
48                 mustWrite(bw, []byte(name))
49                 if len(ent.name) >= 1<<8 {
50                         panic("too deep")
51                 }
52                 mustWrite(bw, []byte{byte(len(ent.name) - 1)})
53                 binary.BigEndian.PutUint64(num, uint64(ent.mtime))
54                 mustWrite(bw, num)
55                 binary.BigEndian.PutUint64(num, uint64(ent.size))
56                 mustWrite(bw, num)
57         }
58         if err = bw.Flush(); err != nil {
59                 log.Fatalln(err)
60         }
61         if err = comp.Close(); err != nil {
62                 log.Fatalln(err)
63         }
64 }