From a6901893ab4d5a62830207873817f48474d9e249 Mon Sep 17 00:00:00 2001 From: "Shawn O. Pearce" Date: Tue, 1 Apr 2008 23:19:44 -0400 Subject: [PATCH] Teach RawParseUtil how to format base 10 numbers it reads In some file formats we need to be able to efficiently produce a base 10 numeric in a byte[], much as how we need to parse those through RawParseUtil.parseBase10. For efficiency reasons we write backwards into the passed buffer, making it necessary for the caller to produce the output in the reverse order that it would parse the input with. Signed-off-by: Shawn O. Pearce --- .../src/org/spearce/jgit/util/RawParseUtils.java | 52 ++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/org.spearce.jgit/src/org/spearce/jgit/util/RawParseUtils.java b/org.spearce.jgit/src/org/spearce/jgit/util/RawParseUtils.java index 829d022a..0e317424 100644 --- a/org.spearce.jgit/src/org/spearce/jgit/util/RawParseUtils.java +++ b/org.spearce.jgit/src/org/spearce/jgit/util/RawParseUtils.java @@ -49,6 +49,58 @@ public final class RawParseUtils { return ptr; } + private static final byte[] base10byte = { '0', '1', '2', '3', '4', '5', + '6', '7', '8', '9' }; + + /** + * Format a base 10 numeric into a temporary buffer. + *

+ * Formatting is performed backwards. The method starts at offset + * o-1 and ends at o-1-digits, where + * digits is the number of positions necessary to store the + * base 10 value. + *

+ * The argument and return values from this method make it easy to chain + * writing, for example: + *

+ * + *
+	 * final byte[] tmp = new byte[64];
+	 * int ptr = tmp.length;
+	 * tmp[--ptr] = '\n';
+	 * ptr = RawParseUtils.formatBase10(tmp, ptr, 32);
+	 * tmp[--ptr] = ' ';
+	 * ptr = RawParseUtils.formatBase10(tmp, ptr, 18);
+	 * tmp[--ptr] = 0;
+	 * final String str = new String(tmp, ptr, tmp.length - ptr);
+	 * 
+ * + * @param b + * buffer to write into. + * @param o + * one offset past the location where writing will begin; writing + * proceeds towards lower index values. + * @param value + * the value to store. + * @return the new offset value o. This is the position of + * the last byte written. Additional writing should start at one + * position earlier. + */ + public static int formatBase10(final byte[] b, int o, int value) { + if (value == 0) { + b[--o] = '0'; + return o; + } + final boolean isneg = value < 0; + while (value != 0) { + b[--o] = base10byte[value % 10]; + value /= 10; + } + if (isneg) + b[--o] = '-'; + return o; + } + /** * Parse a base 10 numeric from a sequence of ASCII digits. *

-- 2.11.4.GIT