Expose RawParseUtils.match to application callers
[egit.git] / org.spearce.jgit / src / org / spearce / jgit / util / RawParseUtils.java
blob51535b549a4235c56d5119f1cff08ed5bdd2c783
1 /*
2 * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
4 * All rights reserved.
6 * Redistribution and use in source and binary forms, with or
7 * without modification, are permitted provided that the following
8 * conditions are met:
10 * - Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
13 * - Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials provided
16 * with the distribution.
18 * - Neither the name of the Git Development Community nor the
19 * names of its contributors may be used to endorse or promote
20 * products derived from this software without specific prior
21 * written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
24 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
25 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
28 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
29 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
33 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
35 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 package org.spearce.jgit.util;
40 import java.nio.ByteBuffer;
41 import java.nio.charset.Charset;
42 import java.util.Arrays;
44 import org.spearce.jgit.lib.Constants;
45 import org.spearce.jgit.lib.PersonIdent;
47 /** Handy utility functions to parse raw object contents. */
48 public final class RawParseUtils {
49 private static final byte[] author = Constants.encodeASCII("author ");
51 private static final byte[] committer = Constants.encodeASCII("committer ");
53 private static final byte[] encoding = Constants.encodeASCII("encoding ");
55 private static final byte[] digits;
57 static {
58 digits = new byte['9' + 1];
59 Arrays.fill(digits, (byte) -1);
60 for (char i = '0'; i <= '9'; i++)
61 digits[i] = (byte) (i - '0');
64 /**
65 * Determine if b[ptr] matches src.
67 * @param b
68 * the buffer to scan.
69 * @param ptr
70 * first position within b, this should match src[0].
71 * @param src
72 * the buffer to test for equality with b.
73 * @return ptr += src.length if b[ptr..src.length] == src; else -1.
75 public static final int match(final byte[] b, int ptr, final byte[] src) {
76 if (ptr + src.length >= b.length)
77 return -1;
78 for (int i = 0; i < src.length; i++, ptr++)
79 if (b[ptr] != src[i])
80 return -1;
81 return ptr;
84 private static final byte[] base10byte = { '0', '1', '2', '3', '4', '5',
85 '6', '7', '8', '9' };
87 /**
88 * Format a base 10 numeric into a temporary buffer.
89 * <p>
90 * Formatting is performed backwards. The method starts at offset
91 * <code>o-1</code> and ends at <code>o-1-digits</code>, where
92 * <code>digits</code> is the number of positions necessary to store the
93 * base 10 value.
94 * <p>
95 * The argument and return values from this method make it easy to chain
96 * writing, for example:
97 * </p>
99 * <pre>
100 * final byte[] tmp = new byte[64];
101 * int ptr = tmp.length;
102 * tmp[--ptr] = '\n';
103 * ptr = RawParseUtils.formatBase10(tmp, ptr, 32);
104 * tmp[--ptr] = ' ';
105 * ptr = RawParseUtils.formatBase10(tmp, ptr, 18);
106 * tmp[--ptr] = 0;
107 * final String str = new String(tmp, ptr, tmp.length - ptr);
108 * </pre>
110 * @param b
111 * buffer to write into.
112 * @param o
113 * one offset past the location where writing will begin; writing
114 * proceeds towards lower index values.
115 * @param value
116 * the value to store.
117 * @return the new offset value <code>o</code>. This is the position of
118 * the last byte written. Additional writing should start at one
119 * position earlier.
121 public static int formatBase10(final byte[] b, int o, int value) {
122 if (value == 0) {
123 b[--o] = '0';
124 return o;
126 final boolean isneg = value < 0;
127 while (value != 0) {
128 b[--o] = base10byte[value % 10];
129 value /= 10;
131 if (isneg)
132 b[--o] = '-';
133 return o;
137 * Parse a base 10 numeric from a sequence of ASCII digits.
138 * <p>
139 * Digit sequences can begin with an optional run of spaces before the
140 * sequence, and may start with a '+' or a '-' to indicate sign position.
141 * Any other characters will cause the method to stop and return the current
142 * result to the caller.
144 * @param b
145 * buffer to scan.
146 * @param ptr
147 * position within buffer to start parsing digits at.
148 * @param ptrResult
149 * optional location to return the new ptr value through. If null
150 * the ptr value will be discarded.
151 * @return the value at this location; 0 if the location is not a valid
152 * numeric.
154 public static final int parseBase10(final byte[] b, int ptr,
155 final MutableInteger ptrResult) {
156 int r = 0;
157 int sign = 0;
158 try {
159 final int sz = b.length;
160 while (ptr < sz && b[ptr] == ' ')
161 ptr++;
162 if (ptr >= sz)
163 return 0;
165 switch (b[ptr]) {
166 case '-':
167 sign = -1;
168 ptr++;
169 break;
170 case '+':
171 ptr++;
172 break;
175 while (ptr < sz) {
176 final byte v = digits[b[ptr]];
177 if (v < 0)
178 break;
179 r = (r * 10) + v;
180 ptr++;
182 } catch (ArrayIndexOutOfBoundsException e) {
183 // Not a valid digit.
185 if (ptrResult != null)
186 ptrResult.value = ptr;
187 return sign < 0 ? -r : r;
191 * Parse a Git style timezone string.
192 * <p>
193 * The sequence "-0315" will be parsed as the numeric value -195, as the
194 * lower two positions count minutes, not 100ths of an hour.
196 * @param b
197 * buffer to scan.
198 * @param ptr
199 * position within buffer to start parsing digits at.
200 * @return the timezone at this location, expressed in minutes.
202 public static final int parseTimeZoneOffset(final byte[] b, int ptr) {
203 final int v = parseBase10(b, ptr, null);
204 final int tzMins = v % 100;
205 final int tzHours = v / 100;
206 return tzHours * 60 + tzMins;
210 * Locate the first position after a given character.
212 * @param b
213 * buffer to scan.
214 * @param ptr
215 * position within buffer to start looking for LF at.
216 * @param chrA
217 * character to find.
218 * @return new position just after chr.
220 public static final int next(final byte[] b, int ptr, final char chrA) {
221 final int sz = b.length;
222 while (ptr < sz) {
223 if (b[ptr] == chrA)
224 return ptr + 1;
225 else
226 ptr++;
228 return ptr;
232 * Locate the first position after either the given character or LF.
233 * <p>
234 * This method stops on the first match it finds from either chrA or '\n'.
236 * @param b
237 * buffer to scan.
238 * @param ptr
239 * position within buffer to start looking for LF at.
240 * @param chrA
241 * character to find.
242 * @return new position just after the first chrA or chrB to be found.
244 public static final int nextLF(final byte[] b, int ptr, final char chrA) {
245 final int sz = b.length;
246 while (ptr < sz) {
247 final byte c = b[ptr];
248 if (c == chrA || c == '\n')
249 return ptr + 1;
250 else
251 ptr++;
253 return ptr;
257 * Locate the "author " header line data.
259 * @param b
260 * buffer to scan.
261 * @param ptr
262 * position in buffer to start the scan at. Most callers should
263 * pass 0 to ensure the scan starts from the beginning of the
264 * commit buffer and does not accidentally look at message body.
265 * @return position just after the space in "author ", so the first
266 * character of the author's name. If no author header can be
267 * located -1 is returned.
269 public static final int author(final byte[] b, int ptr) {
270 final int sz = b.length;
271 if (ptr == 0)
272 ptr += 46; // skip the "tree ..." line.
273 while (ptr < sz && b[ptr] == 'p')
274 ptr += 48; // skip this parent.
275 return match(b, ptr, author);
279 * Locate the "committer " header line data.
281 * @param b
282 * buffer to scan.
283 * @param ptr
284 * position in buffer to start the scan at. Most callers should
285 * pass 0 to ensure the scan starts from the beginning of the
286 * commit buffer and does not accidentally look at message body.
287 * @return position just after the space in "committer ", so the first
288 * character of the committer's name. If no committer header can be
289 * located -1 is returned.
291 public static final int committer(final byte[] b, int ptr) {
292 final int sz = b.length;
293 if (ptr == 0)
294 ptr += 46; // skip the "tree ..." line.
295 while (ptr < sz && b[ptr] == 'p')
296 ptr += 48; // skip this parent.
297 if (ptr < sz && b[ptr] == 'a')
298 ptr = next(b, ptr, '\n');
299 return match(b, ptr, committer);
303 * Locate the "encoding " header line.
305 * @param b
306 * buffer to scan.
307 * @param ptr
308 * position in buffer to start the scan at. Most callers should
309 * pass 0 to ensure the scan starts from the beginning of the
310 * buffer and does not accidentally look at the message body.
311 * @return position just after the space in "encoding ", so the first
312 * character of the encoding's name. If no encoding header can be
313 * located -1 is returned (and UTF-8 should be assumed).
315 public static final int encoding(final byte[] b, int ptr) {
316 final int sz = b.length;
317 while (ptr < sz) {
318 if (b[ptr] == '\n')
319 return -1;
320 if (b[ptr] == 'e')
321 break;
322 ptr = next(b, ptr, '\n');
324 return match(b, ptr, encoding);
328 * Parse the "encoding " header into a character set reference.
329 * <p>
330 * Locates the "encoding " header (if present) by first calling
331 * {@link #encoding(byte[], int)} and then returns the proper character set
332 * to apply to this buffer to evaluate its contents as character data.
333 * <p>
334 * If no encoding header is present, {@link Constants#CHARSET} is assumed.
336 * @param b
337 * buffer to scan.
338 * @return the Java character set representation. Never null.
340 public static Charset parseEncoding(final byte[] b) {
341 final int enc = encoding(b, 0);
342 if (enc < 0)
343 return Constants.CHARSET;
344 final int lf = next(b, enc, '\n');
345 return Charset.forName(decode(Constants.CHARSET, b, enc, lf - 1));
349 * Parse a name line (e.g. author, committer, tagger) into a PersonIdent.
350 * <p>
351 * When passing in a value for <code>nameB</code> callers should use the
352 * return value of {@link #author(byte[], int)} or
353 * {@link #committer(byte[], int)}, as these methods provide the proper
354 * position within the buffer.
356 * @param raw
357 * the buffer to parse character data from.
358 * @param nameB
359 * first position of the identity information. This should be the
360 * first position after the space which delimits the header field
361 * name (e.g. "author" or "committer") from the rest of the
362 * identity line.
363 * @return the parsed identity. Never null.
365 public static PersonIdent parsePersonIdent(final byte[] raw, final int nameB) {
366 final Charset cs = parseEncoding(raw);
367 final int emailB = nextLF(raw, nameB, '<');
368 final int emailE = nextLF(raw, emailB, '>');
370 final String name = decode(cs, raw, nameB, emailB - 2);
371 final String email = decode(cs, raw, emailB, emailE - 1);
373 final MutableInteger ptrout = new MutableInteger();
374 final int when = parseBase10(raw, emailE + 1, ptrout);
375 final int tz = parseTimeZoneOffset(raw, ptrout.value);
377 return new PersonIdent(name, email, when * 1000L, tz);
381 * Decode a region of the buffer under the specified character set.
383 * @param cs
384 * character set to use when decoding the buffer.
385 * @param buffer
386 * buffer to pull raw bytes from.
387 * @param start
388 * first position within the buffer to take data from.
389 * @param end
390 * one position past the last location within the buffer to take
391 * data from.
392 * @return a string representation of the range <code>[start,end)</code>,
393 * after decoding the region through the specified character set.
395 public static String decode(final Charset cs, final byte[] buffer,
396 final int start, final int end) {
397 final ByteBuffer b = ByteBuffer.wrap(buffer, start, end - start);
398 return cs.decode(b).toString();
402 * Locate the position of the commit message body.
404 * @param b
405 * buffer to scan.
406 * @param ptr
407 * position in buffer to start the scan at. Most callers should
408 * pass 0 to ensure the scan starts from the beginning of the
409 * commit buffer.
410 * @return position of the user's message buffer.
412 public static final int commitMessage(final byte[] b, int ptr) {
413 final int sz = b.length;
414 if (ptr == 0)
415 ptr += 46; // skip the "tree ..." line.
416 while (ptr < sz && b[ptr] == 'p')
417 ptr += 48; // skip this parent.
419 // skip any remaining header lines, ignoring what their actual
420 // header line type is.
422 while (ptr < sz && b[ptr] != '\n')
423 ptr = next(b, ptr, '\n');
424 if (ptr < sz && b[ptr] == '\n')
425 return ptr + 1;
426 return -1;
430 * Locate the end of a paragraph.
431 * <p>
432 * A paragraph is ended by two consecutive LF bytes.
434 * @param b
435 * buffer to scan.
436 * @param start
437 * position in buffer to start the scan at. Most callers will
438 * want to pass the first position of the commit message (as
439 * found by {@link #commitMessage(byte[], int)}.
440 * @return position of the LF at the end of the paragraph;
441 * <code>b.length</code> if no paragraph end could be located.
443 public static final int endOfParagraph(final byte[] b, final int start) {
444 int ptr = start;
445 final int sz = b.length;
446 while (ptr < sz && b[ptr] != '\n')
447 ptr = next(b, ptr, '\n');
448 while (0 < ptr && start < ptr && b[ptr - 1] == '\n')
449 ptr--;
450 return ptr;
453 private RawParseUtils() {
454 // Don't create instances of a static only utility.