Java Code Examples for com.google.common.primitives.Ints#saturatedCast()

The following examples show how to use com.google.common.primitives.Ints#saturatedCast() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ImmutableRangeSet.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
int indexOf(Object target) {
  if (contains(target)) {
    @SuppressWarnings("unchecked") // if it's contained, it's definitely a C
    C c = (C) target;
    long total = 0;
    for (Range<C> range : ranges) {
      if (range.contains(c)) {
        return Ints.saturatedCast(total + ContiguousSet.create(range, domain).indexOf(c));
      } else {
        total += ContiguousSet.create(range, domain).size();
      }
    }
    throw new AssertionError("impossible");
  }
  return -1;
}
 
Example 2
Source File: BeatsFrameDecoder.java    From graylog-plugin-beats with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @see <a href="https://github.com/logstash-plugins/logstash-input-beats/blob/master/PROTOCOL.md#data-frame-type">'data' frame type</a>
 */
private Collection<ByteBuf> parseDataFrame(Channel channel, ByteBuf channelBuffer) throws IOException {
    sequenceNum = channelBuffer.readUnsignedInt();
    LOG.trace("Received sequence number {}", sequenceNum);

    final int pairs = Ints.saturatedCast(channelBuffer.readUnsignedInt());
    final JsonFactory jsonFactory = new JsonFactory();
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try (final JsonGenerator jg = jsonFactory.createGenerator(outputStream)) {
        jg.writeStartObject();
        for (int i = 0; i < pairs; i++) {
            final String key = parseDataItem(channelBuffer);
            final String value = parseDataItem(channelBuffer);
            jg.writeStringField(key, value);
        }
        jg.writeEndObject();
    }

    final ByteBuf buffer = Unpooled.wrappedBuffer(outputStream.toByteArray());
    sendACK(channel);

    return Collections.singleton(buffer);
}
 
Example 3
Source File: ImmutableRangeSet.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public int size() {
  // racy single-check idiom
  Integer result = size;
  if (result == null) {
    long total = 0;
    for (Range<C> range : ranges) {
      total += ContiguousSet.create(range, domain).size();
      if (total >= Integer.MAX_VALUE) {
        break;
      }
    }
    result = size = Ints.saturatedCast(total);
  }
  return result.intValue();
}
 
Example 4
Source File: Iterators.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Returns the number of elements remaining in {@code iterator}. The iterator
 * will be left exhausted: its {@code hasNext()} method will return
 * {@code false}.
 */


public static int size(Iterator<?> iterator) {
  long count = 0L;
  while (iterator.hasNext()) {
    iterator.next();
    count++;
  }
  return Ints.saturatedCast(count);
}
 
Example 5
Source File: Lists.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@VisibleForTesting
static int computeArrayListCapacity(int arraySize) {
  checkNonnegative(arraySize, "arraySize");

  // TODO(kevinb): Figure out the right behavior, and document it
  return Ints.saturatedCast(5L + arraySize + (arraySize / 10));
}
 
Example 6
Source File: Lists.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@VisibleForTesting
static int computeArrayListCapacity(int arraySize) {
  checkNonnegative(arraySize, "arraySize");

  // TODO(kevinb): Figure out the right behavior, and document it
  return Ints.saturatedCast(5L + arraySize + (arraySize / 10));
}
 
Example 7
Source File: Multisets.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * An implementation of {@link Multiset#size}.
 */

static int sizeImpl(Multiset<?> multiset) {
  long size = 0;
  for (Entry<?> entry : multiset.entrySet()) {
    size += entry.getCount();
  }
  return Ints.saturatedCast(size);
}
 
Example 8
Source File: SchemaUpgrade.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private void rewriteHeartbeatTablePart2() throws Exception {
    if (!tableExists("heartbeat_temp")) {
        // previously failed mid-upgrade prior to updating schema version
        return;
    }
    logger.info("rewriting heartbeat table (part 2)...");
    Map<String, V09AgentRollup> v09AgentRollups = getV09AgentRollupsFromAgentRollupTable();
    dropTableIfExists("heartbeat");
    session.createTableWithTWCS("create table if not exists heartbeat (agent_id varchar,"
            + " central_capture_time timestamp, primary key (agent_id, central_capture_time))",
            HeartbeatDao.EXPIRATION_HOURS);
    PreparedStatement insertPS = session.prepare("insert into heartbeat (agent_id,"
            + " central_capture_time) values (?, ?) using ttl ?");
    int ttl = Ints.saturatedCast(HOURS.toSeconds(HeartbeatDao.EXPIRATION_HOURS));
    ResultSet results =
            session.read("select agent_id, central_capture_time from heartbeat_temp");
    Queue<ListenableFuture<?>> futures = new ArrayDeque<>();
    for (Row row : results) {
        String v09AgentRollupId = row.getString(0);
        V09AgentRollup v09AgentRollup = v09AgentRollups.get(v09AgentRollupId);
        if (v09AgentRollup == null) {
            // v09AgentRollupId was manually deleted (via the UI) from the agent_rollup
            // table in which case its parent is no longer known and best to ignore
            continue;
        }
        Date centralCaptureDate = checkNotNull(row.getTimestamp(1));
        int adjustedTTL = Common.getAdjustedTTL(ttl, centralCaptureDate.getTime(), clock);
        BoundStatement boundStatement = insertPS.bind();
        int i = 0;
        boundStatement.setString(i++, v09AgentRollup.agentRollupId());
        boundStatement.setTimestamp(i++, centralCaptureDate);
        boundStatement.setInt(i++, adjustedTTL);
        futures.add(session.writeAsync(boundStatement));
        waitForSome(futures);
    }
    MoreFutures.waitForAll(futures);
    dropTableIfExists("heartbeat_temp");
    logger.info("rewriting heartbeat table (part 2) - complete");
}
 
Example 9
Source File: Task.java    From litemall with MIT License 4 votes vote down vote up
@Override
public int compareTo(Delayed o) {
    return Ints.saturatedCast(this.start - ((Task) o).start);
}
 
Example 10
Source File: ManagedStoragePlugin.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
int getMaxMetadataColumns() {
  return Ints.saturatedCast(options.getOption(CatalogOptions.METADATA_LEAF_COLUMN_MAX));
}
 
Example 11
Source File: LocalCache.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public int size() {
  return Ints.saturatedCast(longSize());
}
 
Example 12
Source File: Subscription.java    From ua-server-sdk with GNU Affero General Public License v3.0 4 votes vote down vote up
private void setMaxNotificationsPerPublish(long maxNotificationsPerPublish) {
    if (maxNotificationsPerPublish <= 0 || maxNotificationsPerPublish > MAX_NOTIFICATIONS) {
        maxNotificationsPerPublish = MAX_NOTIFICATIONS;
    }
    this.maxNotificationsPerPublish = Ints.saturatedCast(maxNotificationsPerPublish);
}
 
Example 13
Source File: AbstractMapBasedMultiset.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public int size() {
  return Ints.saturatedCast(size);
}
 
Example 14
Source File: UaTcpClientAcknowledgeHandler.java    From opc-ua-stack with Apache License 2.0 4 votes vote down vote up
private void onAcknowledge(ChannelHandlerContext ctx, ByteBuf buffer) {
    if (helloTimeout != null && !helloTimeout.cancel()) {
        helloTimeout = null;
        handshakeFuture.completeExceptionally(
                new UaException(StatusCodes.Bad_Timeout,
                        "timed out waiting for acknowledge"));
        ctx.close();
        return;
    }

    logger.debug("Received Acknowledge message on channel={}.", ctx.channel());

    buffer.skipBytes(3 + 1 + 4); // Skip messageType, chunkType, and messageSize

    AcknowledgeMessage acknowledge = AcknowledgeMessage.decode(buffer);

    long remoteProtocolVersion = acknowledge.getProtocolVersion();
    long remoteReceiveBufferSize = acknowledge.getReceiveBufferSize();
    long remoteSendBufferSize = acknowledge.getSendBufferSize();
    long remoteMaxMessageSize = acknowledge.getMaxMessageSize();
    long remoteMaxChunkCount = acknowledge.getMaxChunkCount();

    if (PROTOCOL_VERSION > remoteProtocolVersion) {
        logger.warn("Client protocol version ({}) does not match server protocol version ({}).",
                PROTOCOL_VERSION, remoteProtocolVersion);
    }

    ChannelConfig config = client.getChannelConfig();

    /* Our receive buffer size is determined by the remote send buffer size. */
    long localReceiveBufferSize = Math.min(remoteSendBufferSize, config.getMaxChunkSize());

    /* Our send buffer size is determined by the remote receive buffer size. */
    long localSendBufferSize = Math.min(remoteReceiveBufferSize, config.getMaxChunkSize());

    /* Max message size the remote can send us; not influenced by remote configuration. */
    long localMaxMessageSize = config.getMaxMessageSize();

    /* Max chunk count the remote can send us; not influenced by remote configuration. */
    long localMaxChunkCount = config.getMaxChunkCount();

    ChannelParameters parameters = new ChannelParameters(
            Ints.saturatedCast(localMaxMessageSize),
            Ints.saturatedCast(localReceiveBufferSize),
            Ints.saturatedCast(localSendBufferSize),
            Ints.saturatedCast(localMaxChunkCount),
            Ints.saturatedCast(remoteMaxMessageSize),
            Ints.saturatedCast(remoteReceiveBufferSize),
            Ints.saturatedCast(remoteSendBufferSize),
            Ints.saturatedCast(remoteMaxChunkCount)
    );

    ctx.channel().attr(KEY_AWAITING_HANDSHAKE).set(awaitingHandshake);

    ctx.executor().execute(() -> {
        int maxArrayLength = client.getChannelConfig().getMaxArrayLength();
        int maxStringLength = client.getChannelConfig().getMaxStringLength();

        SerializationQueue serializationQueue = new SerializationQueue(
                client.getConfig().getExecutor(),
                parameters,
                maxArrayLength,
                maxStringLength
        );

        UaTcpClientMessageHandler handler = new UaTcpClientMessageHandler(
                client,
                secureChannel,
                serializationQueue,
                handshakeFuture
        );

        ctx.pipeline().addLast(handler);
    });
}
 
Example 15
Source File: ArmeriaChannel.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
public <I, O> ClientCall<I, O> newCall(
        MethodDescriptor<I, O> method, CallOptions callOptions) {
    final HttpRequestWriter req = HttpRequest.streaming(
            RequestHeaders.of(HttpMethod.POST, uri().getPath() + method.getFullMethodName(),
                              HttpHeaderNames.CONTENT_TYPE, serializationFormat.mediaType(),
                              HttpHeaderNames.TE, HttpHeaderValues.TRAILERS));
    final DefaultClientRequestContext ctx = newContext(HttpMethod.POST, req);

    final String fullMethodName = method.getFullMethodName();
    final int methodIndex = fullMethodName.lastIndexOf('/') + 1;
    ctx.logBuilder().name(method.getServiceName(), fullMethodName.substring(methodIndex));
    ctx.logBuilder().serializationFormat(serializationFormat);
    ctx.logBuilder().defer(RequestLogProperty.REQUEST_CONTENT,
                           RequestLogProperty.RESPONSE_CONTENT);

    final ClientOptions options = options();
    final int maxOutboundMessageSizeBytes = options.get(GrpcClientOptions.MAX_OUTBOUND_MESSAGE_SIZE_BYTES);
    final int maxInboundMessageSizeBytes = options.get(GrpcClientOptions.MAX_INBOUND_MESSAGE_SIZE_BYTES);
    final boolean unsafeWrapResponseBuffers = options.get(GrpcClientOptions.UNSAFE_WRAP_RESPONSE_BUFFERS);

    final PooledHttpClient client;

    final CallCredentials credentials = callOptions.getCredentials();
    if (credentials != null) {
        client = new CallCredentialsDecoratingClient(httpClient, credentials, method, authority());
    } else {
        client = httpClient;
    }

    return new ArmeriaClientCall<>(
            ctx,
            params.endpointGroup(),
            client,
            req,
            method,
            maxOutboundMessageSizeBytes,
            maxInboundMessageSizeBytes > 0 ? maxInboundMessageSizeBytes
                                           : Ints.saturatedCast(options.maxResponseLength()),
            callOptions,
            CompressorRegistry.getDefaultInstance(),
            DecompressorRegistry.getDefaultInstance(),
            serializationFormat,
            jsonMarshaller,
            unsafeWrapResponseBuffers,
            advertisedEncodingsHeader);
}
 
Example 16
Source File: IntMath.java    From codebuff with BSD 2-Clause "Simplified" License 2 votes vote down vote up
/**
 * Returns the product of {@code a} and {@code b} unless it would overflow or underflow in which
 * case {@code Integer.MAX_VALUE} or {@code Integer.MIN_VALUE} is returned, respectively.
 *
 * @since 20.0
 */

@Beta
public static int saturatedMultiply(int a, int b) {
  return Ints.saturatedCast((long) a * b);
}
 
Example 17
Source File: IntMath.java    From codebuff with BSD 2-Clause "Simplified" License 2 votes vote down vote up
/**
 * Returns the difference of {@code a} and {@code b} unless it would overflow or underflow in
 * which case {@code Integer.MAX_VALUE} or {@code Integer.MIN_VALUE} is returned, respectively.
 *
 * @since 20.0
 */
@Beta
public static int saturatedSubtract(int a, int b) {
  return Ints.saturatedCast((long) a - b);
}
 
Example 18
Source File: IntMath.java    From codebuff with BSD 2-Clause "Simplified" License 2 votes vote down vote up
/**
 * Returns the product of {@code a} and {@code b} unless it would overflow or underflow in which
 * case {@code Integer.MAX_VALUE} or {@code Integer.MIN_VALUE} is returned, respectively.
 *
 * @since 20.0
 */

@Beta
public static int saturatedMultiply(int a, int b) {
  return Ints.saturatedCast((long) a * b);
}
 
Example 19
Source File: IntMath.java    From codebuff with BSD 2-Clause "Simplified" License 2 votes vote down vote up
/**
 * Returns the difference of {@code a} and {@code b} unless it would overflow or underflow in
 * which case {@code Integer.MAX_VALUE} or {@code Integer.MIN_VALUE} is returned, respectively.
 *
 * @since 20.0
 */

@Beta
public static int saturatedSubtract(int a, int b) {
  return Ints.saturatedCast((long) a - b);
}
 
Example 20
Source File: IntMath.java    From codebuff with BSD 2-Clause "Simplified" License 2 votes vote down vote up
/**
 * Returns the sum of {@code a} and {@code b} unless it would overflow or underflow in which case
 * {@code Integer.MAX_VALUE} or {@code Integer.MIN_VALUE} is returned, respectively.
 *
 * @since 20.0
 */

@Beta
public static int saturatedAdd(int a, int b) {
  return Ints.saturatedCast((long) a + b);
}