-
Notifications
You must be signed in to change notification settings - Fork 0
/
write.go
104 lines (91 loc) · 2.31 KB
/
write.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// seehuhn.de/go/pdf - a library for reading and writing PDF files
// Copyright (C) 2023 Jochen Voss <voss@seehuhn.de>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package numtree
import (
"errors"
"sort"
"golang.org/x/exp/maps"
"seehuhn.de/go/pdf"
)
func Write(w pdf.Putter, tree Tree) (pdf.Reference, error) {
sw := NewSequentialWriter(w)
pos, err := tree.First()
if err != nil {
// TODO(voss): this fails for empty trees
return 0, err
}
for {
val, err := tree.Get(pos)
if err != nil {
return 0, err
}
err = sw.Append(pos, val)
if err != nil {
return 0, err
}
pos, err = tree.Next(pos)
if err == ErrKeyNotFound {
break
} else if err != nil {
return 0, err
}
}
err = sw.Close()
if err != nil {
return 0, err
}
return sw.Reference(), nil
}
// TODO(voss): write an actual tree
type SequentialWriter struct {
w pdf.Putter
ref pdf.Reference
data map[pdf.Integer]pdf.Object
}
func NewSequentialWriter(w pdf.Putter) *SequentialWriter {
sw := &SequentialWriter{
w: w,
ref: w.Alloc(),
data: make(map[pdf.Integer]pdf.Object),
}
return sw
}
func (sw *SequentialWriter) Append(key pdf.Integer, val pdf.Object) error {
sw.data[key] = val
return nil
}
func (sw *SequentialWriter) Close() error {
if len(sw.data) == 0 {
return errors.New("numtree: empty tree")
}
keys := maps.Keys(sw.data)
sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] })
min := keys[0]
max := keys[len(keys)-1]
var Nums pdf.Array
for _, key := range keys {
Nums = append(Nums, key, sw.data[key])
}
dict := pdf.Dict{
"Nums": Nums,
"Limits": pdf.Array{min, max},
}
err := sw.w.Put(sw.ref, dict)
return err
}
func (sw *SequentialWriter) Reference() pdf.Reference {
return sw.ref
}