View Javadoc
1   /*
2    * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org> and others
3    *
4    * This program and the accompanying materials are made available under the
5    * terms of the Eclipse Distribution License v. 1.0 which is available at
6    * https://www.eclipse.org/org/documents/edl-v10.php.
7    *
8    * SPDX-License-Identifier: BSD-3-Clause
9    */
10  
11  package org.eclipse.jgit.util;
12  
13  /**
14   * A rough character sequence around a raw byte buffer.
15   * <p>
16   * Characters are assumed to be 8-bit US-ASCII.
17   */
18  public final class RawCharSequence implements CharSequence {
19  	/** A zero-length character sequence. */
20  	public static final RawCharSequencee.html#RawCharSequence">RawCharSequence EMPTY = new RawCharSequence(null, 0, 0);
21  
22  	final byte[] buffer;
23  
24  	final int startPtr;
25  
26  	final int endPtr;
27  
28  	/**
29  	 * Create a rough character sequence around the raw byte buffer.
30  	 *
31  	 * @param buf
32  	 *            buffer to scan.
33  	 * @param start
34  	 *            starting position for the sequence.
35  	 * @param end
36  	 *            ending position for the sequence.
37  	 */
38  	public RawCharSequence(byte[] buf, int start, int end) {
39  		buffer = buf;
40  		startPtr = start;
41  		endPtr = end;
42  	}
43  
44  	/** {@inheritDoc} */
45  	@Override
46  	public char charAt(int index) {
47  		return (char) (buffer[startPtr + index] & 0xff);
48  	}
49  
50  	/** {@inheritDoc} */
51  	@Override
52  	public int length() {
53  		return endPtr - startPtr;
54  	}
55  
56  	/** {@inheritDoc} */
57  	@Override
58  	public CharSequence subSequence(int start, int end) {
59  		return new RawCharSequence(buffer, startPtr + start, startPtr + end);
60  	}
61  
62  	/** {@inheritDoc} */
63  	@Override
64  	public String toString() {
65  		final int n = length();
66  		final StringBuilder b = new StringBuilder(n);
67  		for (int i = 0; i < n; i++)
68  			b.append(charAt(i));
69  		return b.toString();
70  	}
71  }