comparison src/org/tmatesoft/hg/internal/ByteVector.java @ 574:88afffd39899

Improve memory consumption of HgManifest#getFileRevision(): avoid extra byte[] instances
author Artem Tikhomirov <tikhomirov.artem@gmail.com>
date Tue, 16 Apr 2013 14:44:57 +0200
parents
children a62079bc422b
comparison
equal deleted inserted replaced
573:e49f9d9513fa 574:88afffd39899
1 /*
2 * Copyright (c) 2013 TMate Software Ltd
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 as published by
6 * the Free Software Foundation; version 2 of the License.
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 * For information on how to redistribute this software under
14 * the terms of a license other than GNU General Public License
15 * contact TMate Software at support@hg4j.com
16 */
17 package org.tmatesoft.hg.internal;
18
19 import java.io.ByteArrayOutputStream;
20
21 /**
22 * Alternative to {@link ByteArrayOutputStream}, with extra operation that prevent extra byte[] instances
23 *
24 * @author Artem Tikhomirov
25 * @author TMate Software Ltd.
26 */
27 public class ByteVector {
28 private byte[] data;
29 private int count;
30 private final int increment;
31
32
33 public ByteVector(int initialSize, int increment) {
34 data = new byte[initialSize];
35 this.increment = increment;
36 }
37
38 public void add(int b) {
39 if (count == data.length) {
40 byte[] newData = new byte[count + increment];
41 System.arraycopy(data, 0, newData, 0, count);
42 data = newData;
43 }
44 data[count++] = (byte) b;
45 }
46
47 public int size() {
48 return count;
49 }
50
51 public void clear() {
52 count = 0;
53 }
54
55 public boolean equalsTo(byte[] array) {
56 if (array == null || array.length != count) {
57 return false;
58 }
59 for (int i = 0; i < count; i++) {
60 if (data[i] != array[i]) {
61 return false;
62 }
63 }
64 return true;
65 }
66
67 /**
68 * Copies content of this vector into destination array.
69 * @param destination array, greater or equal to {@link #size()} of the vector
70 */
71 public void copyTo(byte[] destination) {
72 if (destination == null || destination.length < count) {
73 throw new IllegalArgumentException();
74 }
75 System.arraycopy(data, 0, destination, 0, count);
76 }
77
78 public byte[] toByteArray() {
79 byte[] rv = new byte[count];
80 copyTo(rv);
81 return rv;
82 }
83 }