aboutsummaryrefslogtreecommitdiff
path: root/main.go
blob: 98ed5b9b5b74ad295c2e9082d535607432ea0faa (plain)
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
package main

import (
	"bufio"
	"bytes"
	"encoding/binary"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"os"
	"slices"
	"unicode"

	"github.com/ulikunitz/xz/lzma"
)

type stateFn func([]byte, bool) (int, []byte, error, stateFn)

func outsideString(pred func(byte) stateFn) stateFn {
	return func(data []byte, atEOF bool) (int, []byte, error, stateFn) {
		i := 0
		for ; i < len(data); i++ {
			b := data[i]
			if unicode.IsSpace(rune(b)) {
				continue
			}
			if f := pred(b); f != nil {
				return i + 1, data[i:i+1], nil, f
			}
			if b == '\000' && atEOF {
				return i, nil, bufio.ErrFinalToken, nil
			}
			return i, nil, fmt.Errorf("unexpected %q", b), nil
		}
		return i, nil, nil, outsideString(pred)
	}
}

func scanEntsTo(w io.Writer, r io.Reader) error {
	w.Write([]byte{'['})
	defer w.Write([]byte{'\n', ']', '\n'})
	// should technically be 1021 as valve's implementation stores "" & \0
	const VMAXLEN = 1024

	var candidate map[string]string
	var key *string

	var topLevel, inEnt, inString stateFn

	topLevel = outsideString(func(c byte) stateFn {
		if c == '{' {
			candidate = map[string]string{}
			return inEnt
		}
		return nil
	})
	
	nReported := 0
	inEnt = outsideString(func(c byte) stateFn {
		switch c {
		case '"':
			return inString
		case '}':
			if nReported > 0 {
				w.Write([]byte{','})
			}
			w.Write([]byte{'\n', '\t'})
			b, err := json.MarshalIndent(candidate, "\t", "\t")
			if err != nil {
				die(err)
			}
			_, err = w.Write(b)
			if err != nil {
				die(err)
			}
			nReported++
			candidate = nil
			return topLevel
		}
		return nil
	})

	// "runs" of unescaped characters. we may reread, so pains are taken to
	// avoid eager copying. in the overwhelmingly common case of no escapes,
	// `runBuf` is entirely bypassed.
	runBuf := make([][]byte, VMAXLEN/2)
	nt := [2]byte{'\n', '\t'}
	inString = func(data []byte, atEOF bool) (int, []byte, error, stateFn) {
		var i, iRun, runStart int
		inEscape := false
		for ; i < len(data); i++ {
			if b := data[i]; !inEscape {
				switch b {
				default:
					continue
				case '"':
					var str string
					if iRun == 0 {
						str = string(data[:i])
					} else {
						runBuf[iRun] = data[runStart:i]
						str = string(slices.Concat(runBuf[:iRun+1]...))
					}

					if key == nil {
						key = &str
					} else {
						candidate[*key] = str
						key = nil
					}
					return i + 1, data[:i], nil, inEnt
				case '\\':
					runBuf[iRun] = data[runStart:i]
					iRun++
					inEscape = true
				}
			} else {
				inEscape = false
				runStart = i
				switch b {
				case 'n':
					runBuf[iRun] = nt[:1]
				case 't':
					runBuf[iRun] = nt[1:]
				case '\\', '"':
					continue
				default:
					return i, nil, fmt.Errorf("invalid escape %q", b), nil
				}
				iRun++
				runStart++
			}
		}

		if len(data) >= VMAXLEN {
			return 0, nil, errors.New("string too long"), nil
		}
		if atEOF {
			return 0, nil, errors.New("truncated entity lump"), nil
		}
		return 0, nil, nil, inString
	}

	scanner := bufio.NewScanner(r)
	curState := topLevel
	scanner.Split(func(data []byte, eof bool) (adv int, tok []byte, err error) {
		adv, tok, err, curState = curState(data, eof)
		return
	})
	scanner.Buffer(make([]byte, VMAXLEN), VMAXLEN)
	for scanner.Scan() {
	}

	if err := scanner.Err()
	   err != nil && !errors.Is(err, bufio.ErrFinalToken) {
		return err
	}
	if candidate != nil || key != nil {
		return errors.New("truncated entity lump")
	}
	return nil
}

func die(err error) {
	fmt.Fprintln(os.Stderr, err)
	os.Exit(1)
}

func readerForBSP(f io.ReaderAt) (r io.Reader, err error) {
	var fileofs, filelen int64

	{
		var order binary.ByteOrder

		{
			sigbuf := [4]byte{}
			if _, err := f.ReadAt(sigbuf[:], 0); err != nil {
				return nil, fmt.Errorf("header: %w", err)
			}

			switch 0 {
			case bytes.Compare(sigbuf[:], []byte("VBSP")):
				order = binary.LittleEndian
			case bytes.Compare(sigbuf[:], []byte("PSBV")):
				order = binary.BigEndian
			default:
				return nil, errors.New("header: no VBSP signature")
			}
		}

		lumpbuf := [16]byte{}
		if _, err := f.ReadAt(lumpbuf[:], 8); err != nil {
			return nil, fmt.Errorf("header: %w", err)
		}
		// double conversion so reads fail if these go negative
		fileofs = int64(int32(order.Uint32(lumpbuf[:4])))
		filelen = int64(int32(order.Uint32(lumpbuf[4:8])))
	}

	lzmabuf := [17]byte{}
	if _, err := f.ReadAt(lzmabuf[:], fileofs); err != nil {
		return nil, fmt.Errorf("lump contents: %w", err)
	}

	// always little endian apparently.
	// https://developer.valvesoftware.com/wiki/BSP_(Source)#Lump_compression
	if bytes.Compare(lzmabuf[0:4], []byte("LZMA")) == 0 {
		actualSize := binary.LittleEndian.Uint32(lzmabuf[4:8])
		lzmaSize := int64(binary.LittleEndian.Uint32(lzmabuf[8:12]))
		if lzmaSize+17 != filelen {
			return nil, errors.New("filelen and lzmaSize disagree")
		}
		fakeHeader := [13]byte{}
		copy(fakeHeader[0:5], lzmabuf[12:])
		binary.LittleEndian.PutUint64(fakeHeader[5:], uint64(actualSize))
		lzmaReader := io.MultiReader(
			bytes.NewReader(fakeHeader[:]),
			io.NewSectionReader(f, fileofs+17, lzmaSize),
		)
		r, err := lzma.NewReader(lzmaReader)
		if err != nil {
			return nil, fmt.Errorf("compressed lump: %w", err)
		}
		return r, nil
	}
	return io.NewSectionReader(f, fileofs, filelen), nil
}

func main() {
	f, err := os.Open(os.Args[1])
	if err != nil {
		die(err)
	}

	r, err := readerForBSP(f)
	if err != nil {
		die(err)
	}
	
	bw := bufio.NewWriter(os.Stdout)
	defer bw.Flush()
	err = scanEntsTo(bw, r)
	
	if err != nil {
		die(err)
	}
}