Remove unneeded Java 9+ check
[controller.git] / opendaylight / md-sal / sal-clustering-commons / src / main / java / org / opendaylight / controller / cluster / datastore / node / utils / stream / AbstractMagnesiumDataOutput.java
1 /*
2  * Copyright (c) 2019 PANTHEON.tech, s.r.o. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.cluster.datastore.node.utils.stream;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11
12 import java.io.DataOutput;
13 import java.io.IOException;
14 import java.io.StringWriter;
15 import java.math.BigDecimal;
16 import java.math.BigInteger;
17 import java.nio.charset.StandardCharsets;
18 import java.util.ArrayDeque;
19 import java.util.Deque;
20 import java.util.HashMap;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.Map.Entry;
24 import java.util.Optional;
25 import java.util.Set;
26 import javax.xml.transform.TransformerException;
27 import javax.xml.transform.TransformerFactory;
28 import javax.xml.transform.dom.DOMSource;
29 import javax.xml.transform.stream.StreamResult;
30 import org.eclipse.jdt.annotation.NonNull;
31 import org.opendaylight.yangtools.rfc8528.data.api.MountPointIdentifier;
32 import org.opendaylight.yangtools.yang.common.Empty;
33 import org.opendaylight.yangtools.yang.common.QName;
34 import org.opendaylight.yangtools.yang.common.QNameModule;
35 import org.opendaylight.yangtools.yang.common.Revision;
36 import org.opendaylight.yangtools.yang.common.Uint16;
37 import org.opendaylight.yangtools.yang.common.Uint32;
38 import org.opendaylight.yangtools.yang.common.Uint64;
39 import org.opendaylight.yangtools.yang.common.Uint8;
40 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
41 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 /**
50  * Abstract base class for NormalizedNodeDataOutput based on {@link MagnesiumNode}, {@link MagnesiumPathArgument} and
51  * {@link MagnesiumValue}.
52  */
53 abstract class AbstractMagnesiumDataOutput extends AbstractNormalizedNodeDataOutput {
54     private static final Logger LOG = LoggerFactory.getLogger(AbstractMagnesiumDataOutput.class);
55
56     // Marker for encoding state when we have entered startLeafNode() within a startMapEntry() and that leaf corresponds
57     // to a key carried within NodeIdentifierWithPredicates.
58     private static final Object KEY_LEAF_STATE = new Object();
59     // Marker for nodes which have simple content and do not use END_NODE marker to terminate
60     private static final Object NO_ENDNODE_STATE = new Object();
61
62     private static final TransformerFactory TF = TransformerFactory.newInstance();
63
64     /**
65      * Stack tracking encoding state. In general we track the node identifier of the currently-open element, but there
66      * are a few other circumstances where we push other objects. See {@link #KEY_LEAF_STATE} and
67      * {@link #NO_ENDNODE_STATE}.
68      */
69     private final Deque<Object> stack = new ArrayDeque<>();
70
71     // Coding maps
72     private final Map<AugmentationIdentifier, Integer> aidCodeMap = new HashMap<>();
73     private final Map<QNameModule, Integer> moduleCodeMap = new HashMap<>();
74     private final Map<String, Integer> stringCodeMap = new HashMap<>();
75     private final Map<QName, Integer> qnameCodeMap = new HashMap<>();
76
77     AbstractMagnesiumDataOutput(final DataOutput output) {
78         super(output);
79     }
80
81     @Override
82     public final void startLeafNode(final NodeIdentifier name) throws IOException {
83         final Object current = stack.peek();
84         if (current instanceof NodeIdentifierWithPredicates) {
85             final QName qname = name.getNodeType();
86             if (((NodeIdentifierWithPredicates) current).containsKey(qname)) {
87                 writeQNameNode(MagnesiumNode.NODE_LEAF | MagnesiumNode.PREDICATE_ONE, qname);
88                 stack.push(KEY_LEAF_STATE);
89                 return;
90             }
91         }
92
93         startSimpleNode(MagnesiumNode.NODE_LEAF, name);
94     }
95
96     @Override
97     public final void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
98         startQNameNode(MagnesiumNode.NODE_LEAFSET, name);
99     }
100
101     @Override
102     public final void startOrderedLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
103         startQNameNode(MagnesiumNode.NODE_LEAFSET_ORDERED, name);
104     }
105
106     @Override
107     public final void startLeafSetEntryNode(final NodeWithValue<?> name) throws IOException {
108         if (matchesParentQName(name.getNodeType())) {
109             output.writeByte(MagnesiumNode.NODE_LEAFSET_ENTRY);
110             stack.push(NO_ENDNODE_STATE);
111         } else {
112             startSimpleNode(MagnesiumNode.NODE_LEAFSET_ENTRY, name);
113         }
114     }
115
116     @Override
117     public final void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
118         startQNameNode(MagnesiumNode.NODE_CONTAINER, name);
119     }
120
121     @Override
122     public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
123         startQNameNode(MagnesiumNode.NODE_LIST, name);
124     }
125
126     @Override
127     public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
128         startInheritedNode(MagnesiumNode.NODE_LIST_ENTRY, name);
129     }
130
131     @Override
132     public final void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
133         startQNameNode(MagnesiumNode.NODE_MAP, name);
134     }
135
136     @Override
137     public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
138             throws IOException {
139         final int size = identifier.size();
140         if (size == 1) {
141             startInheritedNode((byte) (MagnesiumNode.NODE_MAP_ENTRY | MagnesiumNode.PREDICATE_ONE), identifier);
142         } else if (size == 0) {
143             startInheritedNode((byte) (MagnesiumNode.NODE_MAP_ENTRY | MagnesiumNode.PREDICATE_ZERO), identifier);
144         } else if (size < 256) {
145             startInheritedNode((byte) (MagnesiumNode.NODE_MAP_ENTRY | MagnesiumNode.PREDICATE_1B), identifier);
146             output.writeByte(size);
147         } else {
148             startInheritedNode((byte) (MagnesiumNode.NODE_MAP_ENTRY | MagnesiumNode.PREDICATE_4B), identifier);
149             output.writeInt(size);
150         }
151
152         writePredicates(identifier);
153     }
154
155     @Override
156     public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
157         startQNameNode(MagnesiumNode.NODE_MAP_ORDERED, name);
158     }
159
160     @Override
161     public final void startChoiceNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
162         startQNameNode(MagnesiumNode.NODE_CHOICE, name);
163     }
164
165     @Override
166     public final void startAugmentationNode(final AugmentationIdentifier identifier) throws IOException {
167         final Integer code = aidCodeMap.get(identifier);
168         if (code == null) {
169             aidCodeMap.put(identifier, aidCodeMap.size());
170             output.writeByte(MagnesiumNode.NODE_AUGMENTATION | MagnesiumNode.ADDR_DEFINE);
171             final Set<QName> qnames = identifier.getPossibleChildNames();
172             output.writeInt(qnames.size());
173             for (QName qname : qnames) {
174                 writeQNameInternal(qname);
175             }
176         } else {
177             writeNodeType(MagnesiumNode.NODE_AUGMENTATION, code);
178         }
179         stack.push(identifier);
180     }
181
182     @Override
183     public final boolean startAnyxmlNode(final NodeIdentifier name, final Class<?> objectModel) throws IOException {
184         if (DOMSource.class.isAssignableFrom(objectModel)) {
185             startSimpleNode(MagnesiumNode.NODE_ANYXML, name);
186             return true;
187         }
188         return false;
189     }
190
191     @Override
192     public final void domSourceValue(final DOMSource value) throws IOException {
193         final StringWriter writer = new StringWriter();
194         try {
195             TF.newTransformer().transform(value, new StreamResult(writer));
196         } catch (TransformerException e) {
197             throw new IOException("Error writing anyXml", e);
198         }
199         writeValue(writer.toString());
200     }
201
202     @Override
203     public final void startYangModeledAnyXmlNode(final NodeIdentifier name, final int childSizeHint)
204             throws IOException {
205         // FIXME: implement this
206         throw new UnsupportedOperationException();
207     }
208
209     @Override
210     public final void endNode() throws IOException {
211         if (stack.pop() instanceof PathArgument) {
212             output.writeByte(MagnesiumNode.NODE_END);
213         }
214     }
215
216     @Override
217     public final void scalarValue(final Object value) throws IOException {
218         if (KEY_LEAF_STATE.equals(stack.peek())) {
219             LOG.trace("Inside a map entry key leaf, not emitting value {}", value);
220         } else {
221             writeObject(value);
222         }
223     }
224
225     @Override
226     final void writeQNameInternal(final QName qname) throws IOException {
227         final Integer code = qnameCodeMap.get(qname);
228         if (code == null) {
229             output.writeByte(MagnesiumValue.QNAME);
230             encodeQName(qname);
231         } else {
232             writeQNameRef(code);
233         }
234     }
235
236     @Override
237     final void writePathArgumentInternal(final PathArgument pathArgument) throws IOException {
238         if (pathArgument instanceof NodeIdentifier) {
239             writeNodeIdentifier((NodeIdentifier) pathArgument);
240         } else if (pathArgument instanceof NodeIdentifierWithPredicates) {
241             writeNodeIdentifierWithPredicates((NodeIdentifierWithPredicates) pathArgument);
242         } else if (pathArgument instanceof AugmentationIdentifier) {
243             writeAugmentationIdentifier((AugmentationIdentifier) pathArgument);
244         } else if (pathArgument instanceof NodeWithValue) {
245             writeNodeWithValue((NodeWithValue<?>) pathArgument);
246         } else if (pathArgument instanceof MountPointIdentifier) {
247             writeMountPointIdentifier((MountPointIdentifier) pathArgument);
248         } else {
249             throw new IOException("Unhandled PathArgument " + pathArgument);
250         }
251     }
252
253     private void writeAugmentationIdentifier(final AugmentationIdentifier identifier) throws IOException {
254         final Set<QName> qnames = identifier.getPossibleChildNames();
255         final int size = qnames.size();
256         if (size < 29) {
257             output.writeByte(MagnesiumPathArgument.AUGMENTATION_IDENTIFIER
258                 | size << MagnesiumPathArgument.AID_COUNT_SHIFT);
259         } else if (size < 256) {
260             output.writeByte(MagnesiumPathArgument.AUGMENTATION_IDENTIFIER | MagnesiumPathArgument.AID_COUNT_1B);
261             output.writeByte(size);
262         } else if (size < 65536) {
263             output.writeByte(MagnesiumPathArgument.AUGMENTATION_IDENTIFIER | MagnesiumPathArgument.AID_COUNT_2B);
264             output.writeShort(size);
265         } else {
266             output.writeByte(MagnesiumPathArgument.AUGMENTATION_IDENTIFIER | MagnesiumPathArgument.AID_COUNT_4B);
267             output.writeInt(size);
268         }
269
270         for (QName qname : qnames) {
271             writeQNameInternal(qname);
272         }
273     }
274
275     private void writeNodeIdentifier(final NodeIdentifier identifier) throws IOException {
276         writePathArgumentQName(identifier.getNodeType(), MagnesiumPathArgument.NODE_IDENTIFIER);
277     }
278
279     private void writeMountPointIdentifier(final MountPointIdentifier identifier) throws IOException {
280         writePathArgumentQName(identifier.getNodeType(), MagnesiumPathArgument.MOUNTPOINT_IDENTIFIER);
281     }
282
283     private void writeNodeIdentifierWithPredicates(final NodeIdentifierWithPredicates identifier) throws IOException {
284         final int size = identifier.size();
285         if (size < 5) {
286             writePathArgumentQName(identifier.getNodeType(),
287                 (byte) (MagnesiumPathArgument.NODE_IDENTIFIER_WITH_PREDICATES
288                         | size << MagnesiumPathArgument.SIZE_SHIFT));
289         } else if (size < 256) {
290             writePathArgumentQName(identifier.getNodeType(),
291                 (byte) (MagnesiumPathArgument.NODE_IDENTIFIER_WITH_PREDICATES | MagnesiumPathArgument.SIZE_1B));
292             output.writeByte(size);
293         } else if (size < 65536) {
294             writePathArgumentQName(identifier.getNodeType(),
295                 (byte) (MagnesiumPathArgument.NODE_IDENTIFIER_WITH_PREDICATES | MagnesiumPathArgument.SIZE_2B));
296             output.writeShort(size);
297         } else {
298             writePathArgumentQName(identifier.getNodeType(),
299                 (byte) (MagnesiumPathArgument.NODE_IDENTIFIER_WITH_PREDICATES | MagnesiumPathArgument.SIZE_4B));
300             output.writeInt(size);
301         }
302
303         writePredicates(identifier);
304     }
305
306     private void writePredicates(final NodeIdentifierWithPredicates identifier) throws IOException {
307         for (Entry<QName, Object> e : identifier.entrySet()) {
308             writeQNameInternal(e.getKey());
309             writeObject(e.getValue());
310         }
311     }
312
313     private void writeNodeWithValue(final NodeWithValue<?> identifier) throws IOException {
314         writePathArgumentQName(identifier.getNodeType(), MagnesiumPathArgument.NODE_WITH_VALUE);
315         writeObject(identifier.getValue());
316     }
317
318     private void writePathArgumentQName(final QName qname, final byte typeHeader) throws IOException {
319         final Integer code = qnameCodeMap.get(qname);
320         if (code != null) {
321             final int val = code;
322             if (val < 256) {
323                 output.writeByte(typeHeader | MagnesiumPathArgument.QNAME_REF_1B);
324                 output.writeByte(val);
325             } else if (val < 65792) {
326                 output.writeByte(typeHeader | MagnesiumPathArgument.QNAME_REF_2B);
327                 output.writeShort(val - 256);
328             } else {
329                 output.writeByte(typeHeader | MagnesiumPathArgument.QNAME_REF_4B);
330                 output.writeInt(val);
331             }
332         } else {
333             // implied '| MagnesiumPathArgument.QNAME_DEF'
334             output.writeByte(typeHeader);
335             encodeQName(qname);
336         }
337     }
338
339     @Override
340     final void writeYangInstanceIdentifierInternal(final YangInstanceIdentifier identifier) throws IOException {
341         writeValue(identifier);
342     }
343
344     private void writeObject(final @NonNull Object value) throws IOException {
345         if (value instanceof String) {
346             writeValue((String) value);
347         } else if (value instanceof Boolean) {
348             writeValue((Boolean) value);
349         } else if (value instanceof Byte) {
350             writeValue((Byte) value);
351         } else if (value instanceof Short) {
352             writeValue((Short) value);
353         } else if (value instanceof Integer) {
354             writeValue((Integer) value);
355         } else if (value instanceof Long) {
356             writeValue((Long) value);
357         } else if (value instanceof Uint8) {
358             writeValue((Uint8) value);
359         } else if (value instanceof Uint16) {
360             writeValue((Uint16) value);
361         } else if (value instanceof Uint32) {
362             writeValue((Uint32) value);
363         } else if (value instanceof Uint64) {
364             writeValue((Uint64) value);
365         } else if (value instanceof QName) {
366             writeQNameInternal((QName) value);
367         } else if (value instanceof YangInstanceIdentifier) {
368             writeValue((YangInstanceIdentifier) value);
369         } else if (value instanceof byte[]) {
370             writeValue((byte[]) value);
371         } else if (value instanceof Empty) {
372             output.writeByte(MagnesiumValue.EMPTY);
373         } else if (value instanceof Set) {
374             writeValue((Set<?>) value);
375         } else if (value instanceof BigDecimal) {
376             writeValue((BigDecimal) value);
377         } else if (value instanceof BigInteger) {
378             writeValue((BigInteger) value);
379         } else {
380             throw new IOException("Unhandled value type " + value.getClass());
381         }
382     }
383
384     private void writeValue(final boolean value) throws IOException {
385         output.writeByte(value ? MagnesiumValue.BOOLEAN_TRUE : MagnesiumValue.BOOLEAN_FALSE);
386     }
387
388     private void writeValue(final byte value) throws IOException {
389         if (value != 0) {
390             output.writeByte(MagnesiumValue.INT8);
391             output.writeByte(value);
392         } else {
393             output.writeByte(MagnesiumValue.INT8_0);
394         }
395     }
396
397     private void writeValue(final short value) throws IOException {
398         if (value != 0) {
399             output.writeByte(MagnesiumValue.INT16);
400             output.writeShort(value);
401         } else {
402             output.writeByte(MagnesiumValue.INT16_0);
403         }
404     }
405
406     private void writeValue(final int value) throws IOException {
407         if ((value & 0xFFFF0000) != 0) {
408             output.writeByte(MagnesiumValue.INT32);
409             output.writeInt(value);
410         } else if (value != 0) {
411             output.writeByte(MagnesiumValue.INT32_2B);
412             output.writeShort(value);
413         } else {
414             output.writeByte(MagnesiumValue.INT32_0);
415         }
416     }
417
418     private void writeValue(final long value) throws IOException {
419         if ((value & 0xFFFFFFFF00000000L) != 0) {
420             output.writeByte(MagnesiumValue.INT64);
421             output.writeLong(value);
422         } else if (value != 0) {
423             output.writeByte(MagnesiumValue.INT64_4B);
424             output.writeInt((int) value);
425         } else {
426             output.writeByte(MagnesiumValue.INT64_0);
427         }
428     }
429
430     private void writeValue(final Uint8 value) throws IOException {
431         final byte b = value.byteValue();
432         if (b != 0) {
433             output.writeByte(MagnesiumValue.UINT8);
434             output.writeByte(b);
435         } else {
436             output.writeByte(MagnesiumValue.UINT8_0);
437         }
438     }
439
440     private void writeValue(final Uint16 value) throws IOException {
441         final short s = value.shortValue();
442         if (s != 0) {
443             output.writeByte(MagnesiumValue.UINT16);
444             output.writeShort(s);
445         } else {
446             output.writeByte(MagnesiumValue.UINT16_0);
447         }
448     }
449
450     private void writeValue(final Uint32 value) throws IOException {
451         final int i = value.intValue();
452         if ((i & 0xFFFF0000) != 0) {
453             output.writeByte(MagnesiumValue.UINT32);
454             output.writeInt(i);
455         } else if (i != 0) {
456             output.writeByte(MagnesiumValue.UINT32_2B);
457             output.writeShort(i);
458         } else {
459             output.writeByte(MagnesiumValue.UINT32_0);
460         }
461     }
462
463     private void writeValue(final Uint64 value) throws IOException {
464         final long l = value.longValue();
465         if ((l & 0xFFFFFFFF00000000L) != 0) {
466             output.writeByte(MagnesiumValue.UINT64);
467             output.writeLong(l);
468         } else if (l != 0) {
469             output.writeByte(MagnesiumValue.UINT64_4B);
470             output.writeInt((int) l);
471         } else {
472             output.writeByte(MagnesiumValue.UINT64_0);
473         }
474     }
475
476     private void writeValue(final BigDecimal value) throws IOException {
477         output.writeByte(MagnesiumValue.BIGDECIMAL);
478         output.writeUTF(value.toString());
479     }
480
481     abstract void writeValue(BigInteger value) throws IOException;
482
483     private void writeValue(final String value) throws IOException {
484         if (value.isEmpty()) {
485             output.writeByte(MagnesiumValue.STRING_EMPTY);
486         } else if (value.length() <= Short.MAX_VALUE / 2) {
487             output.writeByte(MagnesiumValue.STRING_UTF);
488             output.writeUTF(value);
489         } else if (value.length() <= 1048576) {
490             final byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
491             if (bytes.length < 65536) {
492                 output.writeByte(MagnesiumValue.STRING_2B);
493                 output.writeShort(bytes.length);
494             } else {
495                 output.writeByte(MagnesiumValue.STRING_4B);
496                 output.writeInt(bytes.length);
497             }
498             output.write(bytes);
499         } else {
500             output.writeByte(MagnesiumValue.STRING_CHARS);
501             output.writeInt(value.length());
502             output.writeChars(value);
503         }
504     }
505
506     private void writeValue(final byte[] value) throws IOException {
507         if (value.length < 128) {
508             output.writeByte(MagnesiumValue.BINARY_0 + value.length);
509         } else if (value.length < 384) {
510             output.writeByte(MagnesiumValue.BINARY_1B);
511             output.writeByte(value.length - 128);
512         } else if (value.length < 65920) {
513             output.writeByte(MagnesiumValue.BINARY_2B);
514             output.writeShort(value.length - 384);
515         } else {
516             output.writeByte(MagnesiumValue.BINARY_4B);
517             output.writeInt(value.length);
518         }
519         output.write(value);
520     }
521
522     private void writeValue(final YangInstanceIdentifier value) throws IOException {
523         final List<PathArgument> args = value.getPathArguments();
524         final int size = args.size();
525         if (size > 31) {
526             output.writeByte(MagnesiumValue.YIID);
527             output.writeInt(size);
528         } else {
529             output.writeByte(MagnesiumValue.YIID_0 + size);
530         }
531         for (PathArgument arg : args) {
532             writePathArgumentInternal(arg);
533         }
534     }
535
536     private void writeValue(final Set<?> value) throws IOException {
537         final int size = value.size();
538         if (size < 29) {
539             output.writeByte(MagnesiumValue.BITS_0 + size);
540         } else if (size < 285) {
541             output.writeByte(MagnesiumValue.BITS_1B);
542             output.writeByte(size - 29);
543         } else if (size < 65821) {
544             output.writeByte(MagnesiumValue.BITS_2B);
545             output.writeShort(size - 285);
546         } else {
547             output.writeByte(MagnesiumValue.BITS_4B);
548             output.writeInt(size);
549         }
550
551         for (Object bit : value) {
552             checkArgument(bit instanceof String, "Expected value type to be String but was %s", bit);
553             encodeString((String) bit);
554         }
555     }
556
557     // Check if the proposed QName matches the parent. This is only effective if the parent is identified by
558     // NodeIdentifier -- which is typically true
559     private boolean matchesParentQName(final QName qname) {
560         final Object current = stack.peek();
561         return current instanceof NodeIdentifier && qname.equals(((NodeIdentifier) current).getNodeType());
562     }
563
564     // Start an END_NODE-terminated node, which typically has a QName matching the parent. If that is the case we emit
565     // a parent reference instead of an explicit QName reference -- saving at least one byte
566     private void startInheritedNode(final byte type, final PathArgument name) throws IOException {
567         final QName qname = name.getNodeType();
568         if (matchesParentQName(qname)) {
569             output.write(type);
570         } else {
571             writeQNameNode(type, qname);
572         }
573         stack.push(name);
574     }
575
576     // Start an END_NODE-terminated node, which needs its QName encoded
577     private void startQNameNode(final byte type, final PathArgument name) throws IOException {
578         writeQNameNode(type, name.getNodeType());
579         stack.push(name);
580     }
581
582     // Start a simple node, which is not terminated through END_NODE and encode its QName
583     private void startSimpleNode(final byte type, final PathArgument name) throws IOException {
584         writeQNameNode(type, name.getNodeType());
585         stack.push(NO_ENDNODE_STATE);
586     }
587
588     // Encode a QName-based (i.e. NodeIdentifier*) node with a particular QName. This will either result in a QName
589     // definition, or a reference, where this is encoded along with the node type.
590     private void writeQNameNode(final int type, final @NonNull QName qname) throws IOException {
591         final Integer code = qnameCodeMap.get(qname);
592         if (code == null) {
593             output.writeByte(type | MagnesiumNode.ADDR_DEFINE);
594             encodeQName(qname);
595         } else {
596             writeNodeType(type, code);
597         }
598     }
599
600     // Write a node type + lookup
601     private void writeNodeType(final int type, final int code) throws IOException {
602         if (code <= 255) {
603             output.writeByte(type | MagnesiumNode.ADDR_LOOKUP_1B);
604             output.writeByte(code);
605         } else {
606             output.writeByte(type | MagnesiumNode.ADDR_LOOKUP_4B);
607             output.writeInt(code);
608         }
609     }
610
611     // Encode a QName using lookup tables, resuling either in a reference to an existing entry, or emitting two
612     // String values.
613     private void encodeQName(final @NonNull QName qname) throws IOException {
614         final Integer prev = qnameCodeMap.put(qname, qnameCodeMap.size());
615         if (prev != null) {
616             throw new IOException("Internal coding error: attempted to re-encode " + qname + "%s already encoded as "
617                     + prev);
618         }
619
620         final QNameModule module = qname.getModule();
621         final Integer code = moduleCodeMap.get(module);
622         if (code == null) {
623             moduleCodeMap.put(module, moduleCodeMap.size());
624             encodeString(module.getNamespace().toString());
625             final Optional<Revision> rev = module.getRevision();
626             if (rev.isPresent()) {
627                 encodeString(rev.get().toString());
628             } else {
629                 output.writeByte(MagnesiumValue.STRING_EMPTY);
630             }
631         } else {
632             writeModuleRef(code);
633         }
634         encodeString(qname.getLocalName());
635     }
636
637     // Encode a String using lookup tables, resulting either in a reference to an existing entry, or emitting as
638     // a literal value
639     private void encodeString(final @NonNull String str) throws IOException {
640         final Integer code = stringCodeMap.get(str);
641         if (code != null) {
642             writeRef(code);
643         } else {
644             stringCodeMap.put(str, stringCodeMap.size());
645             writeValue(str);
646         }
647     }
648
649     // Write a QName with a lookup table reference. This is a combination of asserting the value is a QName plus
650     // the effects of writeRef()
651     private void writeQNameRef(final int code) throws IOException {
652         final int val = code;
653         if (val < 256) {
654             output.writeByte(MagnesiumValue.QNAME_REF_1B);
655             output.writeByte(val);
656         } else if (val < 65792) {
657             output.writeByte(MagnesiumValue.QNAME_REF_2B);
658             output.writeShort(val - 256);
659         } else {
660             output.writeByte(MagnesiumValue.QNAME_REF_4B);
661             output.writeInt(val);
662         }
663     }
664
665     // Write a lookup table reference, which table is being referenced is implied by the caller
666     private void writeRef(final int code) throws IOException {
667         final int val = code;
668         if (val < 256) {
669             output.writeByte(MagnesiumValue.STRING_REF_1B);
670             output.writeByte(val);
671         } else if (val < 65792) {
672             output.writeByte(MagnesiumValue.STRING_REF_2B);
673             output.writeShort(val - 256);
674         } else {
675             output.writeByte(MagnesiumValue.STRING_REF_4B);
676             output.writeInt(val);
677         }
678     }
679
680     // Write a lookup module table reference, which table is being referenced is implied by the caller
681     private void writeModuleRef(final int code) throws IOException {
682         final int val = code;
683         if (val < 256) {
684             output.writeByte(MagnesiumValue.MODREF_1B);
685             output.writeByte(val);
686         } else if (val < 65792) {
687             output.writeByte(MagnesiumValue.MODREF_2B);
688             output.writeShort(val - 256);
689         } else {
690             output.writeByte(MagnesiumValue.MODREF_4B);
691             output.writeInt(val);
692         }
693     }
694 }