Debian Codegraph @

src/uk/me/parabola/imgfmt/app/net/NumberPreparer.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2008 Steve Ratcliffe
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 version 3 or
6 * version 2 as published by the Free Software Foundation.
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 package uk.me.parabola.imgfmt.app.net;
14
15 import java.io.ByteArrayOutputStream;
16 import java.util.ArrayList;
17 import java.util.List;
18
19 import uk.me.parabola.imgfmt.Utils;
20 import uk.me.parabola.imgfmt.app.BitWriter;
21 import uk.me.parabola.imgfmt.app.lbl.City;
22 import uk.me.parabola.imgfmt.app.lbl.Zip;
23 import uk.me.parabola.log.Logger;
24 import uk.me.parabola.mkgmap.general.CityInfo;
25 import uk.me.parabola.mkgmap.general.ZipCodeInfo;
26
27 import static uk.me.parabola.imgfmt.app.net.NumberStyle.*;
28
29 /**
30 * Class to prepare the bit stream of the house numbering information.
31 *
32 * There are multiple ways to encode the same numbers, the trick is to find a way that is reasonably
33 * small. We recognise a few common cases to reduce the size of the bit stream, but mostly just concentrating
34 * on clarity and correctness. Optimisations only made a few percent difference at most.
35 *
36 * @author Steve Ratcliffe
37 */
38 public class NumberPreparer {
39 private static final Logger log = Logger.getLogger(NumberPreparer.class);
40 private final List<Numbers> numbers;
41 private boolean valid;
42
43 // The minimum values of the start and end bit widths.
44 private static final int START_WIDTH_MIN = 5;
45 private static final int END_WIDTH_MIN = 2;
46
47 private BitWriter bw;
48 private boolean swappedDefaultStyle;
49 CityZipWriter zipWriter;
50 CityZipWriter cityWriter;
51
52 public NumberPreparer(List<Numbers> numbers) {
53 this.numbers = new ArrayList<>(numbers);
54 this.zipWriter = new CityZipWriter("zip", 0, 0);
55 this.cityWriter = new CityZipWriter("city", 0, 0);
56 }
57
58
59 public NumberPreparer(List<Numbers> numbers, Zip zip, City city, int numCities, int numZips) {
60 this.numbers = numbers;
61
62 zipWriter = new CityZipWriter("zip",(zip == null) ? 0: zip.getIndex(), numZips);
63 cityWriter = new CityZipWriter("city",(city == null) ? 0: city.getIndex(), numCities);
64 }
65
66 public boolean prepare(){
67 fetchBitStream();
68 if (!valid)
69 return false;
70 zipWriter.compile(numbers);
71 cityWriter.compile(numbers);
72 return true;
73 }
74 /**
75 * Make the bit stream and return it. This is only done once, if you call this several times
76 * the same bit writer is returned every time.
77 * @return A bit writer containing the computed house number stream.
78 */
79 public BitWriter fetchBitStream() {
80 if (bw != null)
81 return bw;
82 int initialValue = setup();
83
84 // Write the bitstream
85 bw = new BitWriter();
86
87 try {
88
89 // Look at the numbers and calculate some optimal values for the bit field widths etc.
90 State state = new GatheringState(initialValue);
91 process(new BitWriter(), state);
92
93 // Write the initial values.
94 writeWidths(state);
95 writeInitialValue(state);
96
97 state = new WritingState(state);
98 process(bw, state);
99
100 // If we get this far and there is something there, the stream might be valid!
101 if (bw.getLength() > 1)
102 valid = true;
103 } catch (Abandon e) {
104 log.error(e.getMessage());
105 valid = false;
106 }
107
108 return bw;
109 }
110
111 /**
112 * Do some initial calculation and sanity checking of the numbers that we are to
113 * write.
114 * @return The initial base value that all other values are derived from.
115 */
116 private int setup() {
117 // Should we use the swapped default numbering style EVEN/ODD rather than
118 // ODD/EVEN and the initialValue.
119 numbers.removeIf(Numbers::isEmpty);
120 if (numbers.isEmpty())
121 throw new Abandon("no numbers");
122
123 Numbers first = numbers.get(0);
124 if (first.getLeftNumberStyle() == EVEN && first.getRightNumberStyle() == ODD)
125 swappedDefaultStyle = true;
126
127 // Calculate the initial value we want to use
128 int initial = 0;
129 if (first.getLeftNumberStyle() != NONE)
130 initial = first.getLeftStart();
131
132 int rightStart = 0;
133 if (first.getRightNumberStyle() != NONE)
134 rightStart = first.getRightStart();
135
136 if (initial == 0)
137 initial = rightStart;
138
139 if (first.getLeftStart() > first.getLeftEnd() || first.getRightStart() > first.getRightEnd())
140 initial = Math.max(initial, rightStart);
141 else if (rightStart > 0)
142 initial = Math.min(initial, rightStart);
143 return initial;
144 }
145
146 /**
147 * Process the list of number ranges and compile them into a bit stream.
148 *
149 * This is done twice, once to calculate the sizes of the bit fields needed, and again
150 * to do the actual writing.
151 *
152 * @param bw The bit stream to write to.
153 * @param state Use to keep track of state during the construction process.
154 */
155 private void process(BitWriter bw, State state) {
156 if (swappedDefaultStyle)
157 state.swapDefaults();
158
159 int lastNode = -1;
160 for (Numbers n : numbers) {
161 if (!n.hasIndex())
162 throw new Abandon("no index set");
163 // See if we need to skip some nodes
164 if (n.getIndex() != lastNode + 1)
165 state.writeSkip(bw, n.getIndex() - lastNode - 2);
166
167 // Normal case write out the next node.
168 state.setTarget(n);
169
170 state.writeNumberingStyle(bw);
171 state.calcNumbers();
172 state.writeBitWidths(bw);
173 state.writeNumbers(bw);
174 state.restoreWriters();
175
176 lastNode = n.getIndex();
177 }
178 }
179
180 /**
181 * The initial base value is written out separately before anything else.
182 * All numbers are derived from differences from this value.
183 * @param state Holds the initial value to write.
184 */
185 private void writeInitialValue(State state) {
186 assert state.initialValue >= 0 : "initial value is not positive: " + state.initialValue;
187 int width = 32 - Integer.numberOfLeadingZeros(state.initialValue);
188 if (width > 20)
189 throw new Abandon("Initial value too large: " + state.initialValue);
190
191 if (width > 5) {
192 bw.put1(false);
193 bw.putn(width - 5, 4);
194 } else {
195 bw.put1(true);
196 width = 5;
197 }
198 bw.putn(state.initialValue, width);
199 }
200
201 /**
202 * Write out a block that describes the number of bits to use. Numbers can be
203 * either all positive or all negative, or they can be signed and each bit field
204 * also has an extra sign bit. This is like how lines are encoded. See the LinePreparer
205 * class.
206 * @param state Holds the width information.
207 */
208 private static void writeWidths(State state) {
209 state.getStartWriter().writeFormat();
210 state.getEndWriter().writeFormat();
211 }
212
213 /**
214 * Returns true if the bit stream was calculated on the basis that the initial even/odd defaults
215 * should be swapped.
216 * @return True to signify swapped default, ie bit 0x20 in the net flags should be set.
217 */
218 public boolean getSwapped() {
219 return swappedDefaultStyle;
220 }
221
222 /**
223 * During development, any case that cannot be written correctly is marked invalid so it can
224 * be skipped on output.
225 *
226 * This will probably go away when complete.
227 *
228 * @return True if the preparer believes that the output is valid.
229 */
230 public boolean isValid() {
231 fetchBitStream();
232 return valid;
233 }
234
235 /**
236 * The current state of the writing process.
237 */
238 abstract static class State {
239
240 protected final Side left = new Side(true);
241 protected final Side right = new Side(false);
242 private int initialValue;
243
244 State() {
245 left.style = ODD;
246 right.style = EVEN;
247 }
248
249 /**
250 * Set the initial value. All numbers are derived from this by adding differences.
251 */
252 public void setInitialValue(int val) {
253 initialValue = val;
254 left.base = val;
255 right.base = val;
256 }
257
258 /**
259 * Set the next number to output. Once the target is set, we then output commands to
260 * transform the current state into the target state.
261 * @param numbers The target numbers.
262 */
263 public void setTarget(Numbers numbers) {
264 left.setTargets(numbers.getLeftNumberStyle(), numbers.getLeftStart(), numbers.getLeftEnd());
265 right.setTargets(numbers.getRightNumberStyle(), numbers.getRightStart(), numbers.getRightEnd());
266 }
267
268 /**
269 * If the target numbering style is different to the current one, then write out
270 * the command to change it.
271 */
272 public void writeNumberingStyle(BitWriter bw) {
273 }
274
275 /**
276 * If we need a larger bit width for this node, then write out a command to
277 * change it. Changes are temporary and it reverts to the default after the
278 * next number output command.
279 */
280 public void writeBitWidths(BitWriter bw) {
281 }
282
283 public void writeSkip(BitWriter bw, int n) {
284 }
285
286 /**
287 * Calculate the number difference to represent the current number range.
288 */
289 public void calcNumbers() {
290 if (left.style == NONE)
291 left.base = right.base;
292
293 equalizeBases();
294
295 left.calc(right);
296 right.calc(left);
297 }
298
299 /**
300 * See if we can set the bases of both sides of the road to be equal. Doesn't seem to be
301 * that useful, but does not cost any bits, as long as doing so doesn't cause you to write
302 * a difference when you wouldn't without.
303 * @return True if the bases have been set equal. There are two cases, the left can be set equal to
304 * the right, or visa versa. The flags on the left/right objects will say which.
305 */
306 private boolean equalizeBases() {
307 left.equalized = right.equalized = false;
308
309 // Don't if runs are in different directions
310 if (left.direction != right.direction) {
311 return false;
312 }
313
314 int diff = left.targetStart - left.base;
315
316 // Do not lose the benefit of a 0 start.
317 if (left.tryStart(left.base))
318 diff = 0;
319
320 if (right.tryStart(left.base + diff)) {
321 left.equalized = true;
322 right.base = left.base;
323 left.startDiff = right.startDiff = diff;
324 return true;
325 }
326
327 diff = right.targetStart - right.base;
328 if (left.tryStart(right.base + diff)) {
329 right.equalized = true;
330 left.base = right.base;
331 left.startDiff = right.startDiff = diff;
332 return true;
333 }
334
335 return false;
336 }
337
338 /**
339 * Write the bit stream to the given bit writer.
340 *
341 * When this is called, all the calculations as to what is to be done have been made and
342 * it is just a case of translating those into the correct format.
343 *
344 * @param bw Bit writer to use. In the gathering phase this must be a throw away one.
345 */
346 public void writeNumbers(BitWriter bw) {
347 boolean doSingleSide = left.style == NONE || right.style == NONE;
348
349 // Output the command that a number follows.
350 bw.put1(true);
351
352 boolean equalized = false;
353 if (!doSingleSide) {
354 equalized = left.equalized || right.equalized;
355 bw.put1(equalized);
356 if (equalized)
357 bw.put1(left.equalized);
358 }
359
360 if (!doSingleSide) {
361 bw.put1(!right.needOverride(left));
362 }
363
364 Side firstSide = left;
365 if (doSingleSide && left.style == NONE)
366 firstSide = right;
367
368 boolean doStart = firstSide.startDiff != 0;
369 boolean doEnd = firstSide.endDiff != 0;
370 bw.put1(!doStart);
371 bw.put1(!doEnd);
372
373 if (doStart)
374 writeStart(firstSide.startDiff);
375 if (doEnd)
376 writeEnd(firstSide.endDiff);
377
378 firstSide.finish();
379
380 if (doSingleSide) {
381 left.base = right.base = firstSide.base;
382 left.lastEndDiff = right.lastEndDiff = firstSide.lastEndDiff;
383 return;
384 }
385
386 doStart = right.startDiff != 0;
387 doEnd = right.endDiff != 0;
388
389 if (!equalized)
390 bw.put1(!doStart);
391 if (right.needOverride(left))
392 bw.put1(!doEnd);
393
394 if (doStart && !equalized)
395 writeStart(right.startDiff);
396 if (doEnd)
397 writeEnd(right.endDiff);
398
399 right.finish();
400 }
401
402 protected void restoreWriters() {
403 }
404
405 /** Write a start difference */
406 public abstract void writeStart(int diff);
407 /** Write an end difference */
408 public abstract void writeEnd(int diff);
409
410 public abstract VarBitWriter getStartWriter();
411 public abstract VarBitWriter getEndWriter();
412
413 /**
414 * By default the left side of the road is odd numbered and the right even.
415 * Calling this swaps that around. If NONE or BOTH is needed then an explicit set of
416 * the numbering styles must be made.
417 */
418 public void swapDefaults() {
419 left.style = EVEN;
420 right.style = ODD;
421 }
422 }
423
424 /**
425 * Represents one side of the road.
426 */
427 static class Side {
428 private final boolean left;
429
430 private NumberStyle style;
431 private int base;
432
433 // The calculated end number for the node. Might be different to the actual number
434 // that are wanted that are in targetEnd.
435 private int end;
436
437 // These are the target start and end numbers for the node. The real numbers are different as there
438 // is an adjustment applied.
439 private NumberStyle targetStyle;
440 private int targetStart;
441 private int targetEnd;
442
443 // Everything is represented as a difference from a previous value.
444 private int startDiff;
445 private int endDiff;
446 private int lastEndDiff;
447
448 // This is +1 if the numbers are ascending, and -1 if descending.
449 private int direction;
450
451 // Bases equalised to this side.
452 private boolean equalized;
453
454 Side(boolean left) {
455 this.left = left;
456 }
457
458 /**
459 * Set the wanted values for start and end for this side of the road.
460 */
461 public void setTargets(NumberStyle style, int start, int end) {
462 this.targetStyle = style;
463 this.targetStart = start;
464 this.targetEnd = end;
465
466 // In reality should use the calculated start and end values, not the targets. Real start and end
467 // values are not ever the same (in this implementation) so that is why the case where start==end
468 // is given the value +1.
469 if (targetStart < targetEnd)
470 direction = 1;
471 else if (targetEnd < targetStart)
472 direction = -1;
473 else
474 direction = 1;
475 }
476
477 /**
478 * Try a start value to see if it will work. Obviously a value equal to the target will work
479 * but so will a value that equals it after rounding for odd/even.
480 * @param value The value to test.
481 * @return True if this value would result in the targetStart.
482 */
483 private boolean tryStart(int value) {
484 return value == targetStart || style.round(value, direction) == targetStart;
485 }
486
487 /**
488 * For the right hand side, read and end value, or use the last end value as default.
489 *
490 * Otherwise, the same end diff is used for the right side as the left.
491 * @param left Reference to the left hand side.
492 */
493 public boolean needOverride(Side left) {
494 return endDiff != 0 || left.endDiff == 0;
495 }
496
497 /**
498 * There is more than one way to represent the same range of numbers. The idea is to pick one of
499 * the shorter ways. We don't make any effort to find the shortest, but just pick a reasonable
500 * strategy for some common cases, and making use of defaults where we can.
501 *
502 * @param other The details of the other side of the road.
503 *
504 */
505 private void calc(Side other) {
506 if (style == NONE)
507 return;
508
509 boolean anyEqualized = this.equalized || other.equalized;
510
511 if (!anyEqualized)
512 startDiff = tryStart(base)? 0: targetStart - base;
513
514 endDiff = targetEnd - (base+startDiff) + direction;
515
516 // Special for start == end, we can often do without an end diff.
517 if (targetStart == targetEnd && base == targetStart && lastEndDiff == 0 && !anyEqualized
518 && (left || other.endDiff == 0)) {
519 endDiff = 0;
520 }
521
522 // Now that end is calculated we fix it and see if we can obtain it by default instead.
523 end = base+startDiff+endDiff;
524
525 if (left) {
526 if (endDiff == lastEndDiff) endDiff = 0; // default is our last diff.
527
528 } else if (other.style != NONE) {
529 // right side (and left not NONE)
530 if (other.endDiff == 0 && endDiff == lastEndDiff) endDiff = 0; // No left diff, default is our last
531 if (other.endDiff != 0 && other.endDiff == endDiff) endDiff = 0; // Left diff set, that's our default
532 }
533 }
534
535 /**
536 * Called at the end of processing a number range. Sets up the fields for the next one.
537 */
538 public void finish() {
539 lastEndDiff = end - (base + startDiff);
540 base = end;
541 }
542 }
543
544 /**
545 * The calculations are run on this class first, which keeps track of the sizes required to
546 * write the values without actually writing them anywhere.
547 *
548 * When passing a BitWriter to any method on this class, it must be a throw away one, as it
549 * will actually be written to by some of the common methods.
550 */
551 private class GatheringState extends State {
552 class BitSizes {
553 private boolean positive;
554 private boolean negative;
555 private int diff;
556
557 private boolean isSigned() {
558 return positive && negative;
559 }
560
561 private int calcWidth() {
562 int n = diff;
563 if (isSigned())
564 n++;
565 return 32 - Integer.numberOfLeadingZeros(n);
566 }
567 }
568
569 private final BitSizes start = new BitSizes();
570 private final BitSizes end = new BitSizes();
571
572 public GatheringState(int initialValue) {
573 setInitialValue(initialValue);
574 }
575
576 @Override
577 public void writeNumberingStyle(BitWriter bw) {
578 left.style = left.targetStyle;
579 right.style = right.targetStyle;
580 }
581
582 /**
583 * Calculate the size required for this write and keeps the maximum values.
584 * @param diff The value to examine.
585 */
586 public void writeStart(int diff) {
587 int val = testSign(start, diff);
588 if (val > start.diff)
589 start.diff = val;
590 }
591
592 /**
593 * Calculate the size required to hold this write and keeps the maximum.
594 * @param diff The value to be examined.
595 */
596 public void writeEnd(int diff) {
597 int val = testSign(end, diff);
598 if (val > end.diff)
599 end.diff = val;
600 }
601
602 /**
603 * Checks the sign properties required for the write.
604 */
605 private int testSign(BitSizes bs, int val) {
606 if (val > 0) {
607 bs.positive = true;
608 } else if (val < 0) {
609 bs.negative = true;
610 return -val;
611 }
612 return val;
613 }
614
615 /**
616 * Construct a writer that uses a bit width and sign properties that are sufficient to write
617 * all of the values found in the gathering phase. This is for start differences.
618 */
619 public VarBitWriter getStartWriter() {
620 return getVarBitWriter(start, START_WIDTH_MIN);
621 }
622 /**
623 * Construct a writer that uses a bit width and sign properties that are sufficient to write
624 * all of the values found in the gathering phase. This is for end differences.
625 */
626 public VarBitWriter getEndWriter() {
627 return getVarBitWriter(end, END_WIDTH_MIN);
628 }
629
630 /**
631 * Common code to create the bit writer.
632 * @see #getStartWriter()
633 * @see #getEndWriter()
634 */
635 private VarBitWriter getVarBitWriter(BitSizes bs, int minWidth) {
636 VarBitWriter writer = new VarBitWriter(bw, minWidth);
637 if (bs.isSigned())
638 writer.signed = true;
639 else if (bs.negative)
640 writer.negative = true;
641 int width = bs.calcWidth();
642 if (width > minWidth)
643 writer.bitWidth = width - minWidth;
644 if (writer.bitWidth > 15)
645 throw new Abandon("Difference too large");
646 return writer;
647 }
648 }
649
650 /**
651 * This is used to actually write the bit stream.
652 * @see GatheringState
653 */
654 static class WritingState extends State {
655
656 private VarBitWriter startWriter;
657 private VarBitWriter endWriter;
658 private boolean restoreBitWriters;
659 private final VarBitWriter savedStartWriter;
660 private final VarBitWriter savedEndWriter;
661
662 public WritingState(State state) {
663 setInitialValue(state.initialValue);
664 left.base = state.initialValue;
665 right.base = state.initialValue;
666
667 startWriter = state.getStartWriter();
668 endWriter = state.getEndWriter();
669 this.savedStartWriter = startWriter;
670 this.savedEndWriter = endWriter;
671 }
672
673 public void writeStart(int diff) {
674 startWriter.write(diff);
675 }
676
677 public void writeEnd(int diff) {
678 endWriter.write(diff);
679 }
680
681 @Override
682 public void writeNumberingStyle(BitWriter bw) {
683 if (left.targetStyle != left.style || right.targetStyle != right.style) {
684 bw.putn(0, 2);
685 bw.putn(left.targetStyle.getVal(), 2);
686 bw.putn(right.targetStyle.getVal(), 2);
687 left.style = left.targetStyle;
688 right.style = right.targetStyle;
689 }
690 }
691
692 /**
693 * You can change the number of bits and the sign properties of the writers before writing a nodes
694 * numbers. We don't try and work out the optimum sequence, but use this for tricky cases where
695 * we fail to work out the correct sizes in advance.
696 *
697 * This routine means that we will always be using writers that will deal with the next node numbers.
698 *
699 * @param bw The output stream writer.
700 */
701 @Override
702 public void writeBitWidths(BitWriter bw) {
703 newWriter(bw, startWriter, left.startDiff, right.startDiff, true);
704 newWriter(bw, endWriter, left.endDiff, right.endDiff, false);
705 }
706
707 /**
708 * Common code for writeBitWidths. Calculate the width and the sign properties required to
709 * represent the two numbers.
710 * @param leftDiff One of the numbers to be represented.
711 * @param rightDiff The other number to be represented.
712 * @param start Set to true if this is the start writer, else it is for the end writer.
713 */
714 private void newWriter(BitWriter bw, VarBitWriter writer, int leftDiff, int rightDiff, boolean start) {
715 if (!writer.checkFit(leftDiff) || !writer.checkFit(rightDiff)) {
716 int min = Math.min(leftDiff, rightDiff);
717 int max = Math.max(leftDiff, rightDiff);
718 boolean signed = false;
719 boolean negative = false;
720 if (max < 0)
721 negative = true;
722 else if (min < 0)
723 signed = true;
724
725 int val = Math.max(Math.abs(min), Math.abs(max));
726 int width = 32 - Integer.numberOfLeadingZeros(val);
727 if (signed) width++;
728
729 restoreBitWriters = true;
730 VarBitWriter nw;
731 if (start) {
732 startWriter = nw = new VarBitWriter(bw, START_WIDTH_MIN, negative, signed, width);
733 bw.putn(2, 4); // change width start
734 } else {
735 endWriter = nw = new VarBitWriter(bw, END_WIDTH_MIN, negative, signed, width);
736 bw.putn(0xa, 4); // change width end (0x8 | 0x2)
737 }
738 nw.writeFormat();
739 }
740 }
741
742 @Override
743 public void writeSkip(BitWriter bw, int n) {
744 if (n < 0)
745 throw new Abandon("bad skip value:" + n);
746
747 bw.putn(6, 3);
748
749 int width = 32 - Integer.numberOfLeadingZeros(n);
750 if (width > 5) {
751 bw.put1(true);
752 width = 10;
753 } else {
754 bw.put1(false);
755 width = 5;
756 }
757 bw.putn(n, width);
758 }
759
760 public VarBitWriter getStartWriter() {
761 return startWriter;
762 }
763
764 public VarBitWriter getEndWriter() {
765 return endWriter;
766 }
767
768 /**
769 * If we used an alternate writer for a node's numbers then we restore the default
770 * writers afterwards.
771 */
772 @Override
773 protected void restoreWriters() {
774 if (restoreBitWriters) {
775 startWriter = savedStartWriter;
776 endWriter = savedEndWriter;
777 restoreBitWriters = false;
778 }
779 }
780 }
781
782 }
783
784
785 class CityZipWriter {
786 private ByteArrayOutputStream buf;
787 private final String type;
788 private final int numItems;
789 private final int defaultIndex;
790 int []lastEncodedIndexes = {-1, -1};
791
792 public CityZipWriter(String type, int defIndex, int numItems) {
793 this.type = type;
794 this.defaultIndex = defIndex;
795 this.numItems = numItems;
796 buf = new ByteArrayOutputStream();
797 }
798
799 public ByteArrayOutputStream getBuffer(){
800 return buf;
801 }
802
803 public boolean compile(List<Numbers> numbers){
804 try {
805 // left and right entry in zip or city table
806 int []indexes = {defaultIndex, defaultIndex}; // current num
807 int []refIndexes = {defaultIndex, defaultIndex}; // previous num
808 int lastEncodedNodeIndex = -1;
809 boolean needsWrite = false;
810 for (Numbers num : numbers){
811 for (int side = 0; side < 2; side++){
812 indexes[side] = defaultIndex;
813 boolean left = (side == 0);
814 switch (type) {
815 case "zip":
816 ZipCodeInfo zipInfo = num.getZipCodeInfo(left);
817 if (zipInfo != null && zipInfo.getImgZip() != null) {
818 indexes[side] = zipInfo.getImgZip().getIndex();
819 }
820 break;
821 case "city":
822 CityInfo cityInfo = num.getCityInfo(left);
823 if (cityInfo != null && cityInfo.getImgCity() != null) {
824 indexes[side] = cityInfo.getImgCity().getIndex();
825 }
826 break;
827 default:
828 break;
829 }
830 }
831 if (indexes[0] == refIndexes[0] && indexes[1] == refIndexes[1])
832 continue;
833 needsWrite = true;
834 if (num.getIndex() > 0){
835 int range = num.getIndex() - 1;
836 if (lastEncodedNodeIndex > 0)
837 range -= lastEncodedNodeIndex;
838 encode(range, refIndexes);
839 }
840 refIndexes[0] = indexes[0];
841 refIndexes[1] = indexes[1];
842 lastEncodedNodeIndex = num.getIndex();
843 }
844 if (needsWrite){
845 int lastIndexWithNumbers = numbers.get(numbers.size()-1).getIndex();
846 int range = lastIndexWithNumbers - lastEncodedNodeIndex;
847 encode(range, indexes);
848 }
849 else {
850 buf.reset(); // probably not needed
851 }
852 } catch (Abandon e) {
853 return false;
854 }
855 return true;
856 }
857
858 private void encode(int skip, int[] indexes) {
859 // we can signal new values for left and / or right side
860
861 int sidesFlag = 0;
862 if (indexes[0] <= 0 && indexes[1] <= 0){
863 sidesFlag |= 4; // signal end of a zip code/city interval
864 if (indexes[0] == 0)
865 sidesFlag |= 1;
866 if (indexes[1] == 0)
867 sidesFlag |= 2;
868 } else {
869 if (indexes[1] != indexes[0]){
870 if (indexes[0] > 0 && indexes[0] != lastEncodedIndexes[0])
871 sidesFlag |= 1;
872 if (indexes[1] > 0 && indexes[1] != lastEncodedIndexes[1])
873 sidesFlag |= 2;
874 }
875 }
876
877 int initFlag = skip;
878 if (initFlag > 31){
879 // we have to write two bytes
880 buf.write((byte) (initFlag & 0x1f | 0x7<<5));
881 initFlag >>= 5;
882 }
883 initFlag |= sidesFlag << 5;
884 buf.write((byte) (initFlag & 0xff));
885 if ((sidesFlag & 4) == 0) {
886 if (indexes[0] > 0 && (sidesFlag == 0 || (sidesFlag & 1) == 1))
887 writeIndex(indexes[0]);
888 if (indexes[1] > 0 && (sidesFlag & 2) != 0)
889 writeIndex(indexes[1]);
890 }
891 lastEncodedIndexes[0] = indexes[0];
892 lastEncodedIndexes[1] = indexes[1];
893 }
894
895 void writeIndex(int val){
896 if (val <= 0)
897 return;
898 int ptrSize = Utils.numberToPointerSize(numItems);
899 buf.write(val);
900 if (ptrSize <= 1)
901 return;
902 buf.write(val >> 8);
903 if (ptrSize <= 2)
904 return;
905 buf.write(val >> 16);
906 }
907
908 }