1 /* Copyright (C) 2002-2005 RealVNC Ltd.  All Rights Reserved.
2  * Copyright (C) 2011-2019 Brian P. Hinz
3  *
4  * This 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; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This software is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this software; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
17  * USA.
18  */
19 
20 //
21 // A MemOutStream grows as needed when data is written to it.
22 //
23 
24 package com.tigervnc.rdr;
25 
26 public class MemOutStream extends OutStream {
27 
MemOutStream(int len)28   public MemOutStream(int len) {
29     b = new byte[len];
30     ptr = 0;
31     end = len;
32   }
MemOutStream()33   public MemOutStream() { this(1024); }
34 
length()35   public int length() { return ptr; }
clear()36   public void clear() { ptr = 0; };
reposition(int pos)37   public void reposition(int pos) { ptr = pos; }
38 
39   // data() returns a pointer to the buffer.
40 
data()41   public final byte[] data() { return b; }
42 
43   // overrun() either doubles the buffer or adds enough space for nItems of
44   // size itemSize bytes.
45 
overrun(int itemSize, int nItems)46   protected int overrun(int itemSize, int nItems) {
47     int len = ptr + itemSize * nItems;
48     if (len < end * 2)
49       len = end * 2;
50 
51     if (len < end)
52       throw new Exception("Overflow in MemOutStream::overrun()");
53 
54     byte[] newBuf = new byte[len];
55     System.arraycopy(b, 0, newBuf, 0, ptr);
56     b = newBuf;
57     end = len;
58 
59     return nItems;
60   }
61 }
62