FileDocCategorySizeDatePackage
NumberTools.javaAPI DocApache Lucene 2.1.04003Wed Feb 14 10:46:42 GMT 2007org.apache.lucene.document

NumberTools

public class NumberTools extends Object
Provides support for converting longs to Strings, and back again. The strings are structured so that lexicographic sorting order is preserved.

That is, if l1 is less than l2 for any two longs l1 and l2, then NumberTools.longToString(l1) is lexicographically less than NumberTools.longToString(l2). (Similarly for "greater than" and "equals".)

This class handles all long values (unlike {@link org.apache.lucene.document.DateField}).

author
Matt Quail (spud at madbean dot com)

Fields Summary
private static final int
RADIX
private static final char
NEGATIVE_PREFIX
private static final char
POSITIVE_PREFIX
public static final String
MIN_STRING_VALUE
Equivalent to longToString(Long.MIN_VALUE)
public static final String
MAX_STRING_VALUE
Equivalent to longToString(Long.MAX_VALUE)
public static final int
STR_SIZE
The length of (all) strings returned by {@link #longToString}
Constructors Summary
Methods Summary
public static java.lang.StringlongToString(long l)
Converts a long to a String suitable for indexing.


                  
         

        if (l == Long.MIN_VALUE) {
            // special case, because long is not symetric around zero
            return MIN_STRING_VALUE;
        }

        StringBuffer buf = new StringBuffer(STR_SIZE);

        if (l < 0) {
            buf.append(NEGATIVE_PREFIX);
            l = Long.MAX_VALUE + l + 1;
        } else {
            buf.append(POSITIVE_PREFIX);
        }
        String num = Long.toString(l, RADIX);

        int padLen = STR_SIZE - num.length() - buf.length();
        while (padLen-- > 0) {
            buf.append('0");
        }
        buf.append(num);

        return buf.toString();
    
public static longstringToLong(java.lang.String str)
Converts a String that was returned by {@link #longToString} back to a long.

throws
IllegalArgumentException if the input is null
throws
NumberFormatException if the input does not parse (it was not a String returned by longToString()).

        if (str == null) {
            throw new NullPointerException("string cannot be null");
        }
        if (str.length() != STR_SIZE) {
            throw new NumberFormatException("string is the wrong size");
        }

        if (str.equals(MIN_STRING_VALUE)) {
            return Long.MIN_VALUE;
        }

        char prefix = str.charAt(0);
        long l = Long.parseLong(str.substring(1), RADIX);

        if (prefix == POSITIVE_PREFIX) {
            // nop
        } else if (prefix == NEGATIVE_PREFIX) {
            l = l - Long.MAX_VALUE - 1;
        } else {
            throw new NumberFormatException(
                    "string does not begin with the correct prefix");
        }

        return l;