Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / networklocation / src / test / java / com / vayunmathur / networklocation / TestFixtures.kt

TestFixtures.kt333 lines · 11.0 KiBRaw
1package com.vayunmathur.networklocation
2
3import java.io.ByteArrayOutputStream
4import java.io.File
5
6/** Bit writer matching the Rust WPSDB2 fixture writer (LSB-first within each byte). */
7internal class BitWriter {
8 private val backing = mutableListOf<Byte>()
9 var bits: Long = 0
10 private set
11
12 fun push(v: Long, nbits: Int) {
13 for (k in 0 until nbits) {
14 while (backing.size <= (bits / 8).toInt()) backing.add(0)
15 if (((v ushr k) and 1L) == 1L) {
16 val idx = (bits / 8).toInt()
17 backing[idx] = (backing[idx].toInt() or (1 shl (bits % 8).toInt())).toByte()
18 }
19 bits++
20 }
21 }
22
23 fun pushBit(set: Boolean) = push(if (set) 1L else 0L, 1)
24
25 fun bytes(): ByteArray = ByteArray(backing.size) { backing[it] }
26}
27
28internal data class WpsRec(
29 val keyHi: Long,
30 val keyLo: Long,
31 val latE8: Long,
32 val lonE8: Long,
33 val acc: Long,
34 val altMeters: Long?,
35)
36
37private fun wpsKeyOf(r: WpsRec) = java.math.BigInteger.valueOf(r.keyHi).shiftLeft(64)
38 .add(
39 java.math.BigInteger.valueOf(r.keyLo)
40 .and(java.math.BigInteger.ONE.shiftLeft(64).subtract(java.math.BigInteger.ONE)),
41 )
42
43private fun wpsChooseL(universeBits: Int, n: Int): Int {
44 if (n == 0) return minOf(universeBits, 64)
45 var cand = 0
46 val u = java.math.BigInteger.ONE.shiftLeft(universeBits)
47 while (cand < 64 && u.shiftRight(cand + 1) >= java.math.BigInteger.valueOf(n.toLong())) cand++
48 return cand
49}
50
51private fun wpsHigh(sorted: List<WpsRec>, l: Int, universeBits: Int): BitWriter {
52 val high = BitWriter()
53 var prevBucket = java.math.BigInteger.ZERO
54 for (r in sorted) {
55 val bucket = wpsKeyOf(r).shiftRight(l)
56 var b = prevBucket
57 while (b < bucket) {
58 high.pushBit(false)
59 b = b.add(java.math.BigInteger.ONE)
60 }
61 high.pushBit(true)
62 prevBucket = bucket
63 }
64 val buckets = java.math.BigInteger.ONE.shiftLeft(universeBits - l)
65 var b = prevBucket
66 while (b < buckets) {
67 high.pushBit(false)
68 b = b.add(java.math.BigInteger.ONE)
69 }
70 return high
71}
72
73private fun wpsZeros(highBytes: ByteArray, highLenBits: Long, sampleLog2: Int): ByteArray {
74 val zeros = mutableListOf(0L)
75 var count = 0L
76 for (p in 0 until highLenBits) {
77 val byte = highBytes[(p / 8).toInt()].toInt()
78 if (((byte ushr (p % 8).toInt()) and 1) == 0) count++
79 if ((p + 1) and ((1L shl sampleLog2) - 1) == 0L) zeros.add(count)
80 }
81 val out = ByteArrayOutputStream()
82 for (z in zeros) for (i in 0 until 8) out.write((z ushr (8 * i)).toInt() and 0xFF)
83 return out.toByteArray()
84}
85
86private fun wpsLow(sorted: List<WpsRec>, l: Int): ByteArray {
87 val low = BitWriter()
88 if (l > 0) {
89 val mask = java.math.BigInteger.ONE.shiftLeft(l).subtract(java.math.BigInteger.ONE)
90 for (r in sorted) low.push(wpsKeyOf(r).and(mask).toLong(), l)
91 }
92 return low.bytes()
93}
94
95private fun wpsPayload(sorted: List<WpsRec>): ByteArray {
96 val payload = BitWriter()
97 for (r in sorted) {
98 payload.push(r.latE8 + 9_000_000_000L, 35)
99 payload.push(r.lonE8 + 18_000_000_000L, 36)
100 payload.push(r.acc, 16)
101 payload.push((r.altMeters ?: -32768L) + 32768L, 16)
102 }
103 return payload.bytes()
104}
105
106private fun ByteArrayOutputStream.u64le(v: Long) {
107 for (i in 0 until 8) write((v ushr (8 * i)).toInt() and 0xFF)
108}
109
110/** Writes a valid WPSDB2 store (payload kind 2) holding [records], mirroring wpsdb_part2.rs. */
111internal fun writeWpsStore(file: File, universeBits: Int, records: List<WpsRec>) {
112 val sorted = records.sortedWith(compareBy({ it.keyHi.toULong() }, { it.keyLo.toULong() }))
113 .distinctBy { it.keyHi to it.keyLo }
114 val sampleLog2 = 6
115 val l = wpsChooseL(universeBits, sorted.size)
116 val high = wpsHigh(sorted, l, universeBits)
117 val highBytes = high.bytes()
118 val out = ByteArrayOutputStream()
119 out.write("WPSDB2\u0000\u0000".toByteArray(Charsets.US_ASCII))
120 out.write(1)
121 out.write(universeBits)
122 out.write(2) // payload kind 2
123 out.write(l)
124 out.write(sampleLog2)
125 out.write(byteArrayOf(0, 0, 0))
126 out.u64le(sorted.size.toLong())
127 out.u64le(high.bits)
128 out.u64le(highBytes.size.toLong())
129 out.write(highBytes)
130 val zerosBytes = wpsZeros(highBytes, high.bits, sampleLog2)
131 out.u64le(zerosBytes.size.toLong())
132 out.write(zerosBytes)
133 val lowBytes = wpsLow(sorted, l)
134 out.u64le(lowBytes.size.toLong())
135 out.write(lowBytes)
136 val payloadBytes = wpsPayload(sorted)
137 out.u64le(payloadBytes.size.toLong())
138 out.write(payloadBytes)
139 file.parentFile?.mkdirs()
140 file.writeBytes(out.toByteArray())
141}
142
143/** Minimal zstd frame holding [data] in raw (uncompressed) blocks, which ruzstd decodes. */
144internal fun zstdRaw(data: ByteArray): ByteArray {
145 val out = ByteArrayOutputStream()
146 out.write(byteArrayOf(0x28, 0xB5.toByte(), 0x2F, 0xFD.toByte()))
147 out.write(0xA0) // single-segment, 4-byte frame content size
148 for (i in 0 until 4) out.write((data.size ushr (8 * i)) and 0xFF)
149 if (data.isEmpty()) {
150 out.write(byteArrayOf(1, 0, 0)) // last, raw, size 0
151 } else {
152 var off = 0
153 while (off < data.size) {
154 val chunk = minOf(data.size - off, 100_000)
155 val last = if (off + chunk == data.size) 1 else 0
156 val header = (chunk shl 3) or last
157 for (i in 0 until 3) out.write((header ushr (8 * i)) and 0xFF)
158 out.write(data, off, chunk)
159 off += chunk
160 }
161 }
162 return out.toByteArray()
163}
164
165private fun be32(out: ByteArrayOutputStream, v: Int) {
166 for (i in 3 downTo 0) out.write((v ushr (8 * i)) and 0xFF)
167}
168
169private fun be64(out: ByteArrayOutputStream, v: Long) {
170 for (i in 7 downTo 0) out.write(((v ushr (8 * i)) and 0xFF).toInt())
171}
172
173private fun zigzag(v: Int): Long = (((v shl 1) xor (v shr 31)).toLong()) and 0xFFFFFFFFL
174
175private fun varint(out: ByteArrayOutputStream, value: Long) {
176 var v = value
177 while (true) {
178 val b = (v and 0x7F).toInt()
179 v = v ushr 7
180 if (v == 0L) {
181 out.write(b)
182 return
183 }
184 out.write(b or 0x80)
185 }
186}
187
188private fun geocoderColumn(values: IntArray, delta: Boolean): ByteArray {
189 val raw = ByteArrayOutputStream()
190 var prev = 0
191 for ((i, v) in values.withIndex()) {
192 val dv = if (delta && i > 0) v - prev else v
193 varint(raw, zigzag(dv))
194 prev = v
195 }
196 val comp = zstdRaw(raw.toByteArray())
197 val out = ByteArrayOutputStream()
198 be32(out, values.size)
199 be32(out, 1)
200 be32(out, raw.size())
201 be32(out, comp.size)
202 out.write(comp)
203 return out.toByteArray()
204}
205
206private fun geocoderDict(strings: List<String>): ByteArray {
207 val per = maxOf(strings.size, 1)
208 val blocks = if (strings.isEmpty()) 0 else (strings.size + per - 1) / per
209 val out = ByteArrayOutputStream()
210 be32(out, strings.size)
211 be32(out, per)
212 be32(out, blocks)
213 // first-string table: first string of each block, cumulative ends
214 val firsts = ByteArrayOutputStream()
215 var end = 0
216 for (blk in 0 until blocks) {
217 val s = strings[blk * per].toByteArray(Charsets.UTF_8)
218 firsts.write(s)
219 end += s.size
220 be32(out, end)
221 }
222 out.write(firsts.toByteArray())
223 // blocks: raw encoding [be32 len][utf8] per string, zstd-wrapped
224 val blockData = ByteArrayOutputStream()
225 var compEnd = 0
226 val ends = mutableListOf<Int>()
227 for (blk in 0 until blocks) {
228 val rawBlk = ByteArrayOutputStream()
229 val from = blk * per
230 val to = minOf(from + per, strings.size)
231 for (i in from until to) {
232 val s = strings[i].toByteArray(Charsets.UTF_8)
233 be32(rawBlk, s.size)
234 rawBlk.write(s)
235 }
236 val comp = zstdRaw(rawBlk.toByteArray())
237 blockData.write(comp)
238 compEnd += comp.size
239 ends.add(compEnd)
240 }
241 for (e in ends) be32(out, e)
242 out.write(blockData.toByteArray())
243 return out.toByteArray()
244}
245
246internal data class GeoRec(
247 val latE5: Int,
248 val lonE5: Int,
249 val nameId: Int,
250 val houseId: Int,
251 val streetId: Int,
252 val cityId: Int,
253 val stateId: Int,
254 val countryId: Int,
255 val postcodeId: Int,
256 val kind: Int,
257)
258
259/** Dictionary contents shared by [writeGeocoderDb] records, in dict order. */
260internal val GEO_DICTS: List<List<String>> = listOf(
261 listOf("", "Test Cafe"), // name
262 listOf("123", "124"), // house
263 listOf("Main St"), // street
264 listOf("Springfield"), // city
265 listOf("CA"), // state
266 listOf("US"), // country
267 listOf("12345"), // postcode
268)
269
270internal val GEO_RECORDS: List<GeoRec> = listOf(
271 GeoRec(3_742_150, -12_208_400, 1, 0, 0, 0, 0, 0, 0, 1),
272 GeoRec(3_742_250, -12_208_300, -1, 1, 0, 0, 0, 0, 0, 1),
273)
274
275/** Writes a minimal but valid v5 geocoder.db holding [GEO_RECORDS]. */
276internal fun writeGeocoderDb(file: File) {
277 val cellOf = { r: GeoRec ->
278 val row = (r.latE5.toLong() + 9_000_000L) / 5_000L
279 val col = (r.lonE5.toLong() + 18_000_000L) / 5_000L
280 row * 7_200L + col
281 }
282 val ordered = GEO_RECORDS.sortedBy(cellOf)
283 val grid = mutableListOf<Pair<Long, Int>>()
284 ordered.forEachIndexed { idx, r ->
285 val c = cellOf(r)
286 if (grid.none { it.first == c }) grid.add(c to idx)
287 }
288 grid.sortBy { it.first }
289
290 val dictSections = GEO_DICTS.map { geocoderDict(it) }
291 val colValues: List<IntArray> = listOf(
292 ordered.map { it.latE5 }.toIntArray(),
293 ordered.map { it.lonE5 }.toIntArray(),
294 ordered.map { it.nameId }.toIntArray(),
295 ordered.map { it.houseId }.toIntArray(),
296 ordered.map { it.streetId }.toIntArray(),
297 ordered.map { it.cityId }.toIntArray(),
298 ordered.map { it.stateId }.toIntArray(),
299 ordered.map { it.countryId }.toIntArray(),
300 ordered.map { it.postcodeId }.toIntArray(),
301 ordered.map { it.kind }.toIntArray(),
302 )
303 val deltaCols = booleanArrayOf(true, true, false, false, false, false, false, false, false, false)
304 val colSections = colValues.mapIndexed { i, v -> geocoderColumn(v, deltaCols[i]) }
305
306 val gridBody = ByteArrayOutputStream()
307 be32(gridBody, grid.size)
308 for ((cell, start) in grid) {
309 be64(gridBody, cell)
310 be32(gridBody, start)
311 }
312
313 val fwdRecs = ordered.indices.filter { ordered[it].streetId >= 0 }
314 val fwd = geocoderColumn(fwdRecs.toIntArray(), delta = true)
315 val nmPairs = ordered.indices
316 .filter { ordered[it].nameId >= 0 }
317 .map { ordered[it].nameId to it }
318 .sortedBy { it.first }
319 val nmName = geocoderColumn(nmPairs.map { it.first }.toIntArray(), delta = true)
320 val nmRec = geocoderColumn(nmPairs.map { it.second }.toIntArray(), delta = false)
321
322 val sections = dictSections + colSections + listOf(gridBody.toByteArray(), fwd, nmName, nmRec)
323 val out = ByteArrayOutputStream()
324 be32(out, 0x4D414745)
325 be32(out, 5)
326 be32(out, ordered.size)
327 for (s in sections) {
328 be32(out, s.size)
329 out.write(s)
330 }
331 file.parentFile?.mkdirs()
332 file.writeBytes(out.toByteArray())
333}