View Javadoc
1   /*
2    * Copyright (C) 2008-2009, Google Inc.
3    * Copyright (C) 2006-2008, Shawn O. Pearce <spearce@spearce.org>
4    * and other copyright owners as documented in the project's IP log.
5    *
6    * This program and the accompanying materials are made available
7    * under the terms of the Eclipse Distribution License v1.0 which
8    * accompanies this distribution, is reproduced below, and is
9    * available at http://www.eclipse.org/org/documents/edl-v10.php
10   *
11   * All rights reserved.
12   *
13   * Redistribution and use in source and binary forms, with or
14   * without modification, are permitted provided that the following
15   * conditions are met:
16   *
17   * - Redistributions of source code must retain the above copyright
18   *   notice, this list of conditions and the following disclaimer.
19   *
20   * - Redistributions in binary form must reproduce the above
21   *   copyright notice, this list of conditions and the following
22   *   disclaimer in the documentation and/or other materials provided
23   *   with the distribution.
24   *
25   * - Neither the name of the Eclipse Foundation, Inc. nor the
26   *   names of its contributors may be used to endorse or promote
27   *   products derived from this software without specific prior
28   *   written permission.
29   *
30   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
31   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
32   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
33   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
34   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
35   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
37   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
38   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
39   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
40   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
41   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
42   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
43   */
44  
45  package org.eclipse.jgit.util;
46  
47  import static java.nio.charset.StandardCharsets.ISO_8859_1;
48  import static java.nio.charset.StandardCharsets.UTF_8;
49  import static org.eclipse.jgit.lib.ObjectChecker.author;
50  import static org.eclipse.jgit.lib.ObjectChecker.committer;
51  import static org.eclipse.jgit.lib.ObjectChecker.encoding;
52  import static org.eclipse.jgit.lib.ObjectChecker.tagger;
53  
54  import java.nio.ByteBuffer;
55  import java.nio.charset.CharacterCodingException;
56  import java.nio.charset.Charset;
57  import java.nio.charset.CharsetDecoder;
58  import java.nio.charset.CodingErrorAction;
59  import java.nio.charset.IllegalCharsetNameException;
60  import java.nio.charset.UnsupportedCharsetException;
61  import java.util.Arrays;
62  import java.util.HashMap;
63  import java.util.Map;
64  
65  import org.eclipse.jgit.annotations.Nullable;
66  import org.eclipse.jgit.errors.BinaryBlobException;
67  import org.eclipse.jgit.lib.Constants;
68  import org.eclipse.jgit.lib.PersonIdent;
69  
70  /**
71   * Handy utility functions to parse raw object contents.
72   */
73  public final class RawParseUtils {
74  	/**
75  	 * UTF-8 charset constant.
76  	 *
77  	 * @since 2.2
78  	 */
79  	public static final Charset UTF8_CHARSET = UTF_8;
80  
81  	private static final byte[] digits10;
82  
83  	private static final byte[] digits16;
84  
85  	private static final byte[] footerLineKeyChars;
86  
87  	private static final Map<String, Charset> encodingAliases;
88  
89  	static {
90  		encodingAliases = new HashMap<>();
91  		encodingAliases.put("latin-1", ISO_8859_1); //$NON-NLS-1$
92  		encodingAliases.put("iso-latin-1", ISO_8859_1); //$NON-NLS-1$
93  
94  		digits10 = new byte['9' + 1];
95  		Arrays.fill(digits10, (byte) -1);
96  		for (char i = '0'; i <= '9'; i++)
97  			digits10[i] = (byte) (i - '0');
98  
99  		digits16 = new byte['f' + 1];
100 		Arrays.fill(digits16, (byte) -1);
101 		for (char i = '0'; i <= '9'; i++)
102 			digits16[i] = (byte) (i - '0');
103 		for (char i = 'a'; i <= 'f'; i++)
104 			digits16[i] = (byte) ((i - 'a') + 10);
105 		for (char i = 'A'; i <= 'F'; i++)
106 			digits16[i] = (byte) ((i - 'A') + 10);
107 
108 		footerLineKeyChars = new byte['z' + 1];
109 		footerLineKeyChars['-'] = 1;
110 		for (char i = '0'; i <= '9'; i++)
111 			footerLineKeyChars[i] = 1;
112 		for (char i = 'A'; i <= 'Z'; i++)
113 			footerLineKeyChars[i] = 1;
114 		for (char i = 'a'; i <= 'z'; i++)
115 			footerLineKeyChars[i] = 1;
116 	}
117 
118 	/**
119 	 * Determine if b[ptr] matches src.
120 	 *
121 	 * @param b
122 	 *            the buffer to scan.
123 	 * @param ptr
124 	 *            first position within b, this should match src[0].
125 	 * @param src
126 	 *            the buffer to test for equality with b.
127 	 * @return ptr + src.length if b[ptr..src.length] == src; else -1.
128 	 */
129 	public static final int match(byte[] b, int ptr, byte[] src) {
130 		if (ptr + src.length > b.length)
131 			return -1;
132 		for (int i = 0; i < src.length; i++, ptr++)
133 			if (b[ptr] != src[i])
134 				return -1;
135 		return ptr;
136 	}
137 
138 	private static final byte[] base10byte = { '0', '1', '2', '3', '4', '5',
139 			'6', '7', '8', '9' };
140 
141 	/**
142 	 * Format a base 10 numeric into a temporary buffer.
143 	 * <p>
144 	 * Formatting is performed backwards. The method starts at offset
145 	 * <code>o-1</code> and ends at <code>o-1-digits</code>, where
146 	 * <code>digits</code> is the number of positions necessary to store the
147 	 * base 10 value.
148 	 * <p>
149 	 * The argument and return values from this method make it easy to chain
150 	 * writing, for example:
151 	 * </p>
152 	 *
153 	 * <pre>
154 	 * final byte[] tmp = new byte[64];
155 	 * int ptr = tmp.length;
156 	 * tmp[--ptr] = '\n';
157 	 * ptr = RawParseUtils.formatBase10(tmp, ptr, 32);
158 	 * tmp[--ptr] = ' ';
159 	 * ptr = RawParseUtils.formatBase10(tmp, ptr, 18);
160 	 * tmp[--ptr] = 0;
161 	 * final String str = new String(tmp, ptr, tmp.length - ptr);
162 	 * </pre>
163 	 *
164 	 * @param b
165 	 *            buffer to write into.
166 	 * @param o
167 	 *            one offset past the location where writing will begin; writing
168 	 *            proceeds towards lower index values.
169 	 * @param value
170 	 *            the value to store.
171 	 * @return the new offset value <code>o</code>. This is the position of
172 	 *         the last byte written. Additional writing should start at one
173 	 *         position earlier.
174 	 */
175 	public static int formatBase10(final byte[] b, int o, int value) {
176 		if (value == 0) {
177 			b[--o] = '0';
178 			return o;
179 		}
180 		final boolean isneg = value < 0;
181 		if (isneg)
182 			value = -value;
183 		while (value != 0) {
184 			b[--o] = base10byte[value % 10];
185 			value /= 10;
186 		}
187 		if (isneg)
188 			b[--o] = '-';
189 		return o;
190 	}
191 
192 	/**
193 	 * Parse a base 10 numeric from a sequence of ASCII digits into an int.
194 	 * <p>
195 	 * Digit sequences can begin with an optional run of spaces before the
196 	 * sequence, and may start with a '+' or a '-' to indicate sign position.
197 	 * Any other characters will cause the method to stop and return the current
198 	 * result to the caller.
199 	 *
200 	 * @param b
201 	 *            buffer to scan.
202 	 * @param ptr
203 	 *            position within buffer to start parsing digits at.
204 	 * @param ptrResult
205 	 *            optional location to return the new ptr value through. If null
206 	 *            the ptr value will be discarded.
207 	 * @return the value at this location; 0 if the location is not a valid
208 	 *         numeric.
209 	 */
210 	public static final int parseBase10(final byte[] b, int ptr,
211 			final MutableInteger ptrResult) {
212 		int r = 0;
213 		int sign = 0;
214 		try {
215 			final int sz = b.length;
216 			while (ptr < sz && b[ptr] == ' ')
217 				ptr++;
218 			if (ptr >= sz)
219 				return 0;
220 
221 			switch (b[ptr]) {
222 			case '-':
223 				sign = -1;
224 				ptr++;
225 				break;
226 			case '+':
227 				ptr++;
228 				break;
229 			}
230 
231 			while (ptr < sz) {
232 				final byte v = digits10[b[ptr]];
233 				if (v < 0)
234 					break;
235 				r = (r * 10) + v;
236 				ptr++;
237 			}
238 		} catch (ArrayIndexOutOfBoundsException e) {
239 			// Not a valid digit.
240 		}
241 		if (ptrResult != null)
242 			ptrResult.value = ptr;
243 		return sign < 0 ? -r : r;
244 	}
245 
246 	/**
247 	 * Parse a base 10 numeric from a sequence of ASCII digits into a long.
248 	 * <p>
249 	 * Digit sequences can begin with an optional run of spaces before the
250 	 * sequence, and may start with a '+' or a '-' to indicate sign position.
251 	 * Any other characters will cause the method to stop and return the current
252 	 * result to the caller.
253 	 *
254 	 * @param b
255 	 *            buffer to scan.
256 	 * @param ptr
257 	 *            position within buffer to start parsing digits at.
258 	 * @param ptrResult
259 	 *            optional location to return the new ptr value through. If null
260 	 *            the ptr value will be discarded.
261 	 * @return the value at this location; 0 if the location is not a valid
262 	 *         numeric.
263 	 */
264 	public static final long parseLongBase10(final byte[] b, int ptr,
265 			final MutableInteger ptrResult) {
266 		long r = 0;
267 		int sign = 0;
268 		try {
269 			final int sz = b.length;
270 			while (ptr < sz && b[ptr] == ' ')
271 				ptr++;
272 			if (ptr >= sz)
273 				return 0;
274 
275 			switch (b[ptr]) {
276 			case '-':
277 				sign = -1;
278 				ptr++;
279 				break;
280 			case '+':
281 				ptr++;
282 				break;
283 			}
284 
285 			while (ptr < sz) {
286 				final byte v = digits10[b[ptr]];
287 				if (v < 0)
288 					break;
289 				r = (r * 10) + v;
290 				ptr++;
291 			}
292 		} catch (ArrayIndexOutOfBoundsException e) {
293 			// Not a valid digit.
294 		}
295 		if (ptrResult != null)
296 			ptrResult.value = ptr;
297 		return sign < 0 ? -r : r;
298 	}
299 
300 	/**
301 	 * Parse 4 character base 16 (hex) formatted string to unsigned integer.
302 	 * <p>
303 	 * The number is read in network byte order, that is, most significant
304 	 * nybble first.
305 	 *
306 	 * @param bs
307 	 *            buffer to parse digits from; positions {@code [p, p+4)} will
308 	 *            be parsed.
309 	 * @param p
310 	 *            first position within the buffer to parse.
311 	 * @return the integer value.
312 	 * @throws java.lang.ArrayIndexOutOfBoundsException
313 	 *             if the string is not hex formatted.
314 	 */
315 	public static final int parseHexInt16(final byte[] bs, final int p) {
316 		int r = digits16[bs[p]] << 4;
317 
318 		r |= digits16[bs[p + 1]];
319 		r <<= 4;
320 
321 		r |= digits16[bs[p + 2]];
322 		r <<= 4;
323 
324 		r |= digits16[bs[p + 3]];
325 		if (r < 0)
326 			throw new ArrayIndexOutOfBoundsException();
327 		return r;
328 	}
329 
330 	/**
331 	 * Parse 8 character base 16 (hex) formatted string to unsigned integer.
332 	 * <p>
333 	 * The number is read in network byte order, that is, most significant
334 	 * nybble first.
335 	 *
336 	 * @param bs
337 	 *            buffer to parse digits from; positions {@code [p, p+8)} will
338 	 *            be parsed.
339 	 * @param p
340 	 *            first position within the buffer to parse.
341 	 * @return the integer value.
342 	 * @throws java.lang.ArrayIndexOutOfBoundsException
343 	 *             if the string is not hex formatted.
344 	 */
345 	public static final int parseHexInt32(final byte[] bs, final int p) {
346 		int r = digits16[bs[p]] << 4;
347 
348 		r |= digits16[bs[p + 1]];
349 		r <<= 4;
350 
351 		r |= digits16[bs[p + 2]];
352 		r <<= 4;
353 
354 		r |= digits16[bs[p + 3]];
355 		r <<= 4;
356 
357 		r |= digits16[bs[p + 4]];
358 		r <<= 4;
359 
360 		r |= digits16[bs[p + 5]];
361 		r <<= 4;
362 
363 		r |= digits16[bs[p + 6]];
364 
365 		final int last = digits16[bs[p + 7]];
366 		if (r < 0 || last < 0)
367 			throw new ArrayIndexOutOfBoundsException();
368 		return (r << 4) | last;
369 	}
370 
371 	/**
372 	 * Parse 16 character base 16 (hex) formatted string to unsigned long.
373 	 * <p>
374 	 * The number is read in network byte order, that is, most significant
375 	 * nibble first.
376 	 *
377 	 * @param bs
378 	 *            buffer to parse digits from; positions {@code [p, p+16)} will
379 	 *            be parsed.
380 	 * @param p
381 	 *            first position within the buffer to parse.
382 	 * @return the integer value.
383 	 * @throws java.lang.ArrayIndexOutOfBoundsException
384 	 *             if the string is not hex formatted.
385 	 * @since 4.3
386 	 */
387 	public static final long parseHexInt64(final byte[] bs, final int p) {
388 		long r = digits16[bs[p]] << 4;
389 
390 		r |= digits16[bs[p + 1]];
391 		r <<= 4;
392 
393 		r |= digits16[bs[p + 2]];
394 		r <<= 4;
395 
396 		r |= digits16[bs[p + 3]];
397 		r <<= 4;
398 
399 		r |= digits16[bs[p + 4]];
400 		r <<= 4;
401 
402 		r |= digits16[bs[p + 5]];
403 		r <<= 4;
404 
405 		r |= digits16[bs[p + 6]];
406 		r <<= 4;
407 
408 		r |= digits16[bs[p + 7]];
409 		r <<= 4;
410 
411 		r |= digits16[bs[p + 8]];
412 		r <<= 4;
413 
414 		r |= digits16[bs[p + 9]];
415 		r <<= 4;
416 
417 		r |= digits16[bs[p + 10]];
418 		r <<= 4;
419 
420 		r |= digits16[bs[p + 11]];
421 		r <<= 4;
422 
423 		r |= digits16[bs[p + 12]];
424 		r <<= 4;
425 
426 		r |= digits16[bs[p + 13]];
427 		r <<= 4;
428 
429 		r |= digits16[bs[p + 14]];
430 
431 		final int last = digits16[bs[p + 15]];
432 		if (r < 0 || last < 0)
433 			throw new ArrayIndexOutOfBoundsException();
434 		return (r << 4) | last;
435 	}
436 
437 	/**
438 	 * Parse a single hex digit to its numeric value (0-15).
439 	 *
440 	 * @param digit
441 	 *            hex character to parse.
442 	 * @return numeric value, in the range 0-15.
443 	 * @throws java.lang.ArrayIndexOutOfBoundsException
444 	 *             if the input digit is not a valid hex digit.
445 	 */
446 	public static final int parseHexInt4(final byte digit) {
447 		final byte r = digits16[digit];
448 		if (r < 0)
449 			throw new ArrayIndexOutOfBoundsException();
450 		return r;
451 	}
452 
453 	/**
454 	 * Parse a Git style timezone string.
455 	 * <p>
456 	 * The sequence "-0315" will be parsed as the numeric value -195, as the
457 	 * lower two positions count minutes, not 100ths of an hour.
458 	 *
459 	 * @param b
460 	 *            buffer to scan.
461 	 * @param ptr
462 	 *            position within buffer to start parsing digits at.
463 	 * @return the timezone at this location, expressed in minutes.
464 	 */
465 	public static final int parseTimeZoneOffset(byte[] b, int ptr) {
466 		return parseTimeZoneOffset(b, ptr, null);
467 	}
468 
469 	/**
470 	 * Parse a Git style timezone string.
471 	 * <p>
472 	 * The sequence "-0315" will be parsed as the numeric value -195, as the
473 	 * lower two positions count minutes, not 100ths of an hour.
474 	 *
475 	 * @param b
476 	 *            buffer to scan.
477 	 * @param ptr
478 	 *            position within buffer to start parsing digits at.
479 	 * @param ptrResult
480 	 *            optional location to return the new ptr value through. If null
481 	 *            the ptr value will be discarded.
482 	 * @return the timezone at this location, expressed in minutes.
483 	 * @since 4.1
484 	 */
485 	public static final int parseTimeZoneOffset(final byte[] b, int ptr,
486 			MutableInteger ptrResult) {
487 		final int v = parseBase10(b, ptr, ptrResult);
488 		final int tzMins = v % 100;
489 		final int tzHours = v / 100;
490 		return tzHours * 60 + tzMins;
491 	}
492 
493 	/**
494 	 * Locate the first position after a given character.
495 	 *
496 	 * @param b
497 	 *            buffer to scan.
498 	 * @param ptr
499 	 *            position within buffer to start looking for chrA at.
500 	 * @param chrA
501 	 *            character to find.
502 	 * @return new position just after chrA.
503 	 */
504 	public static final int next(byte[] b, int ptr, char chrA) {
505 		final int sz = b.length;
506 		while (ptr < sz) {
507 			if (b[ptr++] == chrA)
508 				return ptr;
509 		}
510 		return ptr;
511 	}
512 
513 	/**
514 	 * Locate the first position after the next LF.
515 	 * <p>
516 	 * This method stops on the first '\n' it finds.
517 	 *
518 	 * @param b
519 	 *            buffer to scan.
520 	 * @param ptr
521 	 *            position within buffer to start looking for LF at.
522 	 * @return new position just after the first LF found.
523 	 */
524 	public static final int nextLF(byte[] b, int ptr) {
525 		return next(b, ptr, '\n');
526 	}
527 
528 	/**
529 	 * Locate the first position after either the given character or LF.
530 	 * <p>
531 	 * This method stops on the first match it finds from either chrA or '\n'.
532 	 *
533 	 * @param b
534 	 *            buffer to scan.
535 	 * @param ptr
536 	 *            position within buffer to start looking for chrA or LF at.
537 	 * @param chrA
538 	 *            character to find.
539 	 * @return new position just after the first chrA or LF to be found.
540 	 */
541 	public static final int nextLF(byte[] b, int ptr, char chrA) {
542 		final int sz = b.length;
543 		while (ptr < sz) {
544 			final byte c = b[ptr++];
545 			if (c == chrA || c == '\n')
546 				return ptr;
547 		}
548 		return ptr;
549 	}
550 
551 	/**
552 	 * Locate the first position before a given character.
553 	 *
554 	 * @param b
555 	 *            buffer to scan.
556 	 * @param ptr
557 	 *            position within buffer to start looking for chrA at.
558 	 * @param chrA
559 	 *            character to find.
560 	 * @return new position just before chrA, -1 for not found
561 	 */
562 	public static final int prev(byte[] b, int ptr, char chrA) {
563 		if (ptr == b.length)
564 			--ptr;
565 		while (ptr >= 0) {
566 			if (b[ptr--] == chrA)
567 				return ptr;
568 		}
569 		return ptr;
570 	}
571 
572 	/**
573 	 * Locate the first position before the previous LF.
574 	 * <p>
575 	 * This method stops on the first '\n' it finds.
576 	 *
577 	 * @param b
578 	 *            buffer to scan.
579 	 * @param ptr
580 	 *            position within buffer to start looking for LF at.
581 	 * @return new position just before the first LF found, -1 for not found
582 	 */
583 	public static final int prevLF(byte[] b, int ptr) {
584 		return prev(b, ptr, '\n');
585 	}
586 
587 	/**
588 	 * Locate the previous position before either the given character or LF.
589 	 * <p>
590 	 * This method stops on the first match it finds from either chrA or '\n'.
591 	 *
592 	 * @param b
593 	 *            buffer to scan.
594 	 * @param ptr
595 	 *            position within buffer to start looking for chrA or LF at.
596 	 * @param chrA
597 	 *            character to find.
598 	 * @return new position just before the first chrA or LF to be found, -1 for
599 	 *         not found
600 	 */
601 	public static final int prevLF(byte[] b, int ptr, char chrA) {
602 		if (ptr == b.length)
603 			--ptr;
604 		while (ptr >= 0) {
605 			final byte c = b[ptr--];
606 			if (c == chrA || c == '\n')
607 				return ptr;
608 		}
609 		return ptr;
610 	}
611 
612 	/**
613 	 * Index the region between <code>[ptr, end)</code> to find line starts.
614 	 * <p>
615 	 * The returned list is 1 indexed. Index 0 contains
616 	 * {@link java.lang.Integer#MIN_VALUE} to pad the list out.
617 	 * <p>
618 	 * Using a 1 indexed list means that line numbers can be directly accessed
619 	 * from the list, so <code>list.get(1)</code> (aka get line 1) returns
620 	 * <code>ptr</code>.
621 	 * <p>
622 	 * The last element (index <code>map.size()-1</code>) always contains
623 	 * <code>end</code>.
624 	 * <p>
625 	 * If the data contains a '\0' anywhere, the whole region is considered
626 	 * binary and a LineMap corresponding to a single line is returned.
627 	 * </p>
628 	 *
629 	 * @param buf
630 	 *            buffer to scan.
631 	 * @param ptr
632 	 *            position within the buffer corresponding to the first byte of
633 	 *            line 1.
634 	 * @param end
635 	 *            1 past the end of the content within <code>buf</code>.
636 	 * @return a line map indicating the starting position of each line, or a
637 	 *         map representing the entire buffer as a single line if
638 	 *         <code>buf</code> contains a NUL byte.
639 	 */
640 	public static final IntList lineMap(byte[] buf, int ptr, int end) {
641 		IntList map = lineMapOrNull(buf, ptr, end);
642 		if (map == null) {
643 			map = new IntList(3);
644 			map.add(Integer.MIN_VALUE);
645 			map.add(ptr);
646 			map.add(end);
647 		}
648 		return map;
649 	}
650 
651 	/**
652 	 * Like {@link #lineMap(byte[], int, int)} but throw
653 	 * {@link BinaryBlobException} if a NUL byte is encountered.
654 	 *
655 	 * @param buf
656 	 *            buffer to scan.
657 	 * @param ptr
658 	 *            position within the buffer corresponding to the first byte of
659 	 *            line 1.
660 	 * @param end
661 	 *            1 past the end of the content within <code>buf</code>.
662 	 * @return a line map indicating the starting position of each line.
663 	 * @throws BinaryBlobException
664 	 *            if a NUL byte is found.
665 	 * @since 5.0
666 	 */
667 	public static final IntList lineMapOrBinary(byte[] buf, int ptr, int end)
668 			throws BinaryBlobException {
669 		IntList map = lineMapOrNull(buf, ptr, end);
670 		if (map == null) {
671 			throw new BinaryBlobException();
672 		}
673 		return map;
674 	}
675 
676 	private static @Nullable IntList lineMapOrNull(byte[] buf, int ptr, int end) {
677 		// Experimentally derived from multiple source repositories
678 		// the average number of bytes/line is 36. Its a rough guess
679 		// to initially size our map close to the target.
680 		IntList map = new IntList((end - ptr) / 36);
681 		map.add(Integer.MIN_VALUE);
682 		boolean foundLF = true;
683 		for (; ptr < end; ptr++) {
684 			if (foundLF) {
685 				map.add(ptr);
686 			}
687 
688 			if (buf[ptr] == '\0') {
689 				return null;
690 			}
691 
692 			foundLF = (buf[ptr] == '\n');
693 		}
694 		map.add(end);
695 		return map;
696 	}
697 
698 	/**
699 	 * Locate the "author " header line data.
700 	 *
701 	 * @param b
702 	 *            buffer to scan.
703 	 * @param ptr
704 	 *            position in buffer to start the scan at. Most callers should
705 	 *            pass 0 to ensure the scan starts from the beginning of the
706 	 *            commit buffer and does not accidentally look at message body.
707 	 * @return position just after the space in "author ", so the first
708 	 *         character of the author's name. If no author header can be
709 	 *         located -1 is returned.
710 	 */
711 	public static final int author(byte[] b, int ptr) {
712 		final int sz = b.length;
713 		if (ptr == 0)
714 			ptr += 46; // skip the "tree ..." line.
715 		while (ptr < sz && b[ptr] == 'p')
716 			ptr += 48; // skip this parent.
717 		return match(b, ptr, author);
718 	}
719 
720 	/**
721 	 * Locate the "committer " header line data.
722 	 *
723 	 * @param b
724 	 *            buffer to scan.
725 	 * @param ptr
726 	 *            position in buffer to start the scan at. Most callers should
727 	 *            pass 0 to ensure the scan starts from the beginning of the
728 	 *            commit buffer and does not accidentally look at message body.
729 	 * @return position just after the space in "committer ", so the first
730 	 *         character of the committer's name. If no committer header can be
731 	 *         located -1 is returned.
732 	 */
733 	public static final int committer(byte[] b, int ptr) {
734 		final int sz = b.length;
735 		if (ptr == 0)
736 			ptr += 46; // skip the "tree ..." line.
737 		while (ptr < sz && b[ptr] == 'p')
738 			ptr += 48; // skip this parent.
739 		if (ptr < sz && b[ptr] == 'a')
740 			ptr = nextLF(b, ptr);
741 		return match(b, ptr, committer);
742 	}
743 
744 	/**
745 	 * Locate the "tagger " header line data.
746 	 *
747 	 * @param b
748 	 *            buffer to scan.
749 	 * @param ptr
750 	 *            position in buffer to start the scan at. Most callers should
751 	 *            pass 0 to ensure the scan starts from the beginning of the tag
752 	 *            buffer and does not accidentally look at message body.
753 	 * @return position just after the space in "tagger ", so the first
754 	 *         character of the tagger's name. If no tagger header can be
755 	 *         located -1 is returned.
756 	 */
757 	public static final int tagger(byte[] b, int ptr) {
758 		final int sz = b.length;
759 		if (ptr == 0)
760 			ptr += 48; // skip the "object ..." line.
761 		while (ptr < sz) {
762 			if (b[ptr] == '\n')
763 				return -1;
764 			final int m = match(b, ptr, tagger);
765 			if (m >= 0)
766 				return m;
767 			ptr = nextLF(b, ptr);
768 		}
769 		return -1;
770 	}
771 
772 	/**
773 	 * Locate the "encoding " header line.
774 	 *
775 	 * @param b
776 	 *            buffer to scan.
777 	 * @param ptr
778 	 *            position in buffer to start the scan at. Most callers should
779 	 *            pass 0 to ensure the scan starts from the beginning of the
780 	 *            buffer and does not accidentally look at the message body.
781 	 * @return position just after the space in "encoding ", so the first
782 	 *         character of the encoding's name. If no encoding header can be
783 	 *         located -1 is returned (and UTF-8 should be assumed).
784 	 */
785 	public static final int encoding(byte[] b, int ptr) {
786 		final int sz = b.length;
787 		while (ptr < sz) {
788 			if (b[ptr] == '\n')
789 				return -1;
790 			if (b[ptr] == 'e')
791 				break;
792 			ptr = nextLF(b, ptr);
793 		}
794 		return match(b, ptr, encoding);
795 	}
796 
797 	/**
798 	 * Parse the "encoding " header as a string.
799 	 * <p>
800 	 * Locates the "encoding " header (if present) and returns its value.
801 	 *
802 	 * @param b
803 	 *            buffer to scan.
804 	 * @return the encoding header as specified in the commit; null if the
805 	 *         header was not present and should be assumed.
806 	 * @since 4.2
807 	 */
808 	@Nullable
809 	public static String parseEncodingName(byte[] b) {
810 		int enc = encoding(b, 0);
811 		if (enc < 0) {
812 			return null;
813 		}
814 		int lf = nextLF(b, enc);
815 		return decode(UTF_8, b, enc, lf - 1);
816 	}
817 
818 	/**
819 	 * Parse the "encoding " header into a character set reference.
820 	 * <p>
821 	 * Locates the "encoding " header (if present) by first calling
822 	 * {@link #encoding(byte[], int)} and then returns the proper character set
823 	 * to apply to this buffer to evaluate its contents as character data.
824 	 * <p>
825 	 * If no encoding header is present {@code UTF-8} is assumed.
826 	 *
827 	 * @param b
828 	 *            buffer to scan.
829 	 * @return the Java character set representation. Never null.
830 	 * @throws IllegalCharsetNameException
831 	 *             if the character set requested by the encoding header is
832 	 *             malformed and unsupportable.
833 	 * @throws UnsupportedCharsetException
834 	 *             if the JRE does not support the character set requested by
835 	 *             the encoding header.
836 	 */
837 	public static Charset parseEncoding(byte[] b) {
838 		String enc = parseEncodingName(b);
839 		if (enc == null) {
840 			return UTF_8;
841 		}
842 
843 		String name = enc.trim();
844 		try {
845 			return Charset.forName(name);
846 		} catch (IllegalCharsetNameException
847 				| UnsupportedCharsetException badName) {
848 			Charset aliased = charsetForAlias(name);
849 			if (aliased != null) {
850 				return aliased;
851 			}
852 			throw badName;
853 		}
854 	}
855 
856 	/**
857 	 * Parse a name string (e.g. author, committer, tagger) into a PersonIdent.
858 	 * <p>
859 	 * Leading spaces won't be trimmed from the string, i.e. will show up in the
860 	 * parsed name afterwards.
861 	 *
862 	 * @param in
863 	 *            the string to parse a name from.
864 	 * @return the parsed identity or null in case the identity could not be
865 	 *         parsed.
866 	 */
867 	public static PersonIdent parsePersonIdent(String in) {
868 		return parsePersonIdent(Constants.encode(in), 0);
869 	}
870 
871 	/**
872 	 * Parse a name line (e.g. author, committer, tagger) into a PersonIdent.
873 	 * <p>
874 	 * When passing in a value for <code>nameB</code> callers should use the
875 	 * return value of {@link #author(byte[], int)} or
876 	 * {@link #committer(byte[], int)}, as these methods provide the proper
877 	 * position within the buffer.
878 	 *
879 	 * @param raw
880 	 *            the buffer to parse character data from.
881 	 * @param nameB
882 	 *            first position of the identity information. This should be the
883 	 *            first position after the space which delimits the header field
884 	 *            name (e.g. "author" or "committer") from the rest of the
885 	 *            identity line.
886 	 * @return the parsed identity or null in case the identity could not be
887 	 *         parsed.
888 	 */
889 	public static PersonIdent parsePersonIdent(byte[] raw, int nameB) {
890 		Charset cs;
891 		try {
892 			cs = parseEncoding(raw);
893 		} catch (IllegalCharsetNameException | UnsupportedCharsetException e) {
894 			// Assume UTF-8 for person identities, usually this is correct.
895 			// If not decode() will fall back to the ISO-8859-1 encoding.
896 			cs = UTF_8;
897 		}
898 
899 		final int emailB = nextLF(raw, nameB, '<');
900 		final int emailE = nextLF(raw, emailB, '>');
901 		if (emailB >= raw.length || raw[emailB] == '\n' ||
902 				(emailE >= raw.length - 1 && raw[emailE - 1] != '>'))
903 			return null;
904 
905 		final int nameEnd = emailB - 2 >= nameB && raw[emailB - 2] == ' ' ?
906 				emailB - 2 : emailB - 1;
907 		final String name = decode(cs, raw, nameB, nameEnd);
908 		final String email = decode(cs, raw, emailB, emailE - 1);
909 
910 		// Start searching from end of line, as after first name-email pair,
911 		// another name-email pair may occur. We will ignore all kinds of
912 		// "junk" following the first email.
913 		//
914 		// We've to use (emailE - 1) for the case that raw[email] is LF,
915 		// otherwise we would run too far. "-2" is necessary to position
916 		// before the LF in case of LF termination resp. the penultimate
917 		// character if there is no trailing LF.
918 		final int tzBegin = lastIndexOfTrim(raw, ' ',
919 				nextLF(raw, emailE - 1) - 2) + 1;
920 		if (tzBegin <= emailE) // No time/zone, still valid
921 			return new PersonIdent(name, email, 0, 0);
922 
923 		final int whenBegin = Math.max(emailE,
924 				lastIndexOfTrim(raw, ' ', tzBegin - 1) + 1);
925 		if (whenBegin >= tzBegin - 1) // No time/zone, still valid
926 			return new PersonIdent(name, email, 0, 0);
927 
928 		final long when = parseLongBase10(raw, whenBegin, null);
929 		final int tz = parseTimeZoneOffset(raw, tzBegin);
930 		return new PersonIdent(name, email, when * 1000L, tz);
931 	}
932 
933 	/**
934 	 * Parse a name data (e.g. as within a reflog) into a PersonIdent.
935 	 * <p>
936 	 * When passing in a value for <code>nameB</code> callers should use the
937 	 * return value of {@link #author(byte[], int)} or
938 	 * {@link #committer(byte[], int)}, as these methods provide the proper
939 	 * position within the buffer.
940 	 *
941 	 * @param raw
942 	 *            the buffer to parse character data from.
943 	 * @param nameB
944 	 *            first position of the identity information. This should be the
945 	 *            first position after the space which delimits the header field
946 	 *            name (e.g. "author" or "committer") from the rest of the
947 	 *            identity line.
948 	 * @return the parsed identity. Never null.
949 	 */
950 	public static PersonIdent parsePersonIdentOnly(final byte[] raw,
951 			final int nameB) {
952 		int stop = nextLF(raw, nameB);
953 		int emailB = nextLF(raw, nameB, '<');
954 		int emailE = nextLF(raw, emailB, '>');
955 		final String name;
956 		final String email;
957 		if (emailE < stop) {
958 			email = decode(raw, emailB, emailE - 1);
959 		} else {
960 			email = "invalid"; //$NON-NLS-1$
961 		}
962 		if (emailB < stop)
963 			name = decode(raw, nameB, emailB - 2);
964 		else
965 			name = decode(raw, nameB, stop);
966 
967 		final MutableInteger ptrout = new MutableInteger();
968 		long when;
969 		int tz;
970 		if (emailE < stop) {
971 			when = parseLongBase10(raw, emailE + 1, ptrout);
972 			tz = parseTimeZoneOffset(raw, ptrout.value);
973 		} else {
974 			when = 0;
975 			tz = 0;
976 		}
977 		return new PersonIdent(name, email, when * 1000L, tz);
978 	}
979 
980 	/**
981 	 * Locate the end of a footer line key string.
982 	 * <p>
983 	 * If the region at {@code raw[ptr]} matches {@code ^[A-Za-z0-9-]+:} (e.g.
984 	 * "Signed-off-by: A. U. Thor\n") then this method returns the position of
985 	 * the first ':'.
986 	 * <p>
987 	 * If the region at {@code raw[ptr]} does not match {@code ^[A-Za-z0-9-]+:}
988 	 * then this method returns -1.
989 	 *
990 	 * @param raw
991 	 *            buffer to scan.
992 	 * @param ptr
993 	 *            first position within raw to consider as a footer line key.
994 	 * @return position of the ':' which terminates the footer line key if this
995 	 *         is otherwise a valid footer line key; otherwise -1.
996 	 */
997 	public static int endOfFooterLineKey(byte[] raw, int ptr) {
998 		try {
999 			for (;;) {
1000 				final byte c = raw[ptr];
1001 				if (footerLineKeyChars[c] == 0) {
1002 					if (c == ':')
1003 						return ptr;
1004 					return -1;
1005 				}
1006 				ptr++;
1007 			}
1008 		} catch (ArrayIndexOutOfBoundsException e) {
1009 			return -1;
1010 		}
1011 	}
1012 
1013 	/**
1014 	 * Decode a buffer under UTF-8, if possible.
1015 	 *
1016 	 * If the byte stream cannot be decoded that way, the platform default is tried
1017 	 * and if that too fails, the fail-safe ISO-8859-1 encoding is tried.
1018 	 *
1019 	 * @param buffer
1020 	 *            buffer to pull raw bytes from.
1021 	 * @return a string representation of the range <code>[start,end)</code>,
1022 	 *         after decoding the region through the specified character set.
1023 	 */
1024 	public static String decode(byte[] buffer) {
1025 		return decode(buffer, 0, buffer.length);
1026 	}
1027 
1028 	/**
1029 	 * Decode a buffer under UTF-8, if possible.
1030 	 *
1031 	 * If the byte stream cannot be decoded that way, the platform default is
1032 	 * tried and if that too fails, the fail-safe ISO-8859-1 encoding is tried.
1033 	 *
1034 	 * @param buffer
1035 	 *            buffer to pull raw bytes from.
1036 	 * @param start
1037 	 *            start position in buffer
1038 	 * @param end
1039 	 *            one position past the last location within the buffer to take
1040 	 *            data from.
1041 	 * @return a string representation of the range <code>[start,end)</code>,
1042 	 *         after decoding the region through the specified character set.
1043 	 */
1044 	public static String decode(final byte[] buffer, final int start,
1045 			final int end) {
1046 		return decode(UTF_8, buffer, start, end);
1047 	}
1048 
1049 	/**
1050 	 * Decode a buffer under the specified character set if possible.
1051 	 *
1052 	 * If the byte stream cannot be decoded that way, the platform default is tried
1053 	 * and if that too fails, the fail-safe ISO-8859-1 encoding is tried.
1054 	 *
1055 	 * @param cs
1056 	 *            character set to use when decoding the buffer.
1057 	 * @param buffer
1058 	 *            buffer to pull raw bytes from.
1059 	 * @return a string representation of the range <code>[start,end)</code>,
1060 	 *         after decoding the region through the specified character set.
1061 	 */
1062 	public static String decode(Charset cs, byte[] buffer) {
1063 		return decode(cs, buffer, 0, buffer.length);
1064 	}
1065 
1066 	/**
1067 	 * Decode a region of the buffer under the specified character set if possible.
1068 	 *
1069 	 * If the byte stream cannot be decoded that way, the platform default is tried
1070 	 * and if that too fails, the fail-safe ISO-8859-1 encoding is tried.
1071 	 *
1072 	 * @param cs
1073 	 *            character set to use when decoding the buffer.
1074 	 * @param buffer
1075 	 *            buffer to pull raw bytes from.
1076 	 * @param start
1077 	 *            first position within the buffer to take data from.
1078 	 * @param end
1079 	 *            one position past the last location within the buffer to take
1080 	 *            data from.
1081 	 * @return a string representation of the range <code>[start,end)</code>,
1082 	 *         after decoding the region through the specified character set.
1083 	 */
1084 	public static String decode(final Charset cs, final byte[] buffer,
1085 			final int start, final int end) {
1086 		try {
1087 			return decodeNoFallback(cs, buffer, start, end);
1088 		} catch (CharacterCodingException e) {
1089 			// Fall back to an ISO-8859-1 style encoding. At least all of
1090 			// the bytes will be present in the output.
1091 			//
1092 			return extractBinaryString(buffer, start, end);
1093 		}
1094 	}
1095 
1096 	/**
1097 	 * Decode a region of the buffer under the specified character set if
1098 	 * possible.
1099 	 *
1100 	 * If the byte stream cannot be decoded that way, the platform default is
1101 	 * tried and if that too fails, an exception is thrown.
1102 	 *
1103 	 * @param cs
1104 	 *            character set to use when decoding the buffer.
1105 	 * @param buffer
1106 	 *            buffer to pull raw bytes from.
1107 	 * @param start
1108 	 *            first position within the buffer to take data from.
1109 	 * @param end
1110 	 *            one position past the last location within the buffer to take
1111 	 *            data from.
1112 	 * @return a string representation of the range <code>[start,end)</code>,
1113 	 *         after decoding the region through the specified character set.
1114 	 * @throws java.nio.charset.CharacterCodingException
1115 	 *             the input is not in any of the tested character sets.
1116 	 */
1117 	public static String decodeNoFallback(final Charset cs,
1118 			final byte[] buffer, final int start, final int end)
1119 			throws CharacterCodingException {
1120 		ByteBuffer b = ByteBuffer.wrap(buffer, start, end - start);
1121 		b.mark();
1122 
1123 		// Try our built-in favorite. The assumption here is that
1124 		// decoding will fail if the data is not actually encoded
1125 		// using that encoder.
1126 		try {
1127 			return decode(b, UTF_8);
1128 		} catch (CharacterCodingException e) {
1129 			b.reset();
1130 		}
1131 
1132 		if (!cs.equals(UTF_8)) {
1133 			// Try the suggested encoding, it might be right since it was
1134 			// provided by the caller.
1135 			try {
1136 				return decode(b, cs);
1137 			} catch (CharacterCodingException e) {
1138 				b.reset();
1139 			}
1140 		}
1141 
1142 		// Try the default character set. A small group of people
1143 		// might actually use the same (or very similar) locale.
1144 		Charset defcs = Charset.defaultCharset();
1145 		if (!defcs.equals(cs) && !defcs.equals(UTF_8)) {
1146 			try {
1147 				return decode(b, defcs);
1148 			} catch (CharacterCodingException e) {
1149 				b.reset();
1150 			}
1151 		}
1152 
1153 		throw new CharacterCodingException();
1154 	}
1155 
1156 	/**
1157 	 * Decode a region of the buffer under the ISO-8859-1 encoding.
1158 	 *
1159 	 * Each byte is treated as a single character in the 8859-1 character
1160 	 * encoding, performing a raw binary-&gt;char conversion.
1161 	 *
1162 	 * @param buffer
1163 	 *            buffer to pull raw bytes from.
1164 	 * @param start
1165 	 *            first position within the buffer to take data from.
1166 	 * @param end
1167 	 *            one position past the last location within the buffer to take
1168 	 *            data from.
1169 	 * @return a string representation of the range <code>[start,end)</code>.
1170 	 */
1171 	public static String extractBinaryString(final byte[] buffer,
1172 			final int start, final int end) {
1173 		final StringBuilder r = new StringBuilder(end - start);
1174 		for (int i = start; i < end; i++)
1175 			r.append((char) (buffer[i] & 0xff));
1176 		return r.toString();
1177 	}
1178 
1179 	private static String decode(ByteBuffer b, Charset charset)
1180 			throws CharacterCodingException {
1181 		final CharsetDecoder d = charset.newDecoder();
1182 		d.onMalformedInput(CodingErrorAction.REPORT);
1183 		d.onUnmappableCharacter(CodingErrorAction.REPORT);
1184 		return d.decode(b).toString();
1185 	}
1186 
1187 	/**
1188 	 * Locate the position of the commit message body.
1189 	 *
1190 	 * @param b
1191 	 *            buffer to scan.
1192 	 * @param ptr
1193 	 *            position in buffer to start the scan at. Most callers should
1194 	 *            pass 0 to ensure the scan starts from the beginning of the
1195 	 *            commit buffer.
1196 	 * @return position of the user's message buffer.
1197 	 */
1198 	public static final int commitMessage(byte[] b, int ptr) {
1199 		final int sz = b.length;
1200 		if (ptr == 0)
1201 			ptr += 46; // skip the "tree ..." line.
1202 		while (ptr < sz && b[ptr] == 'p')
1203 			ptr += 48; // skip this parent.
1204 
1205 		// Skip any remaining header lines, ignoring what their actual
1206 		// header line type is. This is identical to the logic for a tag.
1207 		//
1208 		return tagMessage(b, ptr);
1209 	}
1210 
1211 	/**
1212 	 * Locate the position of the tag message body.
1213 	 *
1214 	 * @param b
1215 	 *            buffer to scan.
1216 	 * @param ptr
1217 	 *            position in buffer to start the scan at. Most callers should
1218 	 *            pass 0 to ensure the scan starts from the beginning of the tag
1219 	 *            buffer.
1220 	 * @return position of the user's message buffer.
1221 	 */
1222 	public static final int tagMessage(byte[] b, int ptr) {
1223 		final int sz = b.length;
1224 		if (ptr == 0)
1225 			ptr += 48; // skip the "object ..." line.
1226 		while (ptr < sz && b[ptr] != '\n')
1227 			ptr = nextLF(b, ptr);
1228 		if (ptr < sz && b[ptr] == '\n')
1229 			return ptr + 1;
1230 		return -1;
1231 	}
1232 
1233 	/**
1234 	 * Locate the end of a paragraph.
1235 	 * <p>
1236 	 * A paragraph is ended by two consecutive LF bytes or CRLF pairs
1237 	 *
1238 	 * @param b
1239 	 *            buffer to scan.
1240 	 * @param start
1241 	 *            position in buffer to start the scan at. Most callers will
1242 	 *            want to pass the first position of the commit message (as
1243 	 *            found by {@link #commitMessage(byte[], int)}.
1244 	 * @return position of the LF at the end of the paragraph;
1245 	 *         <code>b.length</code> if no paragraph end could be located.
1246 	 */
1247 	public static final int endOfParagraph(byte[] b, int start) {
1248 		int ptr = start;
1249 		final int sz = b.length;
1250 		while (ptr < sz && (b[ptr] != '\n' && b[ptr] != '\r'))
1251 			ptr = nextLF(b, ptr);
1252 		if (ptr > start && b[ptr - 1] == '\n')
1253 			ptr--;
1254 		if (ptr > start && b[ptr - 1] == '\r')
1255 			ptr--;
1256 		return ptr;
1257 	}
1258 
1259 	/**
1260 	 * Get last index of {@code ch} in raw, trimming spaces.
1261 	 *
1262 	 * @param raw
1263 	 *            buffer to scan.
1264 	 * @param ch
1265 	 *            character to find.
1266 	 * @param pos
1267 	 *            starting position.
1268 	 * @return last index of {@code ch} in raw, trimming spaces.
1269 	 * @since 4.1
1270 	 */
1271 	public static int lastIndexOfTrim(byte[] raw, char ch, int pos) {
1272 		while (pos >= 0 && raw[pos] == ' ')
1273 			pos--;
1274 
1275 		while (pos >= 0 && raw[pos] != ch)
1276 			pos--;
1277 
1278 		return pos;
1279 	}
1280 
1281 	private static Charset charsetForAlias(String name) {
1282 		return encodingAliases.get(StringUtils.toLowerCase(name));
1283 	}
1284 
1285 	private RawParseUtils() {
1286 		// Don't create instances of a static only utility.
1287 	}
1288 }