Moved ByteArray up to core/common now that it has no dependencies on qrcode/encoder.
[zxing.git] / core / src / com / google / zxing / common / ByteArray.java
1 /*
2  * Copyright 2008 ZXing authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package com.google.zxing.common;
18
19 /**
20  * This class implements an array of unsigned bytes.
21  *
22  * @author dswitkin@google.com (Daniel Switkin)
23  */
24 public final class ByteArray {
25
26   private static final int INITIAL_SIZE = 32;
27
28   private byte[] bytes;
29   private int size;
30
31   public ByteArray() {
32     bytes = null;
33     size = 0;
34   }
35
36   public ByteArray(int size) {
37     bytes = new byte[size];
38     this.size = size;
39   }
40
41   public ByteArray(String string) {
42     bytes = string.getBytes();
43     size = bytes.length;
44   }
45
46   public ByteArray(byte[] byteArray) {
47     bytes = byteArray;
48     size = bytes.length;
49   }
50
51   /**
52    * Access an unsigned byte at location index.
53    * @param index The index in the array to access.
54    * @return The unsigned value of the byte as an int.
55    */
56   public int at(int index) {
57     return bytes[index] & 0xff;
58   }
59
60   public void set(int index, int value) {
61     bytes[index] = (byte) value;
62   }
63
64   public int size() {
65     return size;
66   }
67
68   public boolean empty() {
69     return size == 0;
70   }
71
72   public void appendByte(int value) {
73     if (size == 0 || size >= bytes.length) {
74       int newSize = Math.max(INITIAL_SIZE, size * 2);
75       reserve(newSize);
76     }
77     bytes[size] = (byte) value;
78     size++;
79   }
80
81   public void reserve(int capacity) {
82     if (bytes == null || bytes.length < capacity) {
83       byte[] newArray = new byte[capacity];
84       if (bytes != null) {
85         System.arraycopy(bytes, 0, newArray, 0, bytes.length);
86       }
87       bytes = newArray;
88     }
89   }
90
91   // Copy count bytes from array source starting at offset.
92   public void set(byte[] source, int offset, int count) {
93     bytes = new byte[count];
94     size = count;
95     for (int x = 0; x < count; x++) {
96       bytes[x] = source[offset + x];
97     }
98   }
99
100 }