sk.uniq.protobuf.schema.ProtoInteger Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of protobuf-parser Show documentation
Show all versions of protobuf-parser Show documentation
Java parser for Protocol Buffers
The newest version!
/*
* Copyright 2016 Jakub Herkel.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sk.uniq.protobuf.schema;
import java.math.BigInteger;
import sk.uniq.protobuf.schema.ProtoConstant.Type;
/**
*
* @author jherkel
*/
public class ProtoInteger extends ProtoConstant {
public ProtoInteger(long value) {
this(value, Formatter.DECIMAL,null);
}
public ProtoInteger(long value, Formatter formatter,String sourceText) {
super(value, formatter,sourceText);
}
@Override
public Type getType() {
return Type.INTEGER;
}
public static ProtoInteger parse(String text) {
return parse(text, false);
}
public static ProtoInteger parse(String text, boolean minusFlag) {
if (text.isEmpty()) {
throw new IllegalArgumentException("Invalid input, empty text");
}
if (text.charAt(0) == '0') {
// try to parse octal or hexadecimal number
if (text.length() == 1) {
return new ProtoInteger(0, Formatter.OCTAL,text);
}
if (text.charAt(1) == 'x' || text.charAt(1) == 'X') {
// hexadecimal character
if (text.length() < 3 || Character.digit(text.charAt(2), 16) == -1) {
throw new IllegalArgumentException("Invalid hexadecimal value " + text);
}
BigInteger bi = new BigInteger(text.substring(2), 16);
return new ProtoInteger(minusFlag == true ? -bi.longValue() : bi.longValue(), Formatter.HEXADECIMAL,text);
} else {
// octal number
BigInteger bi = new BigInteger(text.substring(1), 8);
return new ProtoInteger(minusFlag == true ? -bi.longValue() : bi.longValue(), Formatter.OCTAL,text);
}
} else if (Character.isDigit(text.charAt(0)) == true) {
BigInteger bi = new BigInteger(text);
return new ProtoInteger(minusFlag == true ? -bi.longValue() : bi.longValue(), Formatter.DECIMAL,text);
} else {
throw new IllegalArgumentException("Invalid integer value " + text);
}
}
public enum Formatter implements ConstantFormatter {
DECIMAL {
@Override
public String toString(Long value) {
return Long.toString(value);
}
},
HEXADECIMAL {
@Override
public String toString(Long value) {
return Long.toHexString(value);
}
},
OCTAL {
@Override
public String toString(Long value) {
return Long.toOctalString(value);
}
};
}
}