下面列出了怎么用com.google.common.primitives.Shorts的API类实例代码及写法,或者点击链接到github查看源代码。
@Subscribe
public void onGrandExchangeSearched(GrandExchangeSearched event)
{
final String input = client.getVar(VarClientStr.INPUT_TEXT);
if (!input.startsWith(TAG_SEARCH))
{
return;
}
event.consume();
final String tag = input.substring(TAG_SEARCH.length()).trim();
final Set<Integer> ids = tagManager.getItemsForTag(tag)
.stream()
.mapToInt(Math::abs)
.mapToObj(ItemVariationMapping::getVariations)
.flatMap(Collection::stream)
.distinct()
.filter(i -> itemManager.getItemDefinition(i).isTradeable())
.limit(MAX_RESULT_COUNT)
.collect(Collectors.toCollection(TreeSet::new));
client.setGeSearchResultIndex(0);
client.setGeSearchResultCount(ids.size());
client.setGeSearchResultIds(Shorts.toArray(ids));
}
public static Long currentTokenAsSmallint(JsonParser parser)
throws IOException
{
switch (parser.currentToken()) {
case VALUE_NULL:
return null;
case VALUE_STRING:
case FIELD_NAME:
return VarcharOperators.castToSmallint(Slices.utf8Slice(parser.getText()));
case VALUE_NUMBER_FLOAT:
return DoubleOperators.castToSmallint(parser.getDoubleValue());
case VALUE_NUMBER_INT:
return (long) Shorts.checkedCast(parser.getLongValue());
case VALUE_TRUE:
return BooleanOperators.castToSmallint(true);
case VALUE_FALSE:
return BooleanOperators.castToSmallint(false);
default:
throw new JsonCastException(format("Unexpected token when cast to %s: %s", StandardTypes.SMALLINT, parser.getText()));
}
}
@UsedByGeneratedCode
public static long shortDecimalToSmallint(long decimal, long precision, long scale, long tenToScale)
{
// this rounds the decimal value to the nearest integral value
long longResult = (decimal + tenToScale / 2) / tenToScale;
if (decimal < 0) {
longResult = -((-decimal + tenToScale / 2) / tenToScale);
}
try {
return Shorts.checkedCast(longResult);
}
catch (IllegalArgumentException e) {
throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast '%s' to SMALLINT", longResult));
}
}
private static long normalizeIntegerValue(Type type, long value)
{
if (type.equals(BIGINT)) {
return value;
}
if (type.equals(INTEGER)) {
return Ints.saturatedCast(value);
}
if (type.equals(SMALLINT)) {
return Shorts.saturatedCast(value);
}
if (type.equals(TINYINT)) {
return SignedBytes.saturatedCast(value);
}
throw new IllegalArgumentException("Unexpected type: " + type);
}
protected byte[] encodeValue(byte[] key, byte[] valueB) {
byte[] compressed = null;
if (config.isEnableCompression() && (valueB.length + Ints.BYTES + key.length > compressThreshold)) {
try {
compressed = CompressionUtils.compress(ByteBuffer.allocate(Ints.BYTES + key.length + valueB.length)
.putInt(key.length).put(key).put(valueB).array());
} catch (IOException e) {
compressed = null;
logger.warn("Compressing value bytes error.", e);
}
}
if (compressed != null) {
return ByteBuffer.allocate(Shorts.BYTES + compressed.length).putShort((short) 1).put(compressed).array();
} else {
return ByteBuffer.allocate(Shorts.BYTES + Ints.BYTES + key.length + valueB.length).putShort((short) 0)
.putInt(key.length).put(key).put(valueB).array();
}
}
@SuppressWarnings({"unchecked", "rawtypes"}) // NOTE: We assume the component type matches the list
private Object toArray(Class<?> componentType, List<Object> values) {
if (componentType == boolean.class) {
return Booleans.toArray((Collection) values);
} else if (componentType == byte.class) {
return Bytes.toArray((Collection) values);
} else if (componentType == short.class) {
return Shorts.toArray((Collection) values);
} else if (componentType == int.class) {
return Ints.toArray((Collection) values);
} else if (componentType == long.class) {
return Longs.toArray((Collection) values);
} else if (componentType == float.class) {
return Floats.toArray((Collection) values);
} else if (componentType == double.class) {
return Doubles.toArray((Collection) values);
} else if (componentType == char.class) {
return Chars.toArray((Collection) values);
}
return values.toArray((Object[]) Array.newInstance(componentType, values.size()));
}
public static CacheDirectiveInfo convert
(CacheDirectiveInfoProto proto) {
CacheDirectiveInfo.Builder builder =
new CacheDirectiveInfo.Builder();
if (proto.hasId()) {
builder.setId(proto.getId());
}
if (proto.hasPath()) {
builder.setPath(new Path(proto.getPath()));
}
if (proto.hasReplication()) {
builder.setReplication(Shorts.checkedCast(
proto.getReplication()));
}
if (proto.hasPool()) {
builder.setPool(proto.getPool());
}
if (proto.hasExpiration()) {
builder.setExpiration(convert(proto.getExpiration()));
}
return builder.build();
}
@Implementation
protected int read(short[] audioData, int offsetInShorts, int sizeInShorts) {
synchronized (audioDataLock) {
if (ShadowAudioRecord.audioData.size() > 0) {
System.arraycopy(
Shorts.toArray(
ShadowAudioRecord.audioData.subList(
0,
sizeInShorts > ShadowAudioRecord.audioData.size()
? ShadowAudioRecord.audioData.size()
: sizeInShorts)),
0,
audioData,
offsetInShorts,
sizeInShorts);
if (ShadowAudioRecord.audioData.size() > 10) {
ShadowAudioRecord.audioData =
ShadowAudioRecord.audioData.subList(sizeInShorts, ShadowAudioRecord.audioData.size());
} else {
ShadowAudioRecord.audioData.clear();
}
return sizeInShorts;
}
return 0;
}
}
public static CacheDirectiveInfo convert
(CacheDirectiveInfoProto proto) {
CacheDirectiveInfo.Builder builder =
new CacheDirectiveInfo.Builder();
if (proto.hasId()) {
builder.setId(proto.getId());
}
if (proto.hasPath()) {
builder.setPath(new Path(proto.getPath()));
}
if (proto.hasReplication()) {
builder.setReplication(Shorts.checkedCast(
proto.getReplication()));
}
if (proto.hasPool()) {
builder.setPool(proto.getPool());
}
if (proto.hasExpiration()) {
builder.setExpiration(convert(proto.getExpiration()));
}
return builder.build();
}
@Subscribe
public void onGrandExchangeSearched(GrandExchangeSearched event)
{
final String input = client.getVar(VarClientStr.INPUT_TEXT);
if (!input.startsWith(TAG_SEARCH))
{
return;
}
event.consume();
final String tag = input.substring(TAG_SEARCH.length()).trim();
final Set<Integer> ids = tagManager.getItemsForTag(tag)
.stream()
.mapToInt(Math::abs)
.mapToObj(ItemVariationMapping::getVariations)
.flatMap(Collection::stream)
.distinct()
.filter(i -> itemManager.getItemComposition(i).isTradeable())
.limit(MAX_RESULT_COUNT)
.collect(Collectors.toCollection(TreeSet::new));
client.setGeSearchResultIndex(0);
client.setGeSearchResultCount(ids.size());
client.setGeSearchResultIds(Shorts.toArray(ids));
}
@ExpectWarning(value="RV_CHECK_COMPARETO_FOR_SPECIFIC_RETURN_VALUE", num = 9)
public static int testGuavaPrimitiveCompareCalls() {
int count = 0;
if (Booleans.compare(false, true) == -1)
count++;
if (Chars.compare('a', 'b') == -1)
count++;
if (Doubles.compare(1, 2) == -1)
count++;
if (Floats.compare(1, 2) == -1)
count++;
if (Ints.compare(1, 2) == -1)
count++;
if (Longs.compare(1, 2) == -1)
count++;
if (Shorts.compare((short) 1, (short) 2) == -1)
count++;
if (SignedBytes.compare((byte) 1, (byte) 2) == -1)
count++;
if (UnsignedBytes.compare((byte) 1, (byte) 2) == -1)
count++;
return count;
}
public AmplitudeData(byte[] rawData) {
if (rawData == null) {
amplitude = 0;
return;
}
int step = rawData.length / Shorts.BYTES / sampleCount;
int count = 0;
double sum = 0;
for (int i = 0;
i < rawData.length - Shorts.BYTES;
i += step) {
byte[] bytes = new byte[Shorts.BYTES];
for (int j = 0;
j < Shorts.BYTES;
j++) {
bytes[j] = rawData[i + j];
}
short s = Shorts.fromByteArray(bytes);
sum += s * s;
count++;
}
amplitude = (int) Math.sqrt(sum / count);
}
@UsedByGeneratedCode
public static long longDecimalToSmallint(Slice decimal, long precision, long scale, BigInteger tenToScale)
{
try {
return Shorts.checkedCast(unscaledDecimalToUnscaledLong(rescale(decimal, DecimalConversions.intScale(-scale))));
}
catch (ArithmeticException | IllegalArgumentException e) {
throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast '%s' to SMALLINT", Decimals.toString(decimal, DecimalConversions.intScale(scale))));
}
}
public void mergeWith(SetDigest other)
{
hll.mergeWith(other.hll);
LongBidirectionalIterator iterator = other.minhash.keySet().iterator();
while (iterator.hasNext()) {
long key = iterator.nextLong();
int count = minhash.get(key) + other.minhash.get(key);
minhash.put(key, Shorts.saturatedCast(count));
}
while (minhash.size() > maxHashes) {
minhash.remove(minhash.lastLongKey());
}
}
@ScalarOperator(CAST)
@SqlType(StandardTypes.SMALLINT)
public static long castToSmallint(@SqlType(StandardTypes.BIGINT) long value)
{
try {
return Shorts.checkedCast(value);
}
catch (IllegalArgumentException e) {
throw new PrestoException(NUMERIC_VALUE_OUT_OF_RANGE, "Out of range for smallint: " + value, e);
}
}
public void encode(final @Nonnull ByteBuffer byteBuffer, @Nonnull final Dhcp6Option option) {
short tag = option.getTag();
byte[] data = option.getData();
byteBuffer.putShort(tag);
byteBuffer.putShort(Shorts.checkedCast(data.length));
byteBuffer.put(data);
}
@ScalarOperator(MULTIPLY)
@SqlType(StandardTypes.SMALLINT)
public static long multiply(@SqlType(StandardTypes.SMALLINT) long left, @SqlType(StandardTypes.SMALLINT) long right)
{
try {
return Shorts.checkedCast(left * right);
}
catch (IllegalArgumentException e) {
throw new PrestoException(NUMERIC_VALUE_OUT_OF_RANGE, format("smallint multiplication overflow: %s * %s", left, right), e);
}
}
@ScalarOperator(NEGATION)
@SqlType(StandardTypes.SMALLINT)
public static long negate(@SqlType(StandardTypes.SMALLINT) long value)
{
try {
return Shorts.checkedCast(-value);
}
catch (IllegalArgumentException e) {
throw new PrestoException(NUMERIC_VALUE_OUT_OF_RANGE, "smallint negation overflow: " + value, e);
}
}
@ScalarOperator(CAST)
@SqlType(StandardTypes.SMALLINT)
public static long castToSmallint(@SqlType(StandardTypes.REAL) long value)
{
float floatValue = intBitsToFloat((int) value);
if (Float.isNaN(floatValue)) {
throw new PrestoException(INVALID_CAST_ARGUMENT, "Cannot cast real NaN to smallint");
}
try {
return Shorts.checkedCast((long) MathFunctions.round((double) floatValue));
}
catch (IllegalArgumentException e) {
throw new PrestoException(NUMERIC_VALUE_OUT_OF_RANGE, "Out of range for smallint: " + floatValue, e);
}
}
@ScalarOperator(CAST)
@SqlType(StandardTypes.SMALLINT)
public static long castToSmallint(@SqlType(StandardTypes.INTEGER) long value)
{
try {
return Shorts.checkedCast(value);
}
catch (IllegalArgumentException e) {
throw new PrestoException(NUMERIC_VALUE_OUT_OF_RANGE, "Out of range for smallint: " + value, e);
}
}
@ScalarOperator(CAST)
@SqlType(StandardTypes.SMALLINT)
public static long castToSmallint(@SqlType(StandardTypes.DOUBLE) double value)
{
if (Double.isNaN(value)) {
throw new PrestoException(INVALID_CAST_ARGUMENT, "Cannot cast double NaN to smallint");
}
try {
return Shorts.checkedCast((long) MathFunctions.round(value));
}
catch (IllegalArgumentException e) {
throw new PrestoException(NUMERIC_VALUE_OUT_OF_RANGE, "Out of range for smallint: " + value, e);
}
}
@Inject
public HdfsEnvironment(
HdfsConfiguration hdfsConfiguration,
HdfsConfig config,
HdfsAuthentication hdfsAuthentication)
{
this.hdfsConfiguration = requireNonNull(hdfsConfiguration, "hdfsConfiguration is null");
requireNonNull(config, "config is null");
this.newDirectoryPermissions = FsPermission.createImmutable(Shorts.checkedCast(parseUnsignedInt(config.getNewDirectoryPermissions(), 8)));
this.verifyChecksum = config.isVerifyChecksum();
this.hdfsAuthentication = requireNonNull(hdfsAuthentication, "hdfsAuthentication is null");
}
public void encode(final @Nonnull ByteBuffer byteBuffer, @Nonnull final Dhcp6Option option) {
short tag = option.getTag();
byte[] data = option.getData();
byteBuffer.putShort(tag);
byteBuffer.putShort(Shorts.checkedCast(data.length));
byteBuffer.put(data);
}
private static Short intToShort(Integer input)
{
if (input == null) {
return null;
}
return Shorts.checkedCast(input);
}
protected static int getValueSplit(MemcachedCacheConfig config, String keyS, int valueBLen) {
// the number 6 means the chunk number size never exceeds 6 bytes
final int valueSize = config.getMaxObjectSize() - Shorts.BYTES - Ints.BYTES
- keyS.getBytes(Charsets.UTF_8).length - 6;
final int maxValueSize = config.getMaxChunkSize() * valueSize;
Preconditions.checkArgument(valueBLen <= maxValueSize,
"the value bytes length [%d] exceeds maximum value size [%d]", valueBLen, maxValueSize);
return (valueBLen - 1) / valueSize + 1;
}
private void commit(PartitionGroup group) throws Exception {
if(logger.isDebugEnabled())logger.debug("topic[{}] add partitionGroup[{}]",group.getTopic(),group.getGroup());
//if (!storeService.partitionGroupExists(group.getTopic(),group.getGroup())) {
storeService.createPartitionGroup(group.getTopic().getFullName(), group.getGroup(), Shorts.toArray(group.getPartitions()));
//}
Set<Integer> replicas = group.getReplicas();
List<Broker> list = new ArrayList<>(replicas.size());
replicas.forEach(brokerId->{
list.add(clusterManager.getBrokerById(brokerId));
});
electionService.onPartitionGroupCreate(group.getElectType(),group.getTopic(),group.getGroup(),list,group.getLearners(),clusterManager.getBrokerId(),group.getLeader());
}
protected void onAddPartitionGroup(TopicName topicName, PartitionGroup partitionGroup) throws Exception {
logger.info("onAddPartitionGroup, topic: {}, partitionGroup: {}", topicName, partitionGroup);
Set<Integer> replicas = partitionGroup.getReplicas();
List<Broker> brokers = new ArrayList<>(replicas.size());
replicas.forEach(brokerId -> {
brokers.add(clusterManager.getBrokerById(brokerId));
});
storeService.createPartitionGroup(topicName.getFullName(), partitionGroup.getGroup(), Shorts.toArray(partitionGroup.getPartitions()));
electionService.onPartitionGroupCreate(partitionGroup.getElectType(), partitionGroup.getTopic(), partitionGroup.getGroup(),
brokers, partitionGroup.getLearners(), clusterManager.getBrokerId(), partitionGroup.getLeader());
}
public Map<Short, List<Short>> getMapShortList()
{
if (mapShortArray == null) {
return null;
}
return Maps.transformValues(mapShortArray, Shorts::asList);
}
@Override
public void onOptionsChanged() {
RockType.CLAY.setShow(showClay);
RockType.COPPER.setShow(showCopper);
RockType.TIN.setShow(showTin);
RockType.IRON.setShow(showIron);
RockType.SILVER.setShow(showSilver);
RockType.COAL.setShow(showCoal);
RockType.GOLD.setShow(showGold);
RockType.MITHRIL.setShow(showMithril);
RockType.ADAMANTITE.setShow(showAdamntite);
RockType.RUNITE.setShow(showRunite);
List<Short> colors = new ArrayList<>();
for (RockType r : RockType.values()) {
if (r.isShow()) {
colors.addAll(Shorts.asList(r.getColors()));
}
}
filter = acceptable -> acceptable.getComposite() != null &&
Arrays.asList(acceptable.getComposite().getOriginalModelColors())
.stream().anyMatch(shorts -> {
if (shorts == null) {
return false;
}
for (short color : shorts) {
if (colors.contains(color)) {
return true;
}
}
return false;
});
}
@Override
public final short getShort()
{
byte[] value = new byte[2];
get(value, 0, value.length);
return Shorts.fromByteArray(value);
}