You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RawParseUtils.java 37KB

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