1 /*
2  * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Distribution License v. 1.0, which is available at
6  * http://www.eclipse.org/org/documents/edl-v10.php.
7  *
8  * SPDX-License-Identifier: BSD-3-Clause
9  */

10
11 package com.sun.xml.bind.v2.runtime.reflect;
12
13 import com.sun.xml.bind.api.AccessorException;
14 import com.sun.xml.bind.v2.runtime.XMLSerializer;
15
16 /**
17  * {@link Lister} for primitive type arrays.
18  *
19  * <p>
20  * B y t e ArrayLister is used as the master to generate the rest of the
21  * lister classes. Do not modify the generated copies.
22  */

23 final class PrimitiveArrayListerByte<BeanT> extends Lister<BeanT,byte[],Byte,PrimitiveArrayListerByte.ByteArrayPack> {
24     
25     private PrimitiveArrayListerByte() {
26     }
27
28     /*package*/ static void register() {
29         Lister.primitiveArrayListers.put(Byte.TYPE,new PrimitiveArrayListerByte());
30     }
31
32     public ListIterator<Byte> iterator(final byte[] objects, XMLSerializer context) {
33         return new ListIterator<Byte>() {
34             int idx=0;
35             public boolean hasNext() {
36                 return idx<objects.length;
37             }
38
39             public Byte next() {
40                 return objects[idx++];
41             }
42         };
43     }
44
45     public ByteArrayPack startPacking(BeanT current, Accessor<BeanT, byte[]> acc) {
46         return new ByteArrayPack();
47     }
48
49     public void addToPack(ByteArrayPack objects, Byte o) {
50         objects.add(o);
51     }
52
53     public void endPacking( ByteArrayPack pack, BeanT bean, Accessor<BeanT,byte[]> acc ) throws AccessorException {
54         acc.set(bean,pack.build());
55     }
56
57     public void reset(BeanT o,Accessor<BeanT,byte[]> acc) throws AccessorException {
58         acc.set(o,new byte[0]);
59     }
60
61     static final class ByteArrayPack {
62         byte[] buf = new byte[16];
63         int size;
64
65         void add(Byte b) {
66             if(buf.length==size) {
67                 // realloc
68                 byte[] nb = new byte[buf.length*2];
69                 System.arraycopy(buf,0,nb,0,buf.length);
70                 buf = nb;
71             }
72             if(b!=null)
73                 buf[size++] = b;
74         }
75
76         byte[] build() {
77             if(buf.length==size)
78                 // if we are lucky enough
79                 return buf;
80
81             byte[] r = new byte[size];
82             System.arraycopy(buf,0,r,0,size);
83             return r;
84         }
85     }
86 }
87