View Javadoc

1   /*
2    * Copyright (c) 2004-2007 Creative Sphere Limited.
3    * All rights reserved. This program and the accompanying materials
4    * are made available under the terms of the Eclipse Public License v1.0
5    * which accompanies this distribution, and is available at
6    * http://www.eclipse.org/legal/epl-v10.html
7    *
8    * Contributors:
9    *
10   *   Creative Sphere - initial API and implementation
11   *
12   */
13  package org.abstracthorizon.mercury.common.io;
14  
15  import java.io.IOException;
16  import java.io.Reader;
17  
18  /**
19   * StringBuffer reader.
20   *
21   * @author Daniel Sendula
22   */
23  public class StringBufferReader extends Reader {
24  
25      /** Buffer */
26      protected StringBuffer buffer;
27  
28      /** Pointer */
29      protected int ptr;
30  
31      /** Marker */
32      protected int mark = 0;
33  
34      /** Size */
35      protected int size;
36  
37      /**
38       * Constructor
39       * @param buffer string buffer
40       */
41      public StringBufferReader(StringBuffer buffer) {
42          this.buffer = buffer;
43          size = buffer.length();
44      }
45  
46      /**
47       * Constructor
48       * @param buffer string buffer
49       * @param from starting offset
50       * @param size size
51       */
52      public StringBufferReader(StringBuffer buffer, int from, int size) {
53          this.buffer = buffer;
54          ptr = from;
55          size = ptr+size;
56          if (ptr > buffer.length()) {
57              ptr = buffer.length();
58          }
59          if (size > buffer.length()) {
60              size = buffer.length();
61          }
62          if (size < ptr) {
63              size = ptr;
64          }
65      }
66  
67      @Override
68      public int read(char[] cbuf, int off, int len) throws IOException {
69          if (ptr >= buffer.length()) {
70              return -1;
71          }
72          if (len > size-ptr) {
73              len = size-ptr;
74          }
75          if (len == 0) {
76              return 0;
77          }
78          buffer.getChars(ptr, ptr+len, cbuf, off);
79          ptr = ptr + len;
80          return len;
81      }
82  
83      @Override
84      public void close() throws IOException {
85      }
86  
87      @Override
88      public boolean markSupported() {
89          return true;
90      }
91  
92      /**
93       * Marks position in string buffer
94       */
95      public void mark() {
96          mark = ptr;
97      }
98  
99      @Override
100     public void reset() {
101         ptr = mark;
102     }
103 
104     @Override
105     public boolean ready() {
106         return true;
107     }
108 
109     @Override
110     public long skip(long n) {
111         if (n > size - ptr) {
112             n = size - ptr;
113         }
114         ptr = ptr + (int)n;
115         return n;
116     }
117 
118 }