comparison src/org/tmatesoft/hg/internal/ByteArrayChannel.java @ 115:c0cc2535462c

Introduced channels to pipeline (and easily filter) data streams
author Artem Tikhomirov <tikhomirov.artem@gmail.com>
date Thu, 03 Feb 2011 23:32:08 +0100
parents
children 7567f4a42fe5
comparison
equal deleted inserted replaced
114:46291ec605a0 115:c0cc2535462c
1 /*
2 * Copyright (c) 2011 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@svnkit.com
16 */
17 package org.tmatesoft.hg.internal;
18
19 import java.nio.ByteBuffer;
20 import java.util.LinkedList;
21 import java.util.List;
22
23 import org.tmatesoft.hg.util.ByteChannel;
24
25 /**
26 *
27 * @author Artem Tikhomirov
28 * @author TMate Software Ltd.
29 */
30 public class ByteArrayChannel implements ByteChannel {
31 private final List<ByteBuffer> buffers;
32 private ByteBuffer target;
33 private byte[] result;
34
35 public ByteArrayChannel() {
36 this(-1);
37 }
38
39 public ByteArrayChannel(int size) {
40 if (size == -1) {
41 buffers = new LinkedList<ByteBuffer>();
42 } else {
43 if (size < 0) {
44 throw new IllegalArgumentException(String.valueOf(size));
45 }
46 buffers = null;
47 target = ByteBuffer.allocate(size);
48 }
49 }
50
51 // TODO document what happens on write after toArray() in each case
52 public int write(ByteBuffer buffer) throws Exception {
53 int rv = buffer.remaining();
54 if (buffers == null) {
55 target.put(buffer);
56 } else {
57 ByteBuffer copy = ByteBuffer.allocate(rv);
58 copy.put(buffer);
59 buffers.add(copy);
60 }
61 return rv;
62 }
63
64 public byte[] toArray() {
65 if (result != null) {
66 return result;
67 }
68 if (buffers == null) {
69 assert target.hasArray();
70 // int total = target.position();
71 // System.arraycopy(target.array(), new byte[total]);
72 // I don't want to duplicate byte[] for now
73 // although correct way of doing things is to make a copy and discard target
74 return target.array();
75 } else {
76 int total = 0;
77 for (ByteBuffer bb : buffers) {
78 bb.flip();
79 total += bb.limit();
80 }
81 result = new byte[total];
82 int off = 0;
83 for (ByteBuffer bb : buffers) {
84 bb.get(result, off, bb.limit());
85 off += bb.limit();
86 }
87 buffers.clear();
88 return result;
89 }
90 }
91 }