file_id
int64 1
215k
| content
stringlengths 7
454k
| repo
stringlengths 6
113
| path
stringlengths 6
251
|
---|---|---|---|
2,675 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.action;
import org.apache.lucene.util.Accountable;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.cluster.metadata.IndexAbstraction;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.cluster.routing.IndexRouting;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.lucene.uid.Versions;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.VersionType;
import org.elasticsearch.index.shard.ShardId;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import static org.elasticsearch.action.ValidateActions.addValidationError;
import static org.elasticsearch.action.index.IndexRequest.MAX_DOCUMENT_ID_LENGTH_IN_BYTES;
import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_PRIMARY_TERM;
import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO;
/**
* Generic interface to group ActionRequest, which perform writes to a single document
* Action requests implementing this can be part of {@link org.elasticsearch.action.bulk.BulkRequest}
*/
public interface DocWriteRequest<T> extends IndicesRequest, Accountable {
// Flag set for disallowing index auto creation for an individual write request.
String REQUIRE_ALIAS = "require_alias";
// Flag set for disallowing index auto creation if no matching data-stream index template is available.
String REQUIRE_DATA_STREAM = "require_data_stream";
// Flag indicating that the list of executed pipelines should be returned in the request
String LIST_EXECUTED_PIPELINES = "list_executed_pipelines";
/**
* Set the index for this request
* @return the Request
*/
T index(String index);
/**
* Get the index that this request operates on
* @return the index
*/
String index();
/**
* Get the id of the document for this request
* @return the id
*/
String id();
/**
* Get the options for this request
* @return the indices options
*/
@Override
IndicesOptions indicesOptions();
/**
* Set the routing for this request
* @return the Request
*/
T routing(String routing);
/**
* Get the routing for this request
* @return the Routing
*/
String routing();
/**
* Get the document version for this request
* @return the document version
*/
long version();
/**
* Sets the version, which will perform the operation only if a matching
* version exists and no changes happened on the doc since then.
*/
T version(long version);
/**
* Get the document version type for this request
* @return the document version type
*/
VersionType versionType();
/**
* Sets the versioning type. Defaults to {@link VersionType#INTERNAL}.
*/
T versionType(VersionType versionType);
/**
* only perform this request if the document was last modification was assigned the given
* sequence number. Must be used in combination with {@link #setIfPrimaryTerm(long)}
*
* If the document last modification was assigned a different sequence number a
* {@link org.elasticsearch.index.engine.VersionConflictEngineException} will be thrown.
*/
T setIfSeqNo(long seqNo);
/**
* only performs this request if the document was last modification was assigned the given
* primary term. Must be used in combination with {@link #setIfSeqNo(long)}
*
* If the document last modification was assigned a different term a
* {@link org.elasticsearch.index.engine.VersionConflictEngineException} will be thrown.
*/
T setIfPrimaryTerm(long term);
/**
* If set, only perform this request if the document was last modification was assigned this sequence number.
* If the document last modification was assigned a different sequence number a
* {@link org.elasticsearch.index.engine.VersionConflictEngineException} will be thrown.
*/
long ifSeqNo();
/**
* If set, only perform this request if the document was last modification was assigned this primary term.
*
* If the document last modification was assigned a different term a
* {@link org.elasticsearch.index.engine.VersionConflictEngineException} will be thrown.
*/
long ifPrimaryTerm();
/**
* Get the requested document operation type of the request
* @return the operation type {@link OpType}
*/
OpType opType();
/**
* Should this request override specifically require the destination to be an alias?
* @return boolean flag, when true specifically requires an alias
*/
boolean isRequireAlias();
/**
* Should this request override specifically require the destination to be a data stream?
* @return boolean flag, when true specifically requires a data stream
*/
boolean isRequireDataStream();
/**
* Finalize the request before executing or routing it.
*/
void process(IndexRouting indexRouting);
/**
* Pick the appropriate shard id to receive this request.
*/
int route(IndexRouting indexRouting);
/**
* Resolves the write index that should receive this request
* based on the provided index abstraction.
*
* @param ia The provided index abstraction
* @param metadata The metadata instance used to resolve the write index.
* @return the write index that should receive this request
*/
default Index getConcreteWriteIndex(IndexAbstraction ia, Metadata metadata) {
return ia.getWriteIndex();
}
/**
* Requested operation type to perform on the document
*/
enum OpType {
/**
* Index the source. If there is an existing document with the id, it will
* be replaced.
*/
INDEX(0),
/**
* Creates the resource. Simply adds it to the index, if there is an existing
* document with the id, then it won't be removed.
*/
CREATE(1),
/** Updates a document */
UPDATE(2),
/** Deletes a document */
DELETE(3);
private final byte op;
private final String lowercase;
OpType(int op) {
this.op = (byte) op;
this.lowercase = this.toString().toLowerCase(Locale.ROOT);
}
public byte getId() {
return op;
}
public String getLowercase() {
return lowercase;
}
public static OpType fromId(byte id) {
return switch (id) {
case 0 -> INDEX;
case 1 -> CREATE;
case 2 -> UPDATE;
case 3 -> DELETE;
default -> throw new IllegalArgumentException("Unknown opType: [" + id + "]");
};
}
public static OpType fromString(String sOpType) {
String lowerCase = sOpType.toLowerCase(Locale.ROOT);
for (OpType opType : OpType.values()) {
if (opType.getLowercase().equals(lowerCase)) {
return opType;
}
}
throw new IllegalArgumentException("Unknown opType: [" + sOpType + "]");
}
}
/**
* Read a document write (index/delete/update) request
*
* @param shardId shard id of the request. {@code null} when reading as part of a {@link org.elasticsearch.action.bulk.BulkRequest}
* that does not have a unique shard id.
*/
static DocWriteRequest<?> readDocumentRequest(@Nullable ShardId shardId, StreamInput in) throws IOException {
byte type = in.readByte();
DocWriteRequest<?> docWriteRequest;
if (type == 0) {
docWriteRequest = new IndexRequest(shardId, in);
} else if (type == 1) {
docWriteRequest = new DeleteRequest(shardId, in);
} else if (type == 2) {
docWriteRequest = new UpdateRequest(shardId, in);
} else {
throw new IllegalStateException("invalid request type [" + type + " ]");
}
return docWriteRequest;
}
/** write a document write (index/delete/update) request*/
static void writeDocumentRequest(StreamOutput out, DocWriteRequest<?> request) throws IOException {
if (request instanceof IndexRequest) {
out.writeByte((byte) 0);
((IndexRequest) request).writeTo(out);
} else if (request instanceof DeleteRequest) {
out.writeByte((byte) 1);
((DeleteRequest) request).writeTo(out);
} else if (request instanceof UpdateRequest) {
out.writeByte((byte) 2);
((UpdateRequest) request).writeTo(out);
} else {
throw new IllegalStateException("invalid request [" + request.getClass().getSimpleName() + " ]");
}
}
/** write a document write (index/delete/update) request without shard id*/
static void writeDocumentRequestThin(StreamOutput out, DocWriteRequest<?> request) throws IOException {
if (request instanceof IndexRequest) {
out.writeByte((byte) 0);
((IndexRequest) request).writeThin(out);
} else if (request instanceof DeleteRequest) {
out.writeByte((byte) 1);
((DeleteRequest) request).writeThin(out);
} else if (request instanceof UpdateRequest) {
out.writeByte((byte) 2);
((UpdateRequest) request).writeThin(out);
} else {
throw new IllegalStateException("invalid request [" + request.getClass().getSimpleName() + " ]");
}
}
static ActionRequestValidationException validateSeqNoBasedCASParams(
DocWriteRequest<?> request,
ActionRequestValidationException validationException
) {
final long version = request.version();
final VersionType versionType = request.versionType();
if (versionType.validateVersionForWrites(version) == false) {
validationException = addValidationError(
"illegal version value [" + version + "] for version type [" + versionType.name() + "]",
validationException
);
}
if (versionType == VersionType.INTERNAL && version != Versions.MATCH_ANY && version != Versions.MATCH_DELETED) {
validationException = addValidationError(
"internal versioning can not be used for optimistic concurrency control. "
+ "Please use `if_seq_no` and `if_primary_term` instead",
validationException
);
}
if (request.ifSeqNo() != UNASSIGNED_SEQ_NO && (versionType != VersionType.INTERNAL || version != Versions.MATCH_ANY)) {
validationException = addValidationError("compare and write operations can not use versioning", validationException);
}
if (request.ifPrimaryTerm() == UNASSIGNED_PRIMARY_TERM && request.ifSeqNo() != UNASSIGNED_SEQ_NO) {
validationException = addValidationError("ifSeqNo is set, but primary term is [0]", validationException);
}
if (request.ifPrimaryTerm() != UNASSIGNED_PRIMARY_TERM && request.ifSeqNo() == UNASSIGNED_SEQ_NO) {
validationException = addValidationError(
"ifSeqNo is unassigned, but primary term is [" + request.ifPrimaryTerm() + "]",
validationException
);
}
return validationException;
}
static ActionRequestValidationException validateDocIdLength(String id, ActionRequestValidationException validationException) {
if (id != null && id.getBytes(StandardCharsets.UTF_8).length > MAX_DOCUMENT_ID_LENGTH_IN_BYTES) {
validationException = addValidationError(
"id ["
+ id
+ "] is too long, must be no longer than "
+ MAX_DOCUMENT_ID_LENGTH_IN_BYTES
+ " bytes but was: "
+ id.getBytes(StandardCharsets.UTF_8).length,
validationException
);
}
return validationException;
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/action/DocWriteRequest.java |
2,676 | /*
* Copyright (C) 2006 Google Inc.
*
* 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 org.elasticsearch.common.inject;
import java.util.List;
/**
* Builds the graphs of objects that make up your application. The injector tracks the dependencies
* for each type and uses bindings to inject them. This is the core of Guice, although you rarely
* interact with it directly. This "behind-the-scenes" operation is what distinguishes dependency
* injection from its cousin, the service locator pattern.
* <p>
* Contains several default bindings:
* <ul>
* <li>This {@link Injector} instance itself
* <li>A {@code Provider<T>} for each binding of type {@code T}
* <li>The {@link java.util.logging.Logger} for the class being injected
* </ul>
* <p>
* Injectors are created using the facade class {@link Guice}.
*
* @author [email protected] (Bob Lee)
* @author [email protected] (Jesse Wilson)
*/
public interface Injector {
/**
* Returns all explicit bindings for {@code type}.
* <p>
* This method is part of the Guice SPI and is intended for use by tools and extensions.
*/
<T> List<Binding<T>> findBindingsByType(TypeLiteral<T> type);
/**
* Returns the provider used to obtain instances for the given injection key. When feasible, avoid
* using this method, in favor of having Guice inject your dependencies ahead of time.
*
* @throws ConfigurationException if this injector cannot find or create the provider.
* @see Binder#getProvider(Key) for an alternative that offers up front error detection
*/
<T> Provider<T> getProvider(Key<T> key);
/**
* Returns the appropriate instance for the given injection key; equivalent to {@code
* getProvider(key).get()}. When feasible, avoid using this method, in favor of having Guice
* inject your dependencies ahead of time.
*
* @throws ConfigurationException if this injector cannot find or create the provider.
* @throws ProvisionException if there was a runtime failure while providing an instance.
*/
<T> T getInstance(Key<T> key);
/**
* Returns the appropriate instance for the given injection type; equivalent to {@code
* getProvider(type).get()}. When feasible, avoid using this method, in favor of having Guice
* inject your dependencies ahead of time.
*
* @throws ConfigurationException if this injector cannot find or create the provider.
* @throws ProvisionException if there was a runtime failure while providing an instance.
*/
<T> T getInstance(Class<T> type);
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/common/inject/Injector.java |
2,678 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.common.time;
import org.elasticsearch.core.Nullable;
import java.time.temporal.TemporalAccessor;
/**
* The result of the parse. If successful, {@code result} will be non-null.
* If parse failed, {@code errorIndex} specifies the index into the parsed string
* that the first invalid data was encountered.
*/
record ParseResult(@Nullable TemporalAccessor result, int errorIndex) {
ParseResult(TemporalAccessor result) {
this(result, -1);
}
static ParseResult error(int errorIndex) {
return new ParseResult(null, errorIndex);
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/common/time/ParseResult.java |
2,679 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.search;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.lucene.Lucene;
import org.elasticsearch.common.xcontent.XContentParserUtils;
import org.elasticsearch.search.SearchHit.Fields;
import org.elasticsearch.xcontent.ToXContentFragment;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xcontent.XContentParser;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
public class SearchSortValues implements ToXContentFragment, Writeable {
private static final Object[] EMPTY_ARRAY = new Object[0];
static final SearchSortValues EMPTY = new SearchSortValues(EMPTY_ARRAY);
private final Object[] formattedSortValues;
private final Object[] rawSortValues;
SearchSortValues(Object[] sortValues) {
this(Objects.requireNonNull(sortValues, "sort values must not be empty"), EMPTY_ARRAY);
}
public SearchSortValues(Object[] rawSortValues, DocValueFormat[] sortValueFormats) {
Objects.requireNonNull(rawSortValues);
Objects.requireNonNull(sortValueFormats);
if (rawSortValues.length != sortValueFormats.length) {
throw new IllegalArgumentException("formattedSortValues and sortValueFormats must hold the same number of items");
}
this.rawSortValues = rawSortValues;
this.formattedSortValues = new Object[rawSortValues.length];
for (int i = 0; i < rawSortValues.length; ++i) {
final Object v = sortValueFormats[i].formatSortValue(rawSortValues[i]);
assert v == null || v instanceof String || v instanceof Number || v instanceof Boolean || v instanceof Map
: v + " was not formatted";
formattedSortValues[i] = v;
}
}
public static SearchSortValues readFrom(StreamInput in) throws IOException {
Object[] formattedSortValues = in.readArray(Lucene::readSortValue, Object[]::new);
Object[] rawSortValues = in.readArray(Lucene::readSortValue, Object[]::new);
if (formattedSortValues.length == 0 && rawSortValues.length == 0) {
return EMPTY;
}
return new SearchSortValues(formattedSortValues, rawSortValues);
}
private SearchSortValues(Object[] formattedSortValues, Object[] rawSortValues) {
this.formattedSortValues = formattedSortValues;
this.rawSortValues = rawSortValues;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeArray(Lucene::writeSortValue, this.formattedSortValues);
out.writeArray(Lucene::writeSortValue, this.rawSortValues);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
if (formattedSortValues.length > 0) {
builder.startArray(Fields.SORT);
for (Object sortValue : formattedSortValues) {
builder.value(sortValue);
}
builder.endArray();
}
return builder;
}
public static SearchSortValues fromXContent(XContentParser parser) throws IOException {
XContentParserUtils.ensureExpectedToken(XContentParser.Token.START_ARRAY, parser.currentToken(), parser);
return new SearchSortValues(parser.list().toArray());
}
/**
* Returns the formatted version of the values that sorting was performed against
*/
public Object[] getFormattedSortValues() {
return formattedSortValues;
}
/**
* Returns the raw version of the values that sorting was performed against
*/
public Object[] getRawSortValues() {
return rawSortValues;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SearchSortValues that = (SearchSortValues) o;
return Arrays.equals(formattedSortValues, that.formattedSortValues) && Arrays.equals(rawSortValues, that.rawSortValues);
}
@Override
public int hashCode() {
int result = Arrays.hashCode(formattedSortValues);
result = 31 * result + Arrays.hashCode(rawSortValues);
return result;
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/search/SearchSortValues.java |
2,680 | /*
* Copyright (C) 2012 The Guava Authors
*
* 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 com.google.common.base;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.CharMatcher.NamedFastMatcher;
import java.util.BitSet;
/**
* An immutable version of CharMatcher for smallish sets of characters that uses a hash table with
* linear probing to check for matches.
*
* @author Christopher Swenson
*/
@GwtIncompatible // no precomputation is done in GWT
@ElementTypesAreNonnullByDefault
final class SmallCharMatcher extends NamedFastMatcher {
static final int MAX_SIZE = 1023;
private final char[] table;
private final boolean containsZero;
private final long filter;
private SmallCharMatcher(char[] table, long filter, boolean containsZero, String description) {
super(description);
this.table = table;
this.filter = filter;
this.containsZero = containsZero;
}
private static final int C1 = 0xcc9e2d51;
private static final int C2 = 0x1b873593;
/*
* This method was rewritten in Java from an intermediate step of the Murmur hash function in
* http://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp, which contained the
* following header:
*
* MurmurHash3 was written by Austin Appleby, and is placed in the public domain. The author
* hereby disclaims copyright to this source code.
*/
static int smear(int hashCode) {
return C2 * Integer.rotateLeft(hashCode * C1, 15);
}
private boolean checkFilter(int c) {
return 1 == (1 & (filter >> c));
}
// This is all essentially copied from ImmutableSet, but we have to duplicate because
// of dependencies.
// Represents how tightly we can pack things, as a maximum.
private static final double DESIRED_LOAD_FACTOR = 0.5;
/**
* Returns an array size suitable for the backing array of a hash table that uses open addressing
* with linear probing in its implementation. The returned size is the smallest power of two that
* can hold setSize elements with the desired load factor.
*/
@VisibleForTesting
static int chooseTableSize(int setSize) {
if (setSize == 1) {
return 2;
}
// Correct the size for open addressing to match desired load factor.
// Round up to the next highest power of 2.
int tableSize = Integer.highestOneBit(setSize - 1) << 1;
while (tableSize * DESIRED_LOAD_FACTOR < setSize) {
tableSize <<= 1;
}
return tableSize;
}
static CharMatcher from(BitSet chars, String description) {
// Compute the filter.
long filter = 0;
int size = chars.cardinality();
boolean containsZero = chars.get(0);
// Compute the hash table.
char[] table = new char[chooseTableSize(size)];
int mask = table.length - 1;
for (int c = chars.nextSetBit(0); c != -1; c = chars.nextSetBit(c + 1)) {
// Compute the filter at the same time.
filter |= 1L << c;
int index = smear(c) & mask;
while (true) {
// Check for empty.
if (table[index] == 0) {
table[index] = (char) c;
break;
}
// Linear probing.
index = (index + 1) & mask;
}
}
return new SmallCharMatcher(table, filter, containsZero, description);
}
@Override
public boolean matches(char c) {
if (c == 0) {
return containsZero;
}
if (!checkFilter(c)) {
return false;
}
int mask = table.length - 1;
int startingIndex = smear(c) & mask;
int index = startingIndex;
do {
if (table[index] == 0) { // Check for empty.
return false;
} else if (table[index] == c) { // Check for match.
return true;
} else { // Linear probing.
index = (index + 1) & mask;
}
// Check to see if we wrapped around the whole table.
} while (index != startingIndex);
return false;
}
@Override
void setBits(BitSet table) {
if (containsZero) {
table.set(0);
}
for (char c : this.table) {
if (c != 0) {
table.set(c);
}
}
}
}
| google/guava | guava/src/com/google/common/base/SmallCharMatcher.java |
2,681 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.script;
import org.elasticsearch.index.fielddata.ScriptDocValues;
import org.elasticsearch.script.field.EmptyField;
import org.elasticsearch.script.field.Field;
import org.elasticsearch.search.lookup.Source;
import org.elasticsearch.xcontent.XContentType;
import java.util.Collections;
import java.util.Map;
import java.util.function.Supplier;
import java.util.stream.Stream;
public abstract class DocBasedScript {
protected final DocReader docReader;
public DocBasedScript(DocReader docReader) {
this.docReader = docReader;
}
public Field<?> field(String fieldName) {
if (docReader == null) {
return new EmptyField(fieldName);
}
return docReader.field(fieldName);
}
public Stream<Field<?>> fields(String fieldGlob) {
if (docReader == null) {
return Stream.empty();
}
return docReader.fields(fieldGlob);
}
/**
* Set the current document to run the script on next.
*/
public void setDocument(int docID) {
if (docReader != null) {
docReader.setDocument(docID);
}
}
public Map<String, Object> docAsMap() {
if (docReader == null) {
return Collections.emptyMap();
}
return docReader.docAsMap();
}
public Supplier<Source> source() {
if (docReader == null) {
return () -> Source.empty(XContentType.JSON);
}
return docReader.source();
}
/**
* The doc lookup for the Lucene segment this script was created for.
*/
public Map<String, ScriptDocValues<?>> getDoc() {
if (docReader == null) {
return Collections.emptyMap();
}
return docReader.doc();
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/script/DocBasedScript.java |
2,682 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.common.util;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefIterator;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.Writeable;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* Abstraction of an array of byte values.
*/
public interface ByteArray extends BigArray, Writeable {
static ByteArray readFrom(StreamInput in) throws IOException {
return new ReleasableByteArray(in);
}
/**
* Get an element given its index.
*/
byte get(long index);
/**
* Set a value at the given index and return the previous value.
*/
byte set(long index, byte value);
/**
* Get a reference to a slice.
*
* @return <code>true</code> when a byte[] was materialized, <code>false</code> otherwise.
*/
boolean get(long index, int len, BytesRef ref);
/**
* Bulk set.
*/
void set(long index, byte[] buf, int offset, int len);
/**
* Fill slots between <code>fromIndex</code> inclusive to <code>toIndex</code> exclusive with <code>value</code>.
*/
void fill(long fromIndex, long toIndex, byte value);
/**
* Fills this ByteArray with bytes from the given input stream
*/
void fillWith(StreamInput in) throws IOException;
/**
* Returns a BytesRefIterator for this ByteArray. This method allows
* access to the internal pages of this reference without copying them.
*/
BytesRefIterator iterator();
/**
* Checks if this instance is backed by a single byte array analogous to {@link ByteBuffer#hasArray()}.
*/
boolean hasArray();
/**
* Get backing byte array analogous to {@link ByteBuffer#array()}.
*/
byte[] array();
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/common/util/ByteArray.java |
2,684 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.action;
import org.elasticsearch.xcontent.ToXContent;
public enum ClusterStatsLevel {
CLUSTER("cluster"),
INDICES("indices"),
SHARDS("shards");
private final String level;
ClusterStatsLevel(String level) {
this.level = level;
}
public String getLevel() {
return level;
}
public static ClusterStatsLevel of(String level) {
for (ClusterStatsLevel value : values()) {
if (value.getLevel().equalsIgnoreCase(level)) {
return value;
}
}
throw new IllegalArgumentException("level parameter must be one of [cluster] or [indices] or [shards] but was [" + level + "]");
}
public static ClusterStatsLevel of(ToXContent.Params params, ClusterStatsLevel defaultLevel) {
return ClusterStatsLevel.of(params.param("level", defaultLevel.getLevel()));
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/action/ClusterStatsLevel.java |
2,685 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.search;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.search.fetch.FetchSearchResult;
import org.elasticsearch.search.internal.ShardSearchContextId;
import org.elasticsearch.search.internal.ShardSearchRequest;
import org.elasticsearch.search.query.QuerySearchResult;
import org.elasticsearch.transport.TransportResponse;
import java.io.IOException;
/**
* This class is a base class for all search related results. It contains the shard target it
* was executed against, a shard index used to reference the result on the coordinating node
* and a request ID that is used to reference the request context on the executing node. The
* request ID is particularly important since it is used to reference and maintain a context
* across search phases to ensure the same point in time snapshot is used for querying and
* fetching etc.
*/
public abstract class SearchPhaseResult extends TransportResponse {
private SearchShardTarget searchShardTarget;
private int shardIndex = -1;
protected ShardSearchContextId contextId;
private ShardSearchRequest shardSearchRequest;
private RescoreDocIds rescoreDocIds = RescoreDocIds.EMPTY;
protected SearchPhaseResult() {
}
protected SearchPhaseResult(StreamInput in) throws IOException {
super(in);
}
/**
* Returns the search context ID that is used to reference the search context on the executing node
* or <code>null</code> if no context was created.
*/
@Nullable
public ShardSearchContextId getContextId() {
return contextId;
}
/**
* Returns the shard index in the context of the currently executing search request that is
* used for accounting on the coordinating node
*/
public int getShardIndex() {
assert shardIndex != -1 : "shardIndex is not set";
return shardIndex;
}
public SearchShardTarget getSearchShardTarget() {
return searchShardTarget;
}
public void setSearchShardTarget(SearchShardTarget shardTarget) {
this.searchShardTarget = shardTarget;
}
public void setShardIndex(int shardIndex) {
assert shardIndex >= 0 : "shardIndex must be >= 0 but was: " + shardIndex;
this.shardIndex = shardIndex;
}
/**
* Returns the query result iff it's included in this response otherwise <code>null</code>
*/
public QuerySearchResult queryResult() {
return null;
}
/**
* Returns the fetch result iff it's included in this response otherwise <code>null</code>
*/
public FetchSearchResult fetchResult() {
return null;
}
@Nullable
public ShardSearchRequest getShardSearchRequest() {
return shardSearchRequest;
}
public void setShardSearchRequest(ShardSearchRequest shardSearchRequest) {
this.shardSearchRequest = shardSearchRequest;
}
public RescoreDocIds getRescoreDocIds() {
return rescoreDocIds;
}
public void setRescoreDocIds(RescoreDocIds rescoreDocIds) {
this.rescoreDocIds = rescoreDocIds;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
// TODO: this seems wrong, SearchPhaseResult should have a writeTo?
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/search/SearchPhaseResult.java |
2,688 | /*
* Copyright (C) 2008 Google Inc.
*
* 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 org.elasticsearch.common.inject.spi;
/**
* A core component of a module or injector.
* <p>
* The elements of a module can be inspected, validated and rewritten. Use {@link
* Elements#getElements(org.elasticsearch.common.inject.Module[]) Elements.getElements()} to read the elements
* from a module to rewrite them.
* This can be used for static analysis and generation of Guice modules.
*
* @author [email protected] (Jesse Wilson)
* @author [email protected] (Bob Lee)
* @since 2.0
*/
public interface Element {
/**
* Returns an arbitrary object containing information about the "place" where this element was
* configured. Used by Guice in the production of descriptive error messages.
* <p>
* Tools might specially handle types they know about; {@code StackTraceElement} is a good
* example. Tools should simply call {@code toString()} on the source object if the type is
* unfamiliar.
*/
Object getSource();
/**
* Accepts an element visitor. Invokes the visitor method specific to this element's type.
*
* @param visitor to call back on
*/
<T> T acceptVisitor(ElementVisitor<T> visitor);
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/common/inject/spi/Element.java |
2,690 | /*
* Copyright (C) 2016 The Guava Authors
*
* 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 com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Collections.emptyList;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.stream.Collector;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Collectors not present in {@code java.util.stream.Collectors} that are not otherwise associated
* with a {@code com.google.common} type.
*
* @author Louis Wasserman
* @since 33.2.0 (available since 21.0 in guava-jre)
*/
@GwtCompatible
@ElementTypesAreNonnullByDefault
@SuppressWarnings({"AndroidJdkLibsChecker", "Java7ApiChecker"})
@IgnoreJRERequirement // Users will use this only if they're already using streams.
@Beta // TODO: b/288085449 - Remove.
public final class MoreCollectors {
/*
* TODO(lowasser): figure out if we can convert this to a concurrent AtomicReference-based
* collector without breaking j2cl?
*/
private static final Collector<Object, ?, Optional<Object>> TO_OPTIONAL =
Collector.of(
ToOptionalState::new,
ToOptionalState::add,
ToOptionalState::combine,
ToOptionalState::getOptional,
Collector.Characteristics.UNORDERED);
/**
* A collector that converts a stream of zero or one elements to an {@code Optional}.
*
* @throws IllegalArgumentException if the stream consists of two or more elements.
* @throws NullPointerException if any element in the stream is {@code null}.
* @return {@code Optional.of(onlyElement)} if the stream has exactly one element (must not be
* {@code null}) and returns {@code Optional.empty()} if it has none.
*/
@SuppressWarnings("unchecked")
public static <T> Collector<T, ?, Optional<T>> toOptional() {
return (Collector) TO_OPTIONAL;
}
private static final Object NULL_PLACEHOLDER = new Object();
private static final Collector<@Nullable Object, ?, @Nullable Object> ONLY_ELEMENT =
Collector.<@Nullable Object, ToOptionalState, @Nullable Object>of(
ToOptionalState::new,
(state, o) -> state.add((o == null) ? NULL_PLACEHOLDER : o),
ToOptionalState::combine,
state -> {
Object result = state.getElement();
return (result == NULL_PLACEHOLDER) ? null : result;
},
Collector.Characteristics.UNORDERED);
/**
* A collector that takes a stream containing exactly one element and returns that element. The
* returned collector throws an {@code IllegalArgumentException} if the stream consists of two or
* more elements, and a {@code NoSuchElementException} if the stream is empty.
*/
@SuppressWarnings("unchecked")
public static <T extends @Nullable Object> Collector<T, ?, T> onlyElement() {
return (Collector) ONLY_ELEMENT;
}
/**
* This atrocity is here to let us report several of the elements in the stream if there were more
* than one, not just two.
*/
private static final class ToOptionalState {
static final int MAX_EXTRAS = 4;
@CheckForNull Object element;
List<Object> extras;
ToOptionalState() {
element = null;
extras = emptyList();
}
IllegalArgumentException multiples(boolean overflow) {
StringBuilder sb =
new StringBuilder().append("expected one element but was: <").append(element);
for (Object o : extras) {
sb.append(", ").append(o);
}
if (overflow) {
sb.append(", ...");
}
sb.append('>');
throw new IllegalArgumentException(sb.toString());
}
void add(Object o) {
checkNotNull(o);
if (element == null) {
this.element = o;
} else if (extras.isEmpty()) {
// Replace immutable empty list with mutable list.
extras = new ArrayList<>(MAX_EXTRAS);
extras.add(o);
} else if (extras.size() < MAX_EXTRAS) {
extras.add(o);
} else {
throw multiples(true);
}
}
ToOptionalState combine(ToOptionalState other) {
if (element == null) {
return other;
} else if (other.element == null) {
return this;
} else {
if (extras.isEmpty()) {
// Replace immutable empty list with mutable list.
extras = new ArrayList<>();
}
extras.add(other.element);
extras.addAll(other.extras);
if (extras.size() > MAX_EXTRAS) {
extras.subList(MAX_EXTRAS, extras.size()).clear();
throw multiples(true);
}
return this;
}
}
@IgnoreJRERequirement // see enclosing class (whose annotation Animal Sniffer ignores here...)
Optional<Object> getOptional() {
if (extras.isEmpty()) {
return Optional.ofNullable(element);
} else {
throw multiples(false);
}
}
Object getElement() {
if (element == null) {
throw new NoSuchElementException();
} else if (extras.isEmpty()) {
return element;
} else {
throw multiples(false);
}
}
}
private MoreCollectors() {}
}
| google/guava | android/guava/src/com/google/common/collect/MoreCollectors.java |
2,691 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.common.lucene.uid;
public final class Versions {
/** used to indicate the write operation should succeed regardless of current version **/
public static final long MATCH_ANY = -3L;
/** indicates that the current document was not found in lucene and in the version map */
public static final long NOT_FOUND = -1L;
// -2 was used for docs that can be found in the index but do not have a version
/**
* used to indicate that the write operation should be executed if the document is currently deleted
* i.e., not found in the index and/or found as deleted (with version) in the version map
*/
public static final long MATCH_DELETED = -4L;
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/common/lucene/uid/Versions.java |
2,692 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.transport;
import org.elasticsearch.common.Strings;
public class NetworkTraceFlag {
private NetworkTraceFlag() {
// no instances;
}
public static final String PROPERTY_NAME = "es.insecure_network_trace_enabled";
public static final boolean TRACE_ENABLED;
static {
final var propertyValue = System.getProperty(PROPERTY_NAME);
if (propertyValue == null) {
TRACE_ENABLED = false;
} else if ("true".equals(propertyValue)) {
TRACE_ENABLED = true;
} else {
throw new IllegalArgumentException(
Strings.format("system property [%s] may only be set to [true], but was [%s]", PROPERTY_NAME, propertyValue)
);
}
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/transport/NetworkTraceFlag.java |
2,694 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.index.seqno;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.xcontent.ConstructingObjectParser;
import org.elasticsearch.xcontent.ParseField;
import org.elasticsearch.xcontent.ToXContentObject;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xcontent.XContentParser;
import java.io.IOException;
import java.util.Objects;
/**
* A "shard history retention lease" (or "retention lease" for short) is conceptually a marker containing a retaining sequence number such
* that all operations with sequence number at least that retaining sequence number will be retained during merge operations (which could
* otherwise merge away operations that have been soft deleted). Each retention lease contains a unique identifier, the retaining sequence
* number, the timestamp of when the lease was created or renewed, and the source of the retention lease (e.g., "ccr").
*/
public final class RetentionLease implements ToXContentObject, Writeable {
private final String id;
/**
* The identifier for this retention lease. This identifier should be unique per lease and is set during construction by the caller.
*
* @return the identifier
*/
public String id() {
return id;
}
private final long retainingSequenceNumber;
/**
* The retaining sequence number of this retention lease. The retaining sequence number is the minimum sequence number that this
* retention lease wants to retain during merge operations. The retaining sequence number is set during construction by the caller.
*
* @return the retaining sequence number
*/
public long retainingSequenceNumber() {
return retainingSequenceNumber;
}
private final long timestamp;
/**
* The timestamp of when this retention lease was created or renewed.
*
* @return the timestamp used as a basis for determining lease expiration
*/
public long timestamp() {
return timestamp;
}
private final String source;
/**
* The source of this retention lease. The source is set during construction by the caller.
*
* @return the source
*/
public String source() {
return source;
}
/**
* Constructs a new retention lease.
*
* @param id the identifier of the retention lease
* @param retainingSequenceNumber the retaining sequence number
* @param timestamp the timestamp of when the retention lease was created or renewed
* @param source the source of the retention lease
*/
public RetentionLease(final String id, final long retainingSequenceNumber, final long timestamp, final String source) {
Objects.requireNonNull(id);
if (id.isEmpty()) {
throw new IllegalArgumentException("retention lease ID can not be empty");
}
if (retainingSequenceNumber < 0) {
throw new IllegalArgumentException("retention lease retaining sequence number [" + retainingSequenceNumber + "] out of range");
}
if (timestamp < 0) {
throw new IllegalArgumentException("retention lease timestamp [" + timestamp + "] out of range");
}
Objects.requireNonNull(source);
if (source.isEmpty()) {
throw new IllegalArgumentException("retention lease source can not be empty");
}
this.id = id;
this.retainingSequenceNumber = retainingSequenceNumber;
this.timestamp = timestamp;
// deduplicate the string instances to save memory for the known possible source values
this.source = switch (source) {
case "ccr" -> "ccr";
case ReplicationTracker.PEER_RECOVERY_RETENTION_LEASE_SOURCE -> ReplicationTracker.PEER_RECOVERY_RETENTION_LEASE_SOURCE;
default -> source;
};
}
/**
* Constructs a new retention lease from a stream. The retention lease should have been written via {@link #writeTo(StreamOutput)}.
*
* @param in the stream to construct the retention lease from
* @throws IOException if an I/O exception occurs reading from the stream
*/
public RetentionLease(final StreamInput in) throws IOException {
this(in.readString(), in.readZLong(), in.readVLong(), in.readString());
}
/**
* Writes a retention lease to a stream in a manner suitable for later reconstruction via {@link #RetentionLease(StreamInput)}.
*
* @param out the stream to write the retention lease to
* @throws IOException if an I/O exception occurs writing to the stream
*/
@Override
public void writeTo(final StreamOutput out) throws IOException {
out.writeString(id);
out.writeZLong(retainingSequenceNumber);
out.writeVLong(timestamp);
out.writeString(source);
}
private static final ParseField ID_FIELD = new ParseField("id");
private static final ParseField RETAINING_SEQUENCE_NUMBER_FIELD = new ParseField("retaining_sequence_number");
private static final ParseField TIMESTAMP_FIELD = new ParseField("timestamp");
private static final ParseField SOURCE_FIELD = new ParseField("source");
private static final ConstructingObjectParser<RetentionLease, Void> PARSER = new ConstructingObjectParser<>(
"retention_leases",
(a) -> new RetentionLease((String) a[0], (Long) a[1], (Long) a[2], (String) a[3])
);
static {
PARSER.declareString(ConstructingObjectParser.constructorArg(), ID_FIELD);
PARSER.declareLong(ConstructingObjectParser.constructorArg(), RETAINING_SEQUENCE_NUMBER_FIELD);
PARSER.declareLong(ConstructingObjectParser.constructorArg(), TIMESTAMP_FIELD);
PARSER.declareString(ConstructingObjectParser.constructorArg(), SOURCE_FIELD);
}
@Override
public XContentBuilder toXContent(final XContentBuilder builder, final Params params) throws IOException {
builder.startObject();
{
builder.field(ID_FIELD.getPreferredName(), id);
builder.field(RETAINING_SEQUENCE_NUMBER_FIELD.getPreferredName(), retainingSequenceNumber);
builder.field(TIMESTAMP_FIELD.getPreferredName(), timestamp);
builder.field(SOURCE_FIELD.getPreferredName(), source);
}
builder.endObject();
return builder;
}
/**
* Parses a retention lease from {@link org.elasticsearch.xcontent.XContent}. This method assumes that the retention lease was
* converted to {@link org.elasticsearch.xcontent.XContent} via {@link #toXContent(XContentBuilder, Params)}.
*
* @param parser the parser
* @return a retention lease
*/
public static RetentionLease fromXContent(final XContentParser parser) {
return PARSER.apply(parser, null);
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final RetentionLease that = (RetentionLease) o;
return Objects.equals(id, that.id)
&& retainingSequenceNumber == that.retainingSequenceNumber
&& timestamp == that.timestamp
&& Objects.equals(source, that.source);
}
@Override
public int hashCode() {
return Objects.hash(id, retainingSequenceNumber, timestamp, source);
}
@Override
public String toString() {
return "RetentionLease{"
+ "id='"
+ id
+ '\''
+ ", retainingSequenceNumber="
+ retainingSequenceNumber
+ ", timestamp="
+ timestamp
+ ", source='"
+ source
+ '\''
+ '}';
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/index/seqno/RetentionLease.java |
2,696 | /*
* Copyright (C) 2006 The Guava Authors
*
* 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 com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.util.concurrent.AbstractFuture.TrustedFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/** Implementation of {@link Futures#immediateFuture}. */
@GwtCompatible
@ElementTypesAreNonnullByDefault
// TODO(cpovirk): Make this final (but that may break Mockito spy calls).
class ImmediateFuture<V extends @Nullable Object> implements ListenableFuture<V> {
static final ListenableFuture<?> NULL = new ImmediateFuture<@Nullable Object>(null);
private static final LazyLogger log = new LazyLogger(ImmediateFuture.class);
@ParametricNullness private final V value;
ImmediateFuture(@ParametricNullness V value) {
this.value = value;
}
@Override
@SuppressWarnings("CatchingUnchecked") // sneaky checked exception
public void addListener(Runnable listener, Executor executor) {
checkNotNull(listener, "Runnable was null.");
checkNotNull(executor, "Executor was null.");
try {
executor.execute(listener);
} catch (Exception e) { // sneaky checked exception
// ListenableFuture's contract is that it will not throw unchecked exceptions, so log the bad
// runnable and/or executor and swallow it.
log.get()
.log(
Level.SEVERE,
"RuntimeException while executing runnable "
+ listener
+ " with executor "
+ executor,
e);
}
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
// TODO(lukes): Consider throwing InterruptedException when appropriate.
@Override
@ParametricNullness
public V get() {
return value;
}
@Override
@ParametricNullness
public V get(long timeout, TimeUnit unit) throws ExecutionException {
checkNotNull(unit);
return get();
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public boolean isDone() {
return true;
}
@Override
public String toString() {
// Behaviour analogous to AbstractFuture#toString().
return super.toString() + "[status=SUCCESS, result=[" + value + "]]";
}
static final class ImmediateFailedFuture<V extends @Nullable Object> extends TrustedFuture<V> {
ImmediateFailedFuture(Throwable thrown) {
setException(thrown);
}
}
static final class ImmediateCancelledFuture<V extends @Nullable Object> extends TrustedFuture<V> {
@CheckForNull
static final ImmediateCancelledFuture<Object> INSTANCE =
AbstractFuture.GENERATE_CANCELLATION_CAUSES ? null : new ImmediateCancelledFuture<>();
ImmediateCancelledFuture() {
cancel(false);
}
}
}
| google/guava | guava/src/com/google/common/util/concurrent/ImmediateFuture.java |
2,697 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.inference;
import org.elasticsearch.TransportVersion;
import org.elasticsearch.TransportVersions;
import java.util.EnumSet;
import java.util.Locale;
public enum SimilarityMeasure {
COSINE,
DOT_PRODUCT,
L2_NORM;
private static final EnumSet<SimilarityMeasure> BEFORE_L2_NORM_ENUMS = EnumSet.range(COSINE, DOT_PRODUCT);
@Override
public String toString() {
return name().toLowerCase(Locale.ROOT);
}
public static SimilarityMeasure fromString(String name) {
return valueOf(name.trim().toUpperCase(Locale.ROOT));
}
/**
* Returns a similarity measure that is known based on the transport version provided. If the similarity enum was not yet
* introduced it will be defaulted to null.
*
* @param similarityMeasure the value to translate if necessary
* @param version the version that dictates the translation
* @return the similarity that is known to the version passed in
*/
public static SimilarityMeasure translateSimilarity(SimilarityMeasure similarityMeasure, TransportVersion version) {
if (version.before(TransportVersions.ML_INFERENCE_L2_NORM_SIMILARITY_ADDED)
&& BEFORE_L2_NORM_ENUMS.contains(similarityMeasure) == false) {
return null;
}
return similarityMeasure;
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/inference/SimilarityMeasure.java |
2,698 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.action.delete;
import org.apache.lucene.util.RamUsageEstimator;
import org.elasticsearch.TransportVersions;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.CompositeIndicesRequest;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.support.replication.ReplicatedWriteRequest;
import org.elasticsearch.cluster.routing.IndexRouting;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.lucene.uid.Versions;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.index.VersionType;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.shard.ShardId;
import java.io.IOException;
import static org.elasticsearch.action.ValidateActions.addValidationError;
import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_PRIMARY_TERM;
import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO;
/**
* A request to delete a document from an index based on its type and id.
* <p>
* The operation requires the {@link #index()} and {@link #id(String)} to
* be set.
*
* @see DeleteResponse
* @see org.elasticsearch.client.internal.Client#delete(DeleteRequest)
*/
public class DeleteRequest extends ReplicatedWriteRequest<DeleteRequest>
implements
DocWriteRequest<DeleteRequest>,
CompositeIndicesRequest {
private static final long SHALLOW_SIZE = RamUsageEstimator.shallowSizeOfInstance(DeleteRequest.class);
private static final ShardId NO_SHARD_ID = null;
private String id;
@Nullable
private String routing;
private long version = Versions.MATCH_ANY;
private VersionType versionType = VersionType.INTERNAL;
private long ifSeqNo = UNASSIGNED_SEQ_NO;
private long ifPrimaryTerm = UNASSIGNED_PRIMARY_TERM;
public DeleteRequest(StreamInput in) throws IOException {
this(null, in);
}
public DeleteRequest(@Nullable ShardId shardId, StreamInput in) throws IOException {
super(shardId, in);
if (in.getTransportVersion().before(TransportVersions.V_8_0_0)) {
String type = in.readString();
assert MapperService.SINGLE_MAPPING_NAME.equals(type) : "Expected [_doc] but received [" + type + "]";
}
id = in.readString();
routing = in.readOptionalString();
version = in.readLong();
versionType = VersionType.fromValue(in.readByte());
ifSeqNo = in.readZLong();
ifPrimaryTerm = in.readVLong();
}
public DeleteRequest() {
super(NO_SHARD_ID);
}
/**
* Constructs a new delete request against the specified index. The {@link #id(String)}
* must be set.
*/
public DeleteRequest(String index) {
super(NO_SHARD_ID);
this.index = index;
}
/**
* Constructs a new delete request against the specified index and id.
*
* @param index The index to get the document from
* @param id The id of the document
*/
public DeleteRequest(String index, String id) {
super(NO_SHARD_ID);
this.index = index;
this.id = id;
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = super.validate();
if (Strings.isEmpty(id)) {
validationException = addValidationError("id is missing", validationException);
}
validationException = DocWriteRequest.validateSeqNoBasedCASParams(this, validationException);
return validationException;
}
/**
* The id of the document to delete.
*/
@Override
public String id() {
return id;
}
/**
* Sets the id of the document to delete.
*/
public DeleteRequest id(String id) {
this.id = id;
return this;
}
/**
* Controls the shard routing of the request. Using this value to hash the shard
* and not the id.
*/
@Override
public DeleteRequest routing(String routing) {
if (routing != null && routing.length() == 0) {
this.routing = null;
} else {
this.routing = routing;
}
return this;
}
/**
* Controls the shard routing of the delete request. Using this value to hash the shard
* and not the id.
*/
@Override
public String routing() {
return this.routing;
}
@Override
public DeleteRequest version(long version) {
this.version = version;
return this;
}
@Override
public long version() {
return this.version;
}
@Override
public DeleteRequest versionType(VersionType versionType) {
this.versionType = versionType;
return this;
}
/**
* If set, only perform this delete request if the document was last modification was assigned this sequence number.
* If the document last modification was assigned a different sequence number a
* {@link org.elasticsearch.index.engine.VersionConflictEngineException} will be thrown.
*/
public long ifSeqNo() {
return ifSeqNo;
}
/**
* If set, only perform this delete request if the document was last modification was assigned this primary term.
*
* If the document last modification was assigned a different term a
* {@link org.elasticsearch.index.engine.VersionConflictEngineException} will be thrown.
*/
public long ifPrimaryTerm() {
return ifPrimaryTerm;
}
/**
* only perform this delete request if the document was last modification was assigned the given
* sequence number. Must be used in combination with {@link #setIfPrimaryTerm(long)}
*
* If the document last modification was assigned a different sequence number a
* {@link org.elasticsearch.index.engine.VersionConflictEngineException} will be thrown.
*/
public DeleteRequest setIfSeqNo(long seqNo) {
if (seqNo < 0 && seqNo != UNASSIGNED_SEQ_NO) {
throw new IllegalArgumentException("sequence numbers must be non negative. got [" + seqNo + "].");
}
ifSeqNo = seqNo;
return this;
}
/**
* only perform this delete request if the document was last modification was assigned the given
* primary term. Must be used in combination with {@link #setIfSeqNo(long)}
*
* If the document last modification was assigned a different primary term a
* {@link org.elasticsearch.index.engine.VersionConflictEngineException} will be thrown.
*/
public DeleteRequest setIfPrimaryTerm(long term) {
if (term < 0) {
throw new IllegalArgumentException("primary term must be non negative. got [" + term + "]");
}
ifPrimaryTerm = term;
return this;
}
@Override
public VersionType versionType() {
return this.versionType;
}
@Override
public OpType opType() {
return OpType.DELETE;
}
@Override
public boolean isRequireAlias() {
return false;
}
@Override
public boolean isRequireDataStream() {
return false;
}
@Override
public void process(IndexRouting indexRouting) {
// Nothing to do
}
@Override
public int route(IndexRouting indexRouting) {
return indexRouting.deleteShard(id, routing);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
writeBody(out);
}
@Override
public void writeThin(StreamOutput out) throws IOException {
super.writeThin(out);
writeBody(out);
}
private void writeBody(StreamOutput out) throws IOException {
if (out.getTransportVersion().before(TransportVersions.V_8_0_0)) {
out.writeString(MapperService.SINGLE_MAPPING_NAME);
}
out.writeString(id);
out.writeOptionalString(routing());
out.writeLong(version);
out.writeByte(versionType.getValue());
out.writeZLong(ifSeqNo);
out.writeVLong(ifPrimaryTerm);
}
@Override
public String toString() {
return "delete {[" + index + "][" + id + "]}";
}
@Override
public long ramBytesUsed() {
return SHALLOW_SIZE + RamUsageEstimator.sizeOf(id);
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/action/delete/DeleteRequest.java |
2,699 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.watcher;
import java.nio.file.Path;
/**
* Callback interface that file changes File Watcher is using to notify listeners about changes.
*/
public interface FileChangesListener {
/**
* Called for every file found in the watched directory during initialization
*/
default void onFileInit(Path file) {}
/**
* Called for every subdirectory found in the watched directory during initialization
*/
default void onDirectoryInit(Path file) {}
/**
* Called for every new file found in the watched directory
*/
default void onFileCreated(Path file) {}
/**
* Called for every file that disappeared in the watched directory
*/
default void onFileDeleted(Path file) {}
/**
* Called for every file that was changed in the watched directory
*/
default void onFileChanged(Path file) {}
/**
* Called for every new subdirectory found in the watched directory
*/
default void onDirectoryCreated(Path file) {}
/**
* Called for every file that disappeared in the watched directory
*/
default void onDirectoryDeleted(Path file) {}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/watcher/FileChangesListener.java |
2,700 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.action.bulk;
import org.apache.lucene.util.Accountable;
import org.apache.lucene.util.RamUsageEstimator;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.index.shard.ShardId;
import java.io.IOException;
import java.util.Objects;
public class BulkItemRequest implements Writeable, Accountable {
private static final long SHALLOW_SIZE = RamUsageEstimator.shallowSizeOfInstance(BulkItemRequest.class);
private final int id;
private final DocWriteRequest<?> request;
private volatile BulkItemResponse primaryResponse;
BulkItemRequest(@Nullable ShardId shardId, StreamInput in) throws IOException {
id = in.readVInt();
request = DocWriteRequest.readDocumentRequest(shardId, in);
if (in.readBoolean()) {
if (shardId == null) {
primaryResponse = new BulkItemResponse(in);
} else {
primaryResponse = new BulkItemResponse(shardId, in);
}
}
}
// NOTE: public for testing only
public BulkItemRequest(int id, DocWriteRequest<?> request) {
this.id = id;
this.request = request;
}
public int id() {
return id;
}
public DocWriteRequest<?> request() {
return request;
}
public String index() {
assert request.indices().length == 1;
return request.indices()[0];
}
// public for tests
public BulkItemResponse getPrimaryResponse() {
return primaryResponse;
}
void setPrimaryResponse(BulkItemResponse primaryResponse) {
this.primaryResponse = primaryResponse;
}
/**
* Abort this request, and store a {@link org.elasticsearch.action.bulk.BulkItemResponse.Failure} response.
*
* @param index The concrete index that was resolved for this request
* @param cause The cause of the rejection (may not be null)
* @throws IllegalStateException If a response already exists for this request
*/
public void abort(String index, Exception cause) {
if (primaryResponse == null) {
final BulkItemResponse.Failure failure = new BulkItemResponse.Failure(index, request.id(), Objects.requireNonNull(cause), true);
setPrimaryResponse(BulkItemResponse.failure(id, request.opType(), failure));
} else {
assert primaryResponse.isFailed() && primaryResponse.getFailure().isAborted()
: "response [" + Strings.toString(primaryResponse) + "]; cause [" + cause + "]";
if (primaryResponse.isFailed() && primaryResponse.getFailure().isAborted()) {
primaryResponse.getFailure().getCause().addSuppressed(cause);
} else {
throw new IllegalStateException(
"aborting item that with response [" + primaryResponse + "] that was previously processed",
cause
);
}
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVInt(id);
DocWriteRequest.writeDocumentRequest(out, request);
out.writeOptionalWriteable(primaryResponse);
}
public void writeThin(StreamOutput out) throws IOException {
out.writeVInt(id);
DocWriteRequest.writeDocumentRequestThin(out, request);
out.writeOptionalWriteable(primaryResponse == null ? null : primaryResponse::writeThin);
}
@Override
public long ramBytesUsed() {
return SHALLOW_SIZE + request.ramBytesUsed();
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/action/bulk/BulkItemRequest.java |
2,701 | package com.baeldung;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
public class BenchMark {
@State(Scope.Benchmark)
public static class Log {
public int x = 8;
}
@State(Scope.Benchmark)
public static class ExecutionPlan {
@Param({ "100", "200", "300", "500", "1000" })
public int iterations;
public Hasher murmur3;
public String password = "4v3rys3kur3p455w0rd";
@Setup(Level.Invocation)
public void setUp() {
murmur3 = Hashing.murmur3_128().newHasher();
}
}
@Fork(value = 1, warmups = 1)
@Benchmark
@BenchmarkMode(Mode.Throughput)
@Warmup(iterations = 5)
public void benchMurmur3_128(ExecutionPlan plan) {
for (int i = plan.iterations; i > 0; i--) {
plan.murmur3.putString(plan.password, Charset.defaultCharset());
}
plan.murmur3.hash();
}
@Benchmark
@Fork(value = 1, warmups = 1)
@BenchmarkMode(Mode.Throughput)
public void init() {
// Do nothing
}
@Benchmark
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(Mode.AverageTime)
public void doNothing() {
}
@Benchmark
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(Mode.AverageTime)
public void objectCreation() {
new Object();
}
@Benchmark
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(Mode.AverageTime)
public Object pillarsOfCreation() {
return new Object();
}
@Benchmark
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(Mode.AverageTime)
public void blackHole(Blackhole blackhole) {
blackhole.consume(new Object());
}
@Benchmark
public double foldedLog() {
int x = 8;
return Math.log(x);
}
@Benchmark
public double log(Log input) {
return Math.log(input.x);
}
}
| eugenp/tutorials | jmh/src/main/java/com/baeldung/BenchMark.java |
2,702 | package com.googleresearch.bustle;
import com.google.common.collect.ImmutableList;
import java.util.Arrays;
import java.util.List;
/** A class to define a benchmark task. */
public class Benchmark {
// The name of the benchmark.
private final String name;
// A brief text description of the benchmark.
private final String description;
// The input-output examples provided by the user to learn the transformation.
private final ImmutableList<Example> trainExamples;
// The examples used to test the synthesized program.
private final ImmutableList<Example> testExamples;
// The expected learnt program.
private final String expectedProgram;
// Tags to categorize benchmarks.
private final ImmutableList<BenchmarkTag> tags;
/** Construct a Benchmark with no tags. */
public static Benchmark createBenchmarkWithNoTags(
String name,
String description,
List<Example> trainExamples,
List<Example> testExamples,
String expectedProgram) {
return new Benchmark(
name,
description,
trainExamples,
testExamples,
expectedProgram,
ImmutableList.of());
}
/** Constructs a Benchmark. */
public Benchmark(
String name,
String description,
List<Example> trainExamples,
List<Example> testExamples,
String expectedProgram,
List<BenchmarkTag> tags) {
this.name = name;
this.description = description;
this.trainExamples = ImmutableList.copyOf(trainExamples);
this.testExamples = ImmutableList.copyOf(testExamples);
this.expectedProgram = expectedProgram;
this.tags = ImmutableList.copyOf(tags);
}
@Override
public String toString() {
return String.join(
"\n",
Arrays.asList(
"Benchmark Name: " + name,
"Description: " + description,
"Train Examples: " + trainExamples,
"Test Examples: " + testExamples,
"Expected Program: " + expectedProgram));
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public List<Example> getTrainExamples() {
return trainExamples;
}
public List<Example> getTestExamples() {
return testExamples;
}
public String getExpectedProgram() {
return expectedProgram;
}
public List<BenchmarkTag> getTags() {
return tags;
}
}
| google-research/google-research | bustle/com/googleresearch/bustle/Benchmark.java |
2,703 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.client.benchmark;
import org.elasticsearch.client.benchmark.metrics.Metrics;
import org.elasticsearch.client.benchmark.metrics.MetricsCalculator;
import org.elasticsearch.client.benchmark.metrics.Sample;
import org.elasticsearch.client.benchmark.metrics.SampleRecorder;
import org.elasticsearch.core.SuppressForbidden;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
public final class BenchmarkRunner {
private final int warmupIterations;
private final int iterations;
private final BenchmarkTask task;
public BenchmarkRunner(int warmupIterations, int iterations, BenchmarkTask task) {
this.warmupIterations = warmupIterations;
this.iterations = iterations;
this.task = task;
}
@SuppressForbidden(reason = "system out is ok for a command line tool")
public void run() {
SampleRecorder recorder = new SampleRecorder(iterations);
System.out.printf(
"Running %s with %d warmup iterations and %d iterations.%n",
task.getClass().getSimpleName(),
warmupIterations,
iterations
);
try {
task.setUp(recorder);
task.run();
task.tearDown();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
return;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
List<Sample> samples = recorder.getSamples();
final List<Metrics> summaryMetrics = MetricsCalculator.calculate(samples);
if (summaryMetrics.isEmpty()) {
System.out.println("No results.");
}
for (Metrics metrics : summaryMetrics) {
String throughput = String.format(Locale.ROOT, "Throughput [ops/s]: %f", metrics.throughput());
String serviceTimes = String.format(
Locale.ROOT,
"Service time [ms]: p50 = %f, p90 = %f, p95 = %f, p99 = %f, p99.9 = %f, p99.99 = %f",
metrics.serviceTimeP50(),
metrics.serviceTimeP90(),
metrics.serviceTimeP95(),
metrics.serviceTimeP99(),
metrics.serviceTimeP999(),
metrics.serviceTimeP9999()
);
String latencies = String.format(
Locale.ROOT,
"Latency [ms]: p50 = %f, p90 = %f, p95 = %f, p99 = %f, p99.9 = %f, p99.99 = %f",
metrics.latencyP50(),
metrics.latencyP90(),
metrics.latencyP95(),
metrics.latencyP99(),
metrics.latencyP999(),
metrics.latencyP9999()
);
int lineLength = Math.max(serviceTimes.length(), latencies.length());
System.out.println(repeat(lineLength, '-'));
System.out.println(throughput);
System.out.println(serviceTimes);
System.out.println(latencies);
System.out.printf("success count = %d, error count = %d%n", metrics.successCount(), metrics.errorCount());
System.out.println(repeat(lineLength, '-'));
}
}
private String repeat(int times, char character) {
char[] characters = new char[times];
Arrays.fill(characters, character);
return new String(characters);
}
}
| elastic/elasticsearch | client/benchmark/src/main/java/org/elasticsearch/client/benchmark/BenchmarkRunner.java |
2,704 | /* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
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 ovic.demo.app;
import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Process;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.text.DecimalFormat;
import org.tensorflow.ovic.OvicBenchmarker;
import org.tensorflow.ovic.OvicClassifierBenchmarker;
import org.tensorflow.ovic.OvicDetectorBenchmarker;
/** Class that benchmark image classifier models. */
public class OvicBenchmarkerActivity extends Activity {
/** Tag for the {@link Log}. */
private static final String TAG = "OvicBenchmarkerActivity";
/** Name of the task-dependent data files stored in Assets. */
private static String labelPath = null;
private static String testImagePath = null;
private static String modelPath = null;
/**
* Each bottom press will launch a benchmarking experiment. The experiment stops when either the
* total native latency reaches WALL_TIME or the number of iterations reaches MAX_ITERATIONS,
* whichever comes first.
*/
/** Wall time for each benchmarking experiment. */
private static final double WALL_TIME = 3000;
/** Maximum number of iterations in each benchmarking experiment. */
private static final int MAX_ITERATIONS = 100;
/** Mask for binding to a single big core. Pixel 1 (4), Pixel 2 (16). */
private static final int BIG_CORE_MASK = 16;
/** Amount of time in milliseconds to wait for affinity to set. */
private static final int WAIT_TIME_FOR_AFFINITY = 1000;
/* The model to be benchmarked. */
private MappedByteBuffer model = null;
private InputStream labelInputStream = null;
private OvicBenchmarker benchmarker;
private TextView textView = null;
// private Button startButton = null;
private static final DecimalFormat df2 = new DecimalFormat(".##");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// TextView used to display the progress, for information purposes only.
textView = (TextView) findViewById(R.id.textView);
}
private Bitmap loadTestBitmap() throws IOException {
InputStream imageStream = getAssets().open(testImagePath);
return BitmapFactory.decodeStream(imageStream);
}
public void initializeTest(boolean benchmarkClassification) throws IOException {
Log.i(TAG, "Initializing benchmarker.");
if (benchmarkClassification) {
benchmarker = new OvicClassifierBenchmarker(WALL_TIME);
labelPath = "labels.txt";
testImagePath = "test_image_224.jpg";
modelPath = "quantized_model.lite";
} else { // Benchmarking detection.
benchmarker = new OvicDetectorBenchmarker(WALL_TIME);
labelPath = "coco_labels.txt";
testImagePath = "test_image_224.jpg";
modelPath = "detect.lite";
}
AssetManager am = getAssets();
AssetFileDescriptor fileDescriptor = am.openFd(modelPath);
FileInputStream modelInputStream = new FileInputStream(fileDescriptor.getFileDescriptor());
FileChannel fileChannel = modelInputStream.getChannel();
long startOffset = fileDescriptor.getStartOffset();
long declaredLength = fileDescriptor.getDeclaredLength();
model = fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength);
labelInputStream = am.open(labelPath);
}
public Boolean doTestIteration() throws IOException, InterruptedException {
if (benchmarker == null) {
throw new RuntimeException("Benchmarker has not been initialized.");
}
if (benchmarker.shouldStop()) {
return false;
}
if (!benchmarker.readyToTest()) {
Log.i(TAG, "getting ready to test.");
benchmarker.getReadyToTest(labelInputStream, model);
if (!benchmarker.readyToTest()) {
throw new RuntimeException("Failed to get the benchmarker ready.");
}
}
Log.i(TAG, "Going to do test iter.");
// Start testing.
Bitmap testImageBitmap = loadTestBitmap();
try {
if (!benchmarker.processBitmap(testImageBitmap)) {
throw new RuntimeException("Failed to run test.");
}
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
testImageBitmap.recycle();
}
String iterResultString = benchmarker.getLastResultString();
if (iterResultString == null) {
throw new RuntimeException("Inference failed to produce a result.");
}
Log.i(TAG, iterResultString);
return true;
}
public void detectPressed(View view) throws IOException {
benchmarkSession(false);
}
public void classifyPressed(View view) throws IOException {
benchmarkSession(true);
}
private void benchmarkSession(boolean benchmarkClassification) throws IOException {
try {
initializeTest(benchmarkClassification);
} catch (IOException e) {
Log.e(TAG, "Can't initialize benchmarker.", e);
throw e;
}
String displayText = "";
if (benchmarkClassification) {
displayText = "Classification benchmark: ";
} else {
displayText = "Detection benchmark: ";
}
try {
setProcessorAffinity(BIG_CORE_MASK);
} catch (IOException e) {
Log.e(TAG, e.getMessage());
displayText = e.getMessage() + "\n";
}
Log.i(TAG, "Successfully initialized benchmarker.");
int testIter = 0;
Boolean iterSuccess = false;
while (testIter < MAX_ITERATIONS) {
try {
iterSuccess = doTestIteration();
} catch (IOException e) {
Log.e(TAG, "Error during iteration " + testIter);
throw e;
} catch (InterruptedException e) {
Log.e(TAG, "Interrupted at iteration " + testIter);
displayText += e.getMessage() + "\n";
}
if (!iterSuccess) {
break;
}
testIter++;
}
Log.i(TAG, "Benchmarking finished");
if (textView != null) {
if (testIter > 0) {
textView.setText(
displayText
+ modelPath
+ ": Average latency="
+ df2.format(benchmarker.getTotalRuntimeNano() * 1.0e-6 / testIter)
+ "ms after "
+ testIter
+ " runs.");
} else {
textView.setText("Benchmarker failed to run on more than one images.");
}
}
}
// TODO(b/153429929) Remove with resolution of issue (see below).
@SuppressWarnings("RuntimeExec")
private static void setProcessorAffinity(int mask) throws IOException {
int myPid = Process.myPid();
Log.i(TAG, String.format("Setting processor affinity to 0x%02x", mask));
String command = String.format("taskset -a -p %x %d", mask, myPid);
try {
// TODO(b/153429929) This is deprecated, but updating is not safe while verification is hard.
Runtime.getRuntime().exec(command).waitFor();
} catch (InterruptedException e) {
throw new IOException("Interrupted: " + e);
}
// Make sure set took effect - try for a second to confirm the change took. If not then fail.
long startTimeMs = SystemClock.elapsedRealtime();
while (true) {
int readBackMask = readCpusAllowedMask();
if (readBackMask == mask) {
Log.i(TAG, String.format("Successfully set affinity to 0x%02x", mask));
return;
}
if (SystemClock.elapsedRealtime() > startTimeMs + WAIT_TIME_FOR_AFFINITY) {
throw new IOException(
String.format(
"Core-binding failed: affinity set to 0x%02x but read back as 0x%02x\n"
+ "please root device.",
mask, readBackMask));
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// Ignore sleep interrupted, will sleep again and compare is final cross-check.
}
}
}
public static int readCpusAllowedMask() throws IOException {
// Determine how many CPUs there are total
final String pathname = "/proc/self/status";
final String resultPrefix = "Cpus_allowed:";
File file = new File(pathname);
String line = "<NO LINE READ>";
String allowedCPU = "";
Integer allowedMask = null;
BufferedReader bufReader = null;
try {
bufReader = new BufferedReader(new FileReader(file));
while ((line = bufReader.readLine()) != null) {
if (line.startsWith(resultPrefix)) {
allowedMask = Integer.valueOf(line.substring(resultPrefix.length()).trim(), 16);
allowedCPU = bufReader.readLine();
break;
}
}
} catch (RuntimeException e) {
throw new IOException(
"Invalid number in " + pathname + " line: \"" + line + "\": " + e.getMessage());
} finally {
if (bufReader != null) {
bufReader.close();
}
}
if (allowedMask == null) {
throw new IOException(pathname + " missing " + resultPrefix + " line");
}
Log.i(TAG, allowedCPU);
return allowedMask;
}
}
| tensorflow/tensorflow | tensorflow/lite/java/ovic/demo/app/OvicBenchmarkerActivity.java |
2,705 | /*
* Copyright 2002-2020 the original author or authors.
*
* 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
*
* https://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 org.springframework.http;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
import org.springframework.util.MimeTypeUtils;
/**
* Benchmarks for parsing Media Types using {@link MediaType}.
* <p>{@code MediaType is using }{@link MimeTypeUtils} has an internal parser only accessible through a package private method.
* The publicly accessible method is backed by a LRUCache for better performance.
*
* @author Brian Clozel
* @see MimeTypeUtils
*/
@BenchmarkMode(Mode.Throughput)
public class MediaTypeBenchmark {
@Benchmark
public void parseAllMediaTypes(BenchmarkData data, Blackhole bh) {
for (String type : data.mediaTypes) {
bh.consume(MediaType.parseMediaType(type));
}
}
@Benchmark
public void parseSomeMediaTypes(BenchmarkData data, Blackhole bh) {
for (String type : data.requestedMediaTypes) {
bh.consume(MediaType.parseMediaType(type));
}
}
/**
* Benchmark data holding typical raw Media Types.
* A {@code customTypesCount} parameter can be used to pad the list with artificial types.
* The {@param requestedTypeCount} parameter allows to choose the number of requested types at runtime,
* since we don't want to use all available types in the cache in some benchmarks.
*/
@State(Scope.Benchmark)
public static class BenchmarkData {
@Param({"40"})
public int customTypesCount;
@Param({"10"})
public int requestedTypeCount;
public List<String> mediaTypes;
public List<String> requestedMediaTypes;
@Setup(Level.Trial)
public void fillCache() {
this.mediaTypes = new ArrayList<>();
// Add 25 common MIME types
this.mediaTypes.addAll(Arrays.asList(
"application/json",
"application/octet-stream",
"application/pdf",
"application/problem+json",
"application/xhtml+xml",
"application/rss+xml",
"application/x-ndjson",
"application/xml;q=0.9",
"application/atom+xml",
"application/cbor",
"application/x-www-form-urlencoded",
"*/*",
"image/gif",
"image/jpeg",
"image/webp",
"image/png",
"image/apng",
"text/plain",
"text/html",
"text/xml",
"text/event-stream",
"text/markdown",
"*/*;q=0.8",
"multipart/form-data",
"multipart/mixed"
));
// Add custom types, allowing to fill the LRU cache (which has a default size of 64)
IntStream.range(0, this.customTypesCount).forEach(i -> this.mediaTypes.add("custom/type" + i));
this.requestedMediaTypes = this.mediaTypes.subList(0, this.requestedTypeCount);
// ensure that all known MIME types are parsed once and cached
this.mediaTypes.forEach(MediaType::parseMediaType);
}
}
}
| spring-projects/spring-framework | spring-web/src/jmh/java/org/springframework/http/MediaTypeBenchmark.java |
2,706 | /*
* Copyright 2016 The Netty Project
*
* The Netty Project licenses this file to you 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:
*
* https://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 io.netty.handler.codec;
import io.netty.microbench.util.AbstractMicrobenchmark;
import io.netty.util.internal.RecyclableArrayList;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import java.util.ArrayList;
import java.util.List;
@State(Scope.Benchmark)
public class CodecOutputListBenchmark extends AbstractMicrobenchmark {
private static final Object ELEMENT = new Object();
private CodecOutputList codecOutputList;
private RecyclableArrayList recycleableArrayList;
private List<Object> arrayList;
@Param({ "1", "4" })
public int elements;
@TearDown
public void destroy() {
codecOutputList.recycle();
recycleableArrayList.recycle();
}
@Benchmark
public void codecOutList() {
codecOutputList = CodecOutputList.newInstance();
benchmarkAddAndClear(codecOutputList, elements);
}
@Benchmark
public void recyclableArrayList() {
recycleableArrayList = RecyclableArrayList.newInstance(16);
benchmarkAddAndClear(recycleableArrayList, elements);
}
@Benchmark
public void arrayList() {
arrayList = new ArrayList<Object>(16);
benchmarkAddAndClear(arrayList, elements);
}
private static void benchmarkAddAndClear(List<Object> list, int elements) {
for (int i = 0; i < elements; i++) {
list.add(ELEMENT);
}
list.clear();
}
}
| netty/netty | microbench/src/main/java/io/netty/handler/codec/CodecOutputListBenchmark.java |
2,707 | /*
* Copyright (C)2009-2014, 2016-2019, 2021, 2023 D. R. Commander.
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the libjpeg-turbo Project nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS",
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
import java.util.*;
import org.libjpegturbo.turbojpeg.*;
final class TJBench {
private TJBench() {}
private static int flags = 0, quiet = 0, pf = TJ.PF_BGR, yuvAlign = 1;
private static boolean compOnly, decompOnly, doTile, doYUV, write = true;
static final String[] PIXFORMATSTR = {
"RGB", "BGR", "RGBX", "BGRX", "XBGR", "XRGB", "GRAY"
};
static final String[] SUBNAME_LONG = {
"4:4:4", "4:2:2", "4:2:0", "GRAY", "4:4:0", "4:1:1"
};
static final String[] SUBNAME = {
"444", "422", "420", "GRAY", "440", "411"
};
static final String[] CSNAME = {
"RGB", "YCbCr", "GRAY", "CMYK", "YCCK"
};
private static TJScalingFactor sf;
private static int xformOp = TJTransform.OP_NONE, xformOpt = 0;
private static double benchTime = 5.0, warmup = 1.0;
static double getTime() {
return (double)System.nanoTime() / 1.0e9;
}
private static String tjErrorMsg;
private static int tjErrorCode = -1;
static void handleTJException(TJException e) throws TJException {
String errorMsg = e.getMessage();
int errorCode = e.getErrorCode();
if ((flags & TJ.FLAG_STOPONWARNING) == 0 &&
errorCode == TJ.ERR_WARNING) {
if (tjErrorMsg == null || !tjErrorMsg.equals(errorMsg) ||
tjErrorCode != errorCode) {
tjErrorMsg = errorMsg;
tjErrorCode = errorCode;
System.out.println("WARNING: " + errorMsg);
}
} else
throw e;
}
static String formatName(int subsamp, int cs) {
if (cs == TJ.CS_YCbCr)
return SUBNAME_LONG[subsamp];
else if (cs == TJ.CS_YCCK)
return CSNAME[cs] + " " + SUBNAME_LONG[subsamp];
else
return CSNAME[cs];
}
static String sigFig(double val, int figs) {
String format;
int digitsAfterDecimal = figs - (int)Math.ceil(Math.log10(Math.abs(val)));
if (digitsAfterDecimal < 1)
format = new String("%.0f");
else
format = new String("%." + digitsAfterDecimal + "f");
return String.format(format, val);
}
static byte[] loadImage(String fileName, int[] w, int[] h, int pixelFormat)
throws Exception {
BufferedImage img = ImageIO.read(new File(fileName));
if (img == null)
throw new Exception("Could not read " + fileName);
w[0] = img.getWidth();
h[0] = img.getHeight();
int[] rgb = img.getRGB(0, 0, w[0], h[0], null, 0, w[0]);
int ps = TJ.getPixelSize(pixelFormat);
int rindex = TJ.getRedOffset(pixelFormat);
int gindex = TJ.getGreenOffset(pixelFormat);
int bindex = TJ.getBlueOffset(pixelFormat);
if ((long)w[0] * (long)h[0] * (long)ps > (long)Integer.MAX_VALUE)
throw new Exception("Image is too large");
byte[] dstBuf = new byte[w[0] * h[0] * ps];
int pixels = w[0] * h[0], dstPtr = 0, rgbPtr = 0;
while (pixels-- > 0) {
dstBuf[dstPtr + rindex] = (byte)((rgb[rgbPtr] >> 16) & 0xff);
dstBuf[dstPtr + gindex] = (byte)((rgb[rgbPtr] >> 8) & 0xff);
dstBuf[dstPtr + bindex] = (byte)(rgb[rgbPtr] & 0xff);
dstPtr += ps;
rgbPtr++;
}
return dstBuf;
}
static void saveImage(String fileName, byte[] srcBuf, int w, int h,
int pixelFormat) throws Exception {
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
int pixels = w * h, srcPtr = 0;
int ps = TJ.getPixelSize(pixelFormat);
int rindex = TJ.getRedOffset(pixelFormat);
int gindex = TJ.getGreenOffset(pixelFormat);
int bindex = TJ.getBlueOffset(pixelFormat);
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++, srcPtr += ps) {
int pixel = (srcBuf[srcPtr + rindex] & 0xff) << 16 |
(srcBuf[srcPtr + gindex] & 0xff) << 8 |
(srcBuf[srcPtr + bindex] & 0xff);
img.setRGB(x, y, pixel);
}
}
ImageIO.write(img, "bmp", new File(fileName));
}
/* Decompression test */
static void decomp(byte[] srcBuf, byte[][] jpegBuf, int[] jpegSize,
byte[] dstBuf, int w, int h, int subsamp, int jpegQual,
String fileName, int tilew, int tileh) throws Exception {
String qualStr = new String(""), sizeStr, tempStr;
TJDecompressor tjd;
double elapsed, elapsedDecode;
int ps = TJ.getPixelSize(pf), i, iter = 0;
int scaledw = sf.getScaled(w);
int scaledh = sf.getScaled(h);
int pitch = scaledw * ps;
YUVImage yuvImage = null;
if (jpegQual > 0)
qualStr = new String("_Q" + jpegQual);
tjd = new TJDecompressor();
if (dstBuf == null) {
if ((long)pitch * (long)scaledh > (long)Integer.MAX_VALUE)
throw new Exception("Image is too large");
dstBuf = new byte[pitch * scaledh];
}
/* Set the destination buffer to gray so we know whether the decompressor
attempted to write to it */
Arrays.fill(dstBuf, (byte)127);
if (doYUV) {
int width = doTile ? tilew : scaledw;
int height = doTile ? tileh : scaledh;
yuvImage = new YUVImage(width, yuvAlign, height, subsamp);
Arrays.fill(yuvImage.getBuf(), (byte)127);
}
/* Benchmark */
iter = -1;
elapsed = elapsedDecode = 0.0;
while (true) {
int tile = 0;
double start = getTime();
for (int y = 0; y < h; y += tileh) {
for (int x = 0; x < w; x += tilew, tile++) {
int width = doTile ? Math.min(tilew, w - x) : scaledw;
int height = doTile ? Math.min(tileh, h - y) : scaledh;
try {
tjd.setSourceImage(jpegBuf[tile], jpegSize[tile]);
} catch (TJException e) { handleTJException(e); }
if (doYUV) {
yuvImage.setBuf(yuvImage.getBuf(), width, yuvAlign, height,
subsamp);
try {
tjd.decompressToYUV(yuvImage, flags);
} catch (TJException e) { handleTJException(e); }
double startDecode = getTime();
tjd.setSourceImage(yuvImage);
try {
tjd.decompress(dstBuf, x, y, width, pitch, height, pf, flags);
} catch (TJException e) { handleTJException(e); }
if (iter >= 0)
elapsedDecode += getTime() - startDecode;
} else {
try {
tjd.decompress(dstBuf, x, y, width, pitch, height, pf, flags);
} catch (TJException e) { handleTJException(e); }
}
}
}
elapsed += getTime() - start;
if (iter >= 0) {
iter++;
if (elapsed >= benchTime)
break;
} else if (elapsed >= warmup) {
iter = 0;
elapsed = elapsedDecode = 0.0;
}
}
if (doYUV)
elapsed -= elapsedDecode;
tjd = null;
for (i = 0; i < jpegBuf.length; i++)
jpegBuf[i] = null;
jpegBuf = null; jpegSize = null;
System.gc();
if (quiet != 0) {
System.out.format("%-6s%s",
sigFig((double)(w * h) / 1000000. *
(double)iter / elapsed, 4),
quiet == 2 ? "\n" : " ");
if (doYUV)
System.out.format("%s\n",
sigFig((double)(w * h) / 1000000. *
(double)iter / elapsedDecode, 4));
else if (quiet != 2)
System.out.print("\n");
} else {
System.out.format("%s --> Frame rate: %f fps\n",
(doYUV ? "Decomp to YUV" : "Decompress "),
(double)iter / elapsed);
System.out.format(" Throughput: %f Megapixels/sec\n",
(double)(w * h) / 1000000. * (double)iter / elapsed);
if (doYUV) {
System.out.format("YUV Decode --> Frame rate: %f fps\n",
(double)iter / elapsedDecode);
System.out.format(" Throughput: %f Megapixels/sec\n",
(double)(w * h) / 1000000. *
(double)iter / elapsedDecode);
}
}
if (!write) return;
if (sf.getNum() != 1 || sf.getDenom() != 1)
sizeStr = new String(sf.getNum() + "_" + sf.getDenom());
else if (tilew != w || tileh != h)
sizeStr = new String(tilew + "x" + tileh);
else
sizeStr = new String("full");
if (decompOnly)
tempStr = new String(fileName + "_" + sizeStr + ".bmp");
else
tempStr = new String(fileName + "_" + SUBNAME[subsamp] + qualStr +
"_" + sizeStr + ".bmp");
saveImage(tempStr, dstBuf, scaledw, scaledh, pf);
int ndx = tempStr.lastIndexOf('.');
tempStr = new String(tempStr.substring(0, ndx) + "-err.bmp");
if (srcBuf != null && sf.getNum() == 1 && sf.getDenom() == 1) {
if (quiet == 0)
System.out.println("Compression error written to " + tempStr + ".");
if (subsamp == TJ.SAMP_GRAY) {
for (int y = 0, index = 0; y < h; y++, index += pitch) {
for (int x = 0, index2 = index; x < w; x++, index2 += ps) {
int rindex = index2 + TJ.getRedOffset(pf);
int gindex = index2 + TJ.getGreenOffset(pf);
int bindex = index2 + TJ.getBlueOffset(pf);
int lum = (int)((double)(srcBuf[rindex] & 0xff) * 0.299 +
(double)(srcBuf[gindex] & 0xff) * 0.587 +
(double)(srcBuf[bindex] & 0xff) * 0.114 + 0.5);
if (lum > 255) lum = 255;
if (lum < 0) lum = 0;
dstBuf[rindex] = (byte)Math.abs((dstBuf[rindex] & 0xff) - lum);
dstBuf[gindex] = (byte)Math.abs((dstBuf[gindex] & 0xff) - lum);
dstBuf[bindex] = (byte)Math.abs((dstBuf[bindex] & 0xff) - lum);
}
}
} else {
for (int y = 0; y < h; y++)
for (int x = 0; x < w * ps; x++)
dstBuf[pitch * y + x] =
(byte)Math.abs((dstBuf[pitch * y + x] & 0xff) -
(srcBuf[pitch * y + x] & 0xff));
}
saveImage(tempStr, dstBuf, w, h, pf);
}
}
static void fullTest(byte[] srcBuf, int w, int h, int subsamp, int jpegQual,
String fileName) throws Exception {
TJCompressor tjc;
byte[] tmpBuf;
byte[][] jpegBuf;
int[] jpegSize;
double start, elapsed, elapsedEncode;
int totalJpegSize = 0, tilew, tileh, i, iter;
int ps = TJ.getPixelSize(pf);
int ntilesw = 1, ntilesh = 1, pitch = w * ps;
String pfStr = PIXFORMATSTR[pf];
YUVImage yuvImage = null;
if ((long)pitch * (long)h > (long)Integer.MAX_VALUE)
throw new Exception("Image is too large");
tmpBuf = new byte[pitch * h];
if (quiet == 0)
System.out.format(">>>>> %s (%s) <--> JPEG %s Q%d <<<<<\n", pfStr,
(flags & TJ.FLAG_BOTTOMUP) != 0 ?
"Bottom-up" : "Top-down",
SUBNAME_LONG[subsamp], jpegQual);
tjc = new TJCompressor();
for (tilew = doTile ? 8 : w, tileh = doTile ? 8 : h; ;
tilew *= 2, tileh *= 2) {
if (tilew > w)
tilew = w;
if (tileh > h)
tileh = h;
ntilesw = (w + tilew - 1) / tilew;
ntilesh = (h + tileh - 1) / tileh;
jpegBuf = new byte[ntilesw * ntilesh][TJ.bufSize(tilew, tileh, subsamp)];
jpegSize = new int[ntilesw * ntilesh];
/* Compression test */
if (quiet == 1)
System.out.format("%-4s (%s) %-5s %-3d ", pfStr,
(flags & TJ.FLAG_BOTTOMUP) != 0 ? "BU" : "TD",
SUBNAME_LONG[subsamp], jpegQual);
for (i = 0; i < h; i++)
System.arraycopy(srcBuf, w * ps * i, tmpBuf, pitch * i, w * ps);
tjc.setJPEGQuality(jpegQual);
tjc.setSubsamp(subsamp);
if (doYUV) {
yuvImage = new YUVImage(tilew, yuvAlign, tileh, subsamp);
Arrays.fill(yuvImage.getBuf(), (byte)127);
}
/* Benchmark */
iter = -1;
elapsed = elapsedEncode = 0.0;
while (true) {
int tile = 0;
totalJpegSize = 0;
start = getTime();
for (int y = 0; y < h; y += tileh) {
for (int x = 0; x < w; x += tilew, tile++) {
int width = Math.min(tilew, w - x);
int height = Math.min(tileh, h - y);
tjc.setSourceImage(srcBuf, x, y, width, pitch, height, pf);
if (doYUV) {
double startEncode = getTime();
yuvImage.setBuf(yuvImage.getBuf(), width, yuvAlign, height,
subsamp);
tjc.encodeYUV(yuvImage, flags);
if (iter >= 0)
elapsedEncode += getTime() - startEncode;
tjc.setSourceImage(yuvImage);
}
tjc.compress(jpegBuf[tile], flags);
jpegSize[tile] = tjc.getCompressedSize();
totalJpegSize += jpegSize[tile];
}
}
elapsed += getTime() - start;
if (iter >= 0) {
iter++;
if (elapsed >= benchTime)
break;
} else if (elapsed >= warmup) {
iter = 0;
elapsed = elapsedEncode = 0.0;
}
}
if (doYUV)
elapsed -= elapsedEncode;
if (quiet == 1)
System.out.format("%-5d %-5d ", tilew, tileh);
if (quiet != 0) {
if (doYUV)
System.out.format("%-6s%s",
sigFig((double)(w * h) / 1000000. *
(double)iter / elapsedEncode, 4),
quiet == 2 ? "\n" : " ");
System.out.format("%-6s%s",
sigFig((double)(w * h) / 1000000. *
(double)iter / elapsed, 4),
quiet == 2 ? "\n" : " ");
System.out.format("%-6s%s",
sigFig((double)(w * h * ps) / (double)totalJpegSize,
4),
quiet == 2 ? "\n" : " ");
} else {
System.out.format("\n%s size: %d x %d\n", doTile ? "Tile" : "Image",
tilew, tileh);
if (doYUV) {
System.out.format("Encode YUV --> Frame rate: %f fps\n",
(double)iter / elapsedEncode);
System.out.format(" Output image size: %d bytes\n",
yuvImage.getSize());
System.out.format(" Compression ratio: %f:1\n",
(double)(w * h * ps) / (double)yuvImage.getSize());
System.out.format(" Throughput: %f Megapixels/sec\n",
(double)(w * h) / 1000000. *
(double)iter / elapsedEncode);
System.out.format(" Output bit stream: %f Megabits/sec\n",
(double)yuvImage.getSize() * 8. / 1000000. *
(double)iter / elapsedEncode);
}
System.out.format("%s --> Frame rate: %f fps\n",
doYUV ? "Comp from YUV" : "Compress ",
(double)iter / elapsed);
System.out.format(" Output image size: %d bytes\n",
totalJpegSize);
System.out.format(" Compression ratio: %f:1\n",
(double)(w * h * ps) / (double)totalJpegSize);
System.out.format(" Throughput: %f Megapixels/sec\n",
(double)(w * h) / 1000000. * (double)iter / elapsed);
System.out.format(" Output bit stream: %f Megabits/sec\n",
(double)totalJpegSize * 8. / 1000000. *
(double)iter / elapsed);
}
if (tilew == w && tileh == h && write) {
String tempStr = fileName + "_" + SUBNAME[subsamp] + "_" + "Q" +
jpegQual + ".jpg";
FileOutputStream fos = new FileOutputStream(tempStr);
fos.write(jpegBuf[0], 0, jpegSize[0]);
fos.close();
if (quiet == 0)
System.out.println("Reference image written to " + tempStr);
}
/* Decompression test */
if (!compOnly)
decomp(srcBuf, jpegBuf, jpegSize, tmpBuf, w, h, subsamp, jpegQual,
fileName, tilew, tileh);
else if (quiet == 1)
System.out.println("N/A");
if (tilew == w && tileh == h) break;
}
}
static void decompTest(String fileName) throws Exception {
TJTransformer tjt;
byte[][] jpegBuf = null;
byte[] srcBuf;
int[] jpegSize = null;
int totalJpegSize;
double start, elapsed;
int ps = TJ.getPixelSize(pf), tile, x, y, iter;
// Original image
int w = 0, h = 0, ntilesw = 1, ntilesh = 1, subsamp = -1, cs = -1;
// Transformed image
int minTile, tw, th, ttilew, ttileh, tntilesw, tntilesh, tsubsamp;
FileInputStream fis = new FileInputStream(fileName);
if (fis.getChannel().size() > (long)Integer.MAX_VALUE)
throw new Exception("Image is too large");
int srcSize = (int)fis.getChannel().size();
srcBuf = new byte[srcSize];
fis.read(srcBuf, 0, srcSize);
fis.close();
int index = fileName.lastIndexOf('.');
if (index >= 0)
fileName = new String(fileName.substring(0, index));
tjt = new TJTransformer();
try {
tjt.setSourceImage(srcBuf, srcSize);
} catch (TJException e) { handleTJException(e); }
w = tjt.getWidth();
h = tjt.getHeight();
subsamp = tjt.getSubsamp();
cs = tjt.getColorspace();
if (quiet == 1) {
System.out.println("All performance values in Mpixels/sec\n");
System.out.format("Pixel JPEG JPEG %s %s Xform Comp Decomp ",
(doTile ? "Tile " : "Image"),
(doTile ? "Tile " : "Image"));
if (doYUV)
System.out.print("Decode");
System.out.print("\n");
System.out.print("Format CS Subsamp Width Height Perf Ratio Perf ");
if (doYUV)
System.out.print("Perf");
System.out.println("\n");
} else if (quiet == 0)
System.out.format(">>>>> JPEG %s --> %s (%s) <<<<<\n",
formatName(subsamp, cs), PIXFORMATSTR[pf],
(flags & TJ.FLAG_BOTTOMUP) != 0 ?
"Bottom-up" : "Top-down");
minTile = Math.max(TJ.getMCUWidth(subsamp), TJ.getMCUHeight(subsamp));
for (int tilew = doTile ? minTile : w, tileh = doTile ? minTile : h; ;
tilew *= 2, tileh *= 2) {
if (tilew > w)
tilew = w;
if (tileh > h)
tileh = h;
ntilesw = (w + tilew - 1) / tilew;
ntilesh = (h + tileh - 1) / tileh;
tw = w; th = h; ttilew = tilew; ttileh = tileh;
if (quiet == 0) {
System.out.format("\n%s size: %d x %d", (doTile ? "Tile" : "Image"),
ttilew, ttileh);
if (sf.getNum() != 1 || sf.getDenom() != 1)
System.out.format(" --> %d x %d", sf.getScaled(tw),
sf.getScaled(th));
System.out.println("");
} else if (quiet == 1) {
System.out.format("%-4s (%s) %-5s %-5s ", PIXFORMATSTR[pf],
(flags & TJ.FLAG_BOTTOMUP) != 0 ? "BU" : "TD",
CSNAME[cs], SUBNAME_LONG[subsamp]);
System.out.format("%-5d %-5d ", tilew, tileh);
}
tsubsamp = subsamp;
if (doTile || xformOp != TJTransform.OP_NONE || xformOpt != 0) {
if (xformOp == TJTransform.OP_TRANSPOSE ||
xformOp == TJTransform.OP_TRANSVERSE ||
xformOp == TJTransform.OP_ROT90 ||
xformOp == TJTransform.OP_ROT270) {
tw = h; th = w; ttilew = tileh; ttileh = tilew;
}
if ((xformOpt & TJTransform.OPT_GRAY) != 0)
tsubsamp = TJ.SAMP_GRAY;
if (xformOp == TJTransform.OP_HFLIP ||
xformOp == TJTransform.OP_ROT180)
tw = tw - (tw % TJ.getMCUWidth(tsubsamp));
if (xformOp == TJTransform.OP_VFLIP ||
xformOp == TJTransform.OP_ROT180)
th = th - (th % TJ.getMCUHeight(tsubsamp));
if (xformOp == TJTransform.OP_TRANSVERSE ||
xformOp == TJTransform.OP_ROT90)
tw = tw - (tw % TJ.getMCUHeight(tsubsamp));
if (xformOp == TJTransform.OP_TRANSVERSE ||
xformOp == TJTransform.OP_ROT270)
th = th - (th % TJ.getMCUWidth(tsubsamp));
tntilesw = (tw + ttilew - 1) / ttilew;
tntilesh = (th + ttileh - 1) / ttileh;
if (xformOp == TJTransform.OP_TRANSPOSE ||
xformOp == TJTransform.OP_TRANSVERSE ||
xformOp == TJTransform.OP_ROT90 ||
xformOp == TJTransform.OP_ROT270) {
if (tsubsamp == TJ.SAMP_422)
tsubsamp = TJ.SAMP_440;
else if (tsubsamp == TJ.SAMP_440)
tsubsamp = TJ.SAMP_422;
}
TJTransform[] t = new TJTransform[tntilesw * tntilesh];
jpegBuf =
new byte[tntilesw * tntilesh][TJ.bufSize(ttilew, ttileh, subsamp)];
for (y = 0, tile = 0; y < th; y += ttileh) {
for (x = 0; x < tw; x += ttilew, tile++) {
t[tile] = new TJTransform();
t[tile].width = Math.min(ttilew, tw - x);
t[tile].height = Math.min(ttileh, th - y);
t[tile].x = x;
t[tile].y = y;
t[tile].op = xformOp;
t[tile].options = xformOpt | TJTransform.OPT_TRIM;
if ((t[tile].options & TJTransform.OPT_NOOUTPUT) != 0 &&
jpegBuf[tile] != null)
jpegBuf[tile] = null;
}
}
iter = -1;
elapsed = 0.;
while (true) {
start = getTime();
try {
tjt.transform(jpegBuf, t, flags);
} catch (TJException e) { handleTJException(e); }
jpegSize = tjt.getTransformedSizes();
elapsed += getTime() - start;
if (iter >= 0) {
iter++;
if (elapsed >= benchTime)
break;
} else if (elapsed >= warmup) {
iter = 0;
elapsed = 0.0;
}
}
t = null;
for (tile = 0, totalJpegSize = 0; tile < tntilesw * tntilesh; tile++)
totalJpegSize += jpegSize[tile];
if (quiet != 0) {
System.out.format("%-6s%s%-6s%s",
sigFig((double)(w * h) / 1000000. / elapsed, 4),
quiet == 2 ? "\n" : " ",
sigFig((double)(w * h * ps) /
(double)totalJpegSize, 4),
quiet == 2 ? "\n" : " ");
} else {
System.out.format("Transform --> Frame rate: %f fps\n",
1.0 / elapsed);
System.out.format(" Output image size: %d bytes\n",
totalJpegSize);
System.out.format(" Compression ratio: %f:1\n",
(double)(w * h * ps) / (double)totalJpegSize);
System.out.format(" Throughput: %f Megapixels/sec\n",
(double)(w * h) / 1000000. / elapsed);
System.out.format(" Output bit stream: %f Megabits/sec\n",
(double)totalJpegSize * 8. / 1000000. / elapsed);
}
} else {
if (quiet == 1)
System.out.print("N/A N/A ");
jpegBuf = new byte[1][TJ.bufSize(ttilew, ttileh, subsamp)];
jpegSize = new int[1];
jpegBuf[0] = srcBuf;
jpegSize[0] = srcSize;
}
if (w == tilew)
ttilew = tw;
if (h == tileh)
ttileh = th;
if ((xformOpt & TJTransform.OPT_NOOUTPUT) == 0)
decomp(null, jpegBuf, jpegSize, null, tw, th, tsubsamp, 0,
fileName, ttilew, ttileh);
else if (quiet == 1)
System.out.println("N/A");
jpegBuf = null;
jpegSize = null;
if (tilew == w && tileh == h) break;
}
}
static void usage() throws Exception {
int i;
TJScalingFactor[] scalingFactors = TJ.getScalingFactors();
int nsf = scalingFactors.length;
String className = new TJBench().getClass().getName();
System.out.println("\nUSAGE: java " + className);
System.out.println(" <Inputimage (BMP)> <Quality> [options]\n");
System.out.println(" java " + className);
System.out.println(" <Inputimage (JPG)> [options]\n");
System.out.println("Options:\n");
System.out.println("-bottomup = Use bottom-up row order for packed-pixel source/destination buffers");
System.out.println("-tile = Compress/transform the input image into separate JPEG tiles of varying");
System.out.println(" sizes (useful for measuring JPEG overhead)");
System.out.println("-rgb, -bgr, -rgbx, -bgrx, -xbgr, -xrgb =");
System.out.println(" Use the specified pixel format for packed-pixel source/destination buffers");
System.out.println(" [default = BGR]");
System.out.println("-fastupsample = Use the fastest chrominance upsampling algorithm available");
System.out.println("-fastdct = Use the fastest DCT/IDCT algorithm available");
System.out.println("-accuratedct = Use the most accurate DCT/IDCT algorithm available");
System.out.println("-progressive = Use progressive entropy coding in JPEG images generated by");
System.out.println(" compression and transform operations");
System.out.println("-subsamp <s> = When compressing, use the specified level of chrominance");
System.out.println(" subsampling (<s> = 444, 422, 440, 420, 411, or GRAY) [default = test");
System.out.println(" Grayscale, 4:2:0, 4:2:2, and 4:4:4 in sequence]");
System.out.println("-quiet = Output results in tabular rather than verbose format");
System.out.println("-yuv = Compress from/decompress to intermediate planar YUV images");
System.out.println("-yuvpad <p> = The number of bytes by which each row in each plane of an");
System.out.println(" intermediate YUV image is evenly divisible (must be a power of 2)");
System.out.println(" [default = 1]");
System.out.println("-scale M/N = When decompressing, scale the width/height of the JPEG image by a");
System.out.print(" factor of M/N (M/N = ");
for (i = 0; i < nsf; i++) {
System.out.format("%d/%d", scalingFactors[i].getNum(),
scalingFactors[i].getDenom());
if (nsf == 2 && i != nsf - 1)
System.out.print(" or ");
else if (nsf > 2) {
if (i != nsf - 1)
System.out.print(", ");
if (i == nsf - 2)
System.out.print("or ");
}
if (i % 8 == 0 && i != 0)
System.out.print("\n ");
}
System.out.println(")");
System.out.println("-hflip, -vflip, -transpose, -transverse, -rot90, -rot180, -rot270 =");
System.out.println(" Perform the specified lossless transform operation on the input image");
System.out.println(" prior to decompression (these operations are mutually exclusive)");
System.out.println("-grayscale = Transform the input image into a grayscale JPEG image prior to");
System.out.println(" decompression (can be combined with the other transform operations above)");
System.out.println("-copynone = Do not copy any extra markers (including EXIF and ICC profile data)");
System.out.println(" when transforming the input image");
System.out.println("-benchtime <t> = Run each benchmark for at least <t> seconds [default = 5.0]");
System.out.println("-warmup <t> = Run each benchmark for <t> seconds [default = 1.0] prior to");
System.out.println(" starting the timer, in order to prime the caches and thus improve the");
System.out.println(" consistency of the benchmark results");
System.out.println("-componly = Stop after running compression tests. Do not test decompression.");
System.out.println("-nowrite = Do not write reference or output images (improves consistency of");
System.out.println(" benchmark results)");
System.out.println("-limitscans = Refuse to decompress or transform progressive JPEG images that");
System.out.println(" have an unreasonably large number of scans");
System.out.println("-stoponwarning = Immediately discontinue the current");
System.out.println(" compression/decompression/transform operation if a warning (non-fatal");
System.out.println(" error) occurs\n");
System.out.println("NOTE: If the quality is specified as a range (e.g. 90-100), a separate");
System.out.println("test will be performed for all quality values in the range.\n");
System.exit(1);
}
public static void main(String[] argv) {
byte[] srcBuf = null;
int w = 0, h = 0, minQual = -1, maxQual = -1;
int minArg = 1, retval = 0;
int subsamp = -1;
try {
if (argv.length < minArg)
usage();
String tempStr = argv[0].toLowerCase();
if (tempStr.endsWith(".jpg") || tempStr.endsWith(".jpeg"))
decompOnly = true;
System.out.println("");
if (!decompOnly) {
minArg = 2;
if (argv.length < minArg)
usage();
String[] quals = argv[1].split("-", 2);
try {
minQual = Integer.parseInt(quals[0]);
} catch (NumberFormatException e) {}
if (minQual < 1 || minQual > 100)
throw new Exception("Quality must be between 1 and 100.");
if (quals.length > 1) {
try {
maxQual = Integer.parseInt(quals[1]);
} catch (NumberFormatException e) {}
}
if (maxQual < 1 || maxQual > 100 || maxQual < minQual)
maxQual = minQual;
}
if (argv.length > minArg) {
for (int i = minArg; i < argv.length; i++) {
if (argv[i].equalsIgnoreCase("-tile")) {
doTile = true; xformOpt |= TJTransform.OPT_CROP;
} else if (argv[i].equalsIgnoreCase("-fastupsample")) {
System.out.println("Using fastest upsampling algorithm\n");
flags |= TJ.FLAG_FASTUPSAMPLE;
} else if (argv[i].equalsIgnoreCase("-fastdct")) {
System.out.println("Using fastest DCT/IDCT algorithm\n");
flags |= TJ.FLAG_FASTDCT;
} else if (argv[i].equalsIgnoreCase("-accuratedct")) {
System.out.println("Using most accurate DCT/IDCT algorithm\n");
flags |= TJ.FLAG_ACCURATEDCT;
} else if (argv[i].equalsIgnoreCase("-progressive")) {
System.out.println("Using progressive entropy coding\n");
flags |= TJ.FLAG_PROGRESSIVE;
xformOpt |= TJTransform.OPT_PROGRESSIVE;
} else if (argv[i].equalsIgnoreCase("-rgb"))
pf = TJ.PF_RGB;
else if (argv[i].equalsIgnoreCase("-rgbx"))
pf = TJ.PF_RGBX;
else if (argv[i].equalsIgnoreCase("-bgr"))
pf = TJ.PF_BGR;
else if (argv[i].equalsIgnoreCase("-bgrx"))
pf = TJ.PF_BGRX;
else if (argv[i].equalsIgnoreCase("-xbgr"))
pf = TJ.PF_XBGR;
else if (argv[i].equalsIgnoreCase("-xrgb"))
pf = TJ.PF_XRGB;
else if (argv[i].equalsIgnoreCase("-bottomup"))
flags |= TJ.FLAG_BOTTOMUP;
else if (argv[i].equalsIgnoreCase("-quiet"))
quiet = 1;
else if (argv[i].equalsIgnoreCase("-qq"))
quiet = 2;
else if (argv[i].equalsIgnoreCase("-scale") && i < argv.length - 1) {
int temp1 = 0, temp2 = 0;
boolean match = false, scanned = true;
Scanner scanner = new Scanner(argv[++i]).useDelimiter("/");
try {
temp1 = scanner.nextInt();
temp2 = scanner.nextInt();
} catch (Exception e) {}
if (temp2 <= 0) temp2 = 1;
if (temp1 > 0) {
TJScalingFactor[] scalingFactors = TJ.getScalingFactors();
for (int j = 0; j < scalingFactors.length; j++) {
if ((double)temp1 / (double)temp2 ==
(double)scalingFactors[j].getNum() /
(double)scalingFactors[j].getDenom()) {
sf = scalingFactors[j];
match = true; break;
}
}
if (!match) usage();
} else
usage();
} else if (argv[i].equalsIgnoreCase("-hflip"))
xformOp = TJTransform.OP_HFLIP;
else if (argv[i].equalsIgnoreCase("-vflip"))
xformOp = TJTransform.OP_VFLIP;
else if (argv[i].equalsIgnoreCase("-transpose"))
xformOp = TJTransform.OP_TRANSPOSE;
else if (argv[i].equalsIgnoreCase("-transverse"))
xformOp = TJTransform.OP_TRANSVERSE;
else if (argv[i].equalsIgnoreCase("-rot90"))
xformOp = TJTransform.OP_ROT90;
else if (argv[i].equalsIgnoreCase("-rot180"))
xformOp = TJTransform.OP_ROT180;
else if (argv[i].equalsIgnoreCase("-rot270"))
xformOp = TJTransform.OP_ROT270;
else if (argv[i].equalsIgnoreCase("-grayscale"))
xformOpt |= TJTransform.OPT_GRAY;
else if (argv[i].equalsIgnoreCase("-nooutput"))
xformOpt |= TJTransform.OPT_NOOUTPUT;
else if (argv[i].equalsIgnoreCase("-copynone"))
xformOpt |= TJTransform.OPT_COPYNONE;
else if (argv[i].equalsIgnoreCase("-benchtime") &&
i < argv.length - 1) {
double temp = -1;
try {
temp = Double.parseDouble(argv[++i]);
} catch (NumberFormatException e) {}
if (temp > 0.0)
benchTime = temp;
else
usage();
} else if (argv[i].equalsIgnoreCase("-warmup") &&
i < argv.length - 1) {
double temp = -1;
try {
temp = Double.parseDouble(argv[++i]);
} catch (NumberFormatException e) {}
if (temp >= 0.0) {
warmup = temp;
System.out.format("Warmup time = %.1f seconds\n\n", warmup);
} else
usage();
} else if (argv[i].equalsIgnoreCase("-yuv")) {
System.out.println("Testing planar YUV encoding/decoding\n");
doYUV = true;
} else if (argv[i].equalsIgnoreCase("-yuvpad") &&
i < argv.length - 1) {
int temp = 0;
try {
temp = Integer.parseInt(argv[++i]);
} catch (NumberFormatException e) {}
if (temp >= 1 && (temp & (temp - 1)) == 0)
yuvAlign = temp;
else
usage();
} else if (argv[i].equalsIgnoreCase("-subsamp") &&
i < argv.length - 1) {
i++;
if (argv[i].toUpperCase().startsWith("G"))
subsamp = TJ.SAMP_GRAY;
else if (argv[i].equals("444"))
subsamp = TJ.SAMP_444;
else if (argv[i].equals("422"))
subsamp = TJ.SAMP_422;
else if (argv[i].equals("440"))
subsamp = TJ.SAMP_440;
else if (argv[i].equals("420"))
subsamp = TJ.SAMP_420;
else if (argv[i].equals("411"))
subsamp = TJ.SAMP_411;
else
usage();
} else if (argv[i].equalsIgnoreCase("-componly"))
compOnly = true;
else if (argv[i].equalsIgnoreCase("-nowrite"))
write = false;
else if (argv[i].equalsIgnoreCase("-limitscans"))
flags |= TJ.FLAG_LIMITSCANS;
else if (argv[i].equalsIgnoreCase("-stoponwarning"))
flags |= TJ.FLAG_STOPONWARNING;
else usage();
}
}
if (sf == null)
sf = new TJScalingFactor(1, 1);
if ((sf.getNum() != 1 || sf.getDenom() != 1) && doTile) {
System.out.println("Disabling tiled compression/decompression tests, because those tests do not");
System.out.println("work when scaled decompression is enabled.\n");
doTile = false;
xformOpt &= (~TJTransform.OPT_CROP);
}
if (!decompOnly) {
int[] width = new int[1], height = new int[1];
srcBuf = loadImage(argv[0], width, height, pf);
w = width[0]; h = height[0];
int index = -1;
if ((index = argv[0].lastIndexOf('.')) >= 0)
argv[0] = argv[0].substring(0, index);
}
if (quiet == 1 && !decompOnly) {
System.out.println("All performance values in Mpixels/sec\n");
System.out.format("Pixel JPEG JPEG %s %s ",
(doTile ? "Tile " : "Image"),
(doTile ? "Tile " : "Image"));
if (doYUV)
System.out.print("Encode ");
System.out.print("Comp Comp Decomp ");
if (doYUV)
System.out.print("Decode");
System.out.print("\n");
System.out.print("Format Subsamp Qual Width Height ");
if (doYUV)
System.out.print("Perf ");
System.out.print("Perf Ratio Perf ");
if (doYUV)
System.out.print("Perf");
System.out.println("\n");
}
if (decompOnly) {
decompTest(argv[0]);
System.out.println("");
System.exit(retval);
}
System.gc();
if (subsamp >= 0 && subsamp < TJ.NUMSAMP) {
for (int i = maxQual; i >= minQual; i--)
fullTest(srcBuf, w, h, subsamp, i, argv[0]);
System.out.println("");
} else {
for (int i = maxQual; i >= minQual; i--)
fullTest(srcBuf, w, h, TJ.SAMP_GRAY, i, argv[0]);
System.out.println("");
System.gc();
for (int i = maxQual; i >= minQual; i--)
fullTest(srcBuf, w, h, TJ.SAMP_420, i, argv[0]);
System.out.println("");
System.gc();
for (int i = maxQual; i >= minQual; i--)
fullTest(srcBuf, w, h, TJ.SAMP_422, i, argv[0]);
System.out.println("");
System.gc();
for (int i = maxQual; i >= minQual; i--)
fullTest(srcBuf, w, h, TJ.SAMP_444, i, argv[0]);
System.out.println("");
}
} catch (Exception e) {
if (e instanceof TJException) {
TJException tje = (TJException)e;
System.out.println((tje.getErrorCode() == TJ.ERR_WARNING ?
"WARNING: " : "ERROR: ") + tje.getMessage());
} else
System.out.println("ERROR: " + e.getMessage());
e.printStackTrace();
retval = -1;
}
System.exit(retval);
}
}
| mozilla/mozjpeg | java/TJBench.java |
2,709 | /*
* Copyright (C) 2007 The Guava Authors
*
* 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 com.google.common.base;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import javax.annotation.CheckForNull;
/**
* This class provides default values for all Java types, as defined by the JLS.
*
* @author Ben Yu
* @since 1.0
*/
@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class Defaults {
private Defaults() {}
private static final Double DOUBLE_DEFAULT = 0d;
private static final Float FLOAT_DEFAULT = 0f;
/**
* Returns the default value of {@code type} as defined by JLS --- {@code 0} for numbers, {@code
* false} for {@code boolean} and {@code '\0'} for {@code char}. For non-primitive types and
* {@code void}, {@code null} is returned.
*/
@SuppressWarnings("unchecked")
@CheckForNull
public static <T> T defaultValue(Class<T> type) {
checkNotNull(type);
if (type.isPrimitive()) {
if (type == boolean.class) {
return (T) Boolean.FALSE;
} else if (type == char.class) {
return (T) Character.valueOf('\0');
} else if (type == byte.class) {
return (T) Byte.valueOf((byte) 0);
} else if (type == short.class) {
return (T) Short.valueOf((short) 0);
} else if (type == int.class) {
return (T) Integer.valueOf(0);
} else if (type == long.class) {
return (T) Long.valueOf(0L);
} else if (type == float.class) {
return (T) FLOAT_DEFAULT;
} else if (type == double.class) {
return (T) DOUBLE_DEFAULT;
}
}
return null;
}
}
| google/guava | guava/src/com/google/common/base/Defaults.java |
2,710 | // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under both the GPLv2 (found in the
// COPYING file in the root directory) and Apache 2.0 License
// (found in the LICENSE.Apache file in the root directory).
/**
* Copyright (C) 2011 the original author or authors.
* See the notice.md file distributed with this work for additional
* information regarding copyright ownership.
*
* 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 org.rocksdb.benchmark;
import java.io.IOException;
import java.lang.Runnable;
import java.lang.Math;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.util.Collection;
import java.util.Date;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.rocksdb.*;
import org.rocksdb.RocksMemEnv;
import org.rocksdb.util.SizeUnit;
class Stats {
int id_;
long start_;
long finish_;
double seconds_;
long done_;
long found_;
long lastOpTime_;
long nextReport_;
long bytes_;
StringBuilder message_;
boolean excludeFromMerge_;
// TODO(yhchiang): use the following arguments:
// (Long)Flag.stats_interval
// (Integer)Flag.stats_per_interval
Stats(int id) {
id_ = id;
nextReport_ = 100;
done_ = 0;
bytes_ = 0;
seconds_ = 0;
start_ = System.nanoTime();
lastOpTime_ = start_;
finish_ = start_;
found_ = 0;
message_ = new StringBuilder("");
excludeFromMerge_ = false;
}
void merge(final Stats other) {
if (other.excludeFromMerge_) {
return;
}
done_ += other.done_;
found_ += other.found_;
bytes_ += other.bytes_;
seconds_ += other.seconds_;
if (other.start_ < start_) start_ = other.start_;
if (other.finish_ > finish_) finish_ = other.finish_;
// Just keep the messages from one thread
if (message_.length() == 0) {
message_ = other.message_;
}
}
void stop() {
finish_ = System.nanoTime();
seconds_ = (double) (finish_ - start_) * 1e-9;
}
void addMessage(String msg) {
if (message_.length() > 0) {
message_.append(" ");
}
message_.append(msg);
}
void setId(int id) { id_ = id; }
void setExcludeFromMerge() { excludeFromMerge_ = true; }
void finishedSingleOp(int bytes) {
done_++;
lastOpTime_ = System.nanoTime();
bytes_ += bytes;
if (done_ >= nextReport_) {
if (nextReport_ < 1000) {
nextReport_ += 100;
} else if (nextReport_ < 5000) {
nextReport_ += 500;
} else if (nextReport_ < 10000) {
nextReport_ += 1000;
} else if (nextReport_ < 50000) {
nextReport_ += 5000;
} else if (nextReport_ < 100000) {
nextReport_ += 10000;
} else if (nextReport_ < 500000) {
nextReport_ += 50000;
} else {
nextReport_ += 100000;
}
System.err.printf("... Task %s finished %d ops%30s\r", id_, done_, "");
}
}
void report(String name) {
// Pretend at least one op was done in case we are running a benchmark
// that does not call FinishedSingleOp().
if (done_ < 1) done_ = 1;
StringBuilder extra = new StringBuilder("");
if (bytes_ > 0) {
// Rate is computed on actual elapsed time, not the sum of per-thread
// elapsed times.
double elapsed = (finish_ - start_) * 1e-9;
extra.append(String.format("%6.1f MB/s", (bytes_ / 1048576.0) / elapsed));
}
extra.append(message_.toString());
double elapsed = (finish_ - start_);
double throughput = (double) done_ / (elapsed * 1e-9);
System.out.format("%-12s : %11.3f micros/op %d ops/sec;%s%s\n",
name, (elapsed * 1e-6) / done_,
(long) throughput, (extra.length() == 0 ? "" : " "), extra.toString());
}
}
public class DbBenchmark {
enum Order {
SEQUENTIAL,
RANDOM
}
enum DBState {
FRESH,
EXISTING
}
static {
RocksDB.loadLibrary();
}
abstract class BenchmarkTask implements Callable<Stats> {
// TODO(yhchiang): use (Integer)Flag.perf_level.
public BenchmarkTask(
int tid, long randSeed, long numEntries, long keyRange) {
tid_ = tid;
rand_ = new Random(randSeed + tid * 1000);
numEntries_ = numEntries;
keyRange_ = keyRange;
stats_ = new Stats(tid);
}
@Override public Stats call() throws RocksDBException {
stats_.start_ = System.nanoTime();
runTask();
stats_.finish_ = System.nanoTime();
return stats_;
}
abstract protected void runTask() throws RocksDBException;
protected int tid_;
protected Random rand_;
protected long numEntries_;
protected long keyRange_;
protected Stats stats_;
protected void getFixedKey(byte[] key, long sn) {
generateKeyFromLong(key, sn);
}
protected void getRandomKey(byte[] key, long range) {
generateKeyFromLong(key, Math.abs(rand_.nextLong() % range));
}
}
abstract class WriteTask extends BenchmarkTask {
public WriteTask(
int tid, long randSeed, long numEntries, long keyRange,
WriteOptions writeOpt, long entriesPerBatch) {
super(tid, randSeed, numEntries, keyRange);
writeOpt_ = writeOpt;
entriesPerBatch_ = entriesPerBatch;
maxWritesPerSecond_ = -1;
}
public WriteTask(
int tid, long randSeed, long numEntries, long keyRange,
WriteOptions writeOpt, long entriesPerBatch, long maxWritesPerSecond) {
super(tid, randSeed, numEntries, keyRange);
writeOpt_ = writeOpt;
entriesPerBatch_ = entriesPerBatch;
maxWritesPerSecond_ = maxWritesPerSecond;
}
@Override public void runTask() throws RocksDBException {
if (numEntries_ != DbBenchmark.this.num_) {
stats_.message_.append(String.format(" (%d ops)", numEntries_));
}
byte[] key = new byte[keySize_];
byte[] value = new byte[valueSize_];
try {
if (entriesPerBatch_ == 1) {
for (long i = 0; i < numEntries_; ++i) {
getKey(key, i, keyRange_);
DbBenchmark.this.gen_.generate(value);
db_.put(writeOpt_, key, value);
stats_.finishedSingleOp(keySize_ + valueSize_);
writeRateControl(i);
if (isFinished()) {
return;
}
}
} else {
for (long i = 0; i < numEntries_; i += entriesPerBatch_) {
WriteBatch batch = new WriteBatch();
for (long j = 0; j < entriesPerBatch_; j++) {
getKey(key, i + j, keyRange_);
DbBenchmark.this.gen_.generate(value);
batch.put(key, value);
stats_.finishedSingleOp(keySize_ + valueSize_);
}
db_.write(writeOpt_, batch);
batch.dispose();
writeRateControl(i);
if (isFinished()) {
return;
}
}
}
} catch (InterruptedException e) {
// thread has been terminated.
}
}
protected void writeRateControl(long writeCount)
throws InterruptedException {
if (maxWritesPerSecond_ <= 0) return;
long minInterval =
writeCount * TimeUnit.SECONDS.toNanos(1) / maxWritesPerSecond_;
long interval = System.nanoTime() - stats_.start_;
if (minInterval - interval > TimeUnit.MILLISECONDS.toNanos(1)) {
TimeUnit.NANOSECONDS.sleep(minInterval - interval);
}
}
abstract protected void getKey(byte[] key, long id, long range);
protected WriteOptions writeOpt_;
protected long entriesPerBatch_;
protected long maxWritesPerSecond_;
}
class WriteSequentialTask extends WriteTask {
public WriteSequentialTask(
int tid, long randSeed, long numEntries, long keyRange,
WriteOptions writeOpt, long entriesPerBatch) {
super(tid, randSeed, numEntries, keyRange,
writeOpt, entriesPerBatch);
}
public WriteSequentialTask(
int tid, long randSeed, long numEntries, long keyRange,
WriteOptions writeOpt, long entriesPerBatch,
long maxWritesPerSecond) {
super(tid, randSeed, numEntries, keyRange,
writeOpt, entriesPerBatch,
maxWritesPerSecond);
}
@Override protected void getKey(byte[] key, long id, long range) {
getFixedKey(key, id);
}
}
class WriteRandomTask extends WriteTask {
public WriteRandomTask(
int tid, long randSeed, long numEntries, long keyRange,
WriteOptions writeOpt, long entriesPerBatch) {
super(tid, randSeed, numEntries, keyRange,
writeOpt, entriesPerBatch);
}
public WriteRandomTask(
int tid, long randSeed, long numEntries, long keyRange,
WriteOptions writeOpt, long entriesPerBatch,
long maxWritesPerSecond) {
super(tid, randSeed, numEntries, keyRange,
writeOpt, entriesPerBatch,
maxWritesPerSecond);
}
@Override protected void getKey(byte[] key, long id, long range) {
getRandomKey(key, range);
}
}
class WriteUniqueRandomTask extends WriteTask {
static final int MAX_BUFFER_SIZE = 10000000;
public WriteUniqueRandomTask(
int tid, long randSeed, long numEntries, long keyRange,
WriteOptions writeOpt, long entriesPerBatch) {
super(tid, randSeed, numEntries, keyRange,
writeOpt, entriesPerBatch);
initRandomKeySequence();
}
public WriteUniqueRandomTask(
int tid, long randSeed, long numEntries, long keyRange,
WriteOptions writeOpt, long entriesPerBatch,
long maxWritesPerSecond) {
super(tid, randSeed, numEntries, keyRange,
writeOpt, entriesPerBatch,
maxWritesPerSecond);
initRandomKeySequence();
}
@Override protected void getKey(byte[] key, long id, long range) {
generateKeyFromLong(key, nextUniqueRandom());
}
protected void initRandomKeySequence() {
bufferSize_ = MAX_BUFFER_SIZE;
if (bufferSize_ > keyRange_) {
bufferSize_ = (int) keyRange_;
}
currentKeyCount_ = bufferSize_;
keyBuffer_ = new long[MAX_BUFFER_SIZE];
for (int k = 0; k < bufferSize_; ++k) {
keyBuffer_[k] = k;
}
}
/**
* Semi-randomly return the next unique key. It is guaranteed to be
* fully random if keyRange_ <= MAX_BUFFER_SIZE.
*/
long nextUniqueRandom() {
if (bufferSize_ == 0) {
System.err.println("bufferSize_ == 0.");
return 0;
}
int r = rand_.nextInt(bufferSize_);
// randomly pick one from the keyBuffer
long randKey = keyBuffer_[r];
if (currentKeyCount_ < keyRange_) {
// if we have not yet inserted all keys, insert next new key to [r].
keyBuffer_[r] = currentKeyCount_++;
} else {
// move the last element to [r] and decrease the size by 1.
keyBuffer_[r] = keyBuffer_[--bufferSize_];
}
return randKey;
}
int bufferSize_;
long currentKeyCount_;
long[] keyBuffer_;
}
class ReadRandomTask extends BenchmarkTask {
public ReadRandomTask(
int tid, long randSeed, long numEntries, long keyRange) {
super(tid, randSeed, numEntries, keyRange);
}
@Override public void runTask() throws RocksDBException {
byte[] key = new byte[keySize_];
byte[] value = new byte[valueSize_];
for (long i = 0; i < numEntries_; i++) {
getRandomKey(key, keyRange_);
int len = db_.get(key, value);
if (len != RocksDB.NOT_FOUND) {
stats_.found_++;
stats_.finishedSingleOp(keySize_ + valueSize_);
} else {
stats_.finishedSingleOp(keySize_);
}
if (isFinished()) {
return;
}
}
}
}
class ReadSequentialTask extends BenchmarkTask {
public ReadSequentialTask(
int tid, long randSeed, long numEntries, long keyRange) {
super(tid, randSeed, numEntries, keyRange);
}
@Override public void runTask() throws RocksDBException {
RocksIterator iter = db_.newIterator();
long i;
for (iter.seekToFirst(), i = 0;
iter.isValid() && i < numEntries_;
iter.next(), ++i) {
stats_.found_++;
stats_.finishedSingleOp(iter.key().length + iter.value().length);
if (isFinished()) {
iter.dispose();
return;
}
}
iter.dispose();
}
}
public DbBenchmark(Map<Flag, Object> flags) throws Exception {
benchmarks_ = (List<String>) flags.get(Flag.benchmarks);
num_ = (Integer) flags.get(Flag.num);
threadNum_ = (Integer) flags.get(Flag.threads);
reads_ = (Integer) (flags.get(Flag.reads) == null ?
flags.get(Flag.num) : flags.get(Flag.reads));
keySize_ = (Integer) flags.get(Flag.key_size);
valueSize_ = (Integer) flags.get(Flag.value_size);
compressionRatio_ = (Double) flags.get(Flag.compression_ratio);
useExisting_ = (Boolean) flags.get(Flag.use_existing_db);
randSeed_ = (Long) flags.get(Flag.seed);
databaseDir_ = (String) flags.get(Flag.db);
writesPerSeconds_ = (Integer) flags.get(Flag.writes_per_second);
memtable_ = (String) flags.get(Flag.memtablerep);
maxWriteBufferNumber_ = (Integer) flags.get(Flag.max_write_buffer_number);
prefixSize_ = (Integer) flags.get(Flag.prefix_size);
keysPerPrefix_ = (Integer) flags.get(Flag.keys_per_prefix);
hashBucketCount_ = (Long) flags.get(Flag.hash_bucket_count);
usePlainTable_ = (Boolean) flags.get(Flag.use_plain_table);
useMemenv_ = (Boolean) flags.get(Flag.use_mem_env);
flags_ = flags;
finishLock_ = new Object();
// options.setPrefixSize((Integer)flags_.get(Flag.prefix_size));
// options.setKeysPerPrefix((Long)flags_.get(Flag.keys_per_prefix));
compressionType_ = (String) flags.get(Flag.compression_type);
compression_ = CompressionType.NO_COMPRESSION;
try {
if (compressionType_!=null) {
final CompressionType compressionType =
CompressionType.getCompressionType(compressionType_);
if (compressionType != null &&
compressionType != CompressionType.NO_COMPRESSION) {
System.loadLibrary(compressionType.getLibraryName());
}
}
} catch (UnsatisfiedLinkError e) {
System.err.format("Unable to load %s library:%s%n" +
"No compression is used.%n",
compressionType_, e.toString());
compressionType_ = "none";
}
gen_ = new RandomGenerator(randSeed_, compressionRatio_);
}
private void prepareReadOptions(ReadOptions options) {
options.setVerifyChecksums((Boolean)flags_.get(Flag.verify_checksum));
options.setTailing((Boolean)flags_.get(Flag.use_tailing_iterator));
}
private void prepareWriteOptions(WriteOptions options) {
options.setSync((Boolean)flags_.get(Flag.sync));
options.setDisableWAL((Boolean)flags_.get(Flag.disable_wal));
}
private void prepareOptions(Options options) throws RocksDBException {
if (!useExisting_) {
options.setCreateIfMissing(true);
} else {
options.setCreateIfMissing(false);
}
if (useMemenv_) {
options.setEnv(new RocksMemEnv(Env.getDefault()));
}
switch (memtable_) {
case "skip_list":
options.setMemTableConfig(new SkipListMemTableConfig());
break;
case "vector":
options.setMemTableConfig(new VectorMemTableConfig());
break;
case "hash_linkedlist":
options.setMemTableConfig(
new HashLinkedListMemTableConfig()
.setBucketCount(hashBucketCount_));
options.useFixedLengthPrefixExtractor(prefixSize_);
break;
case "hash_skiplist":
case "prefix_hash":
options.setMemTableConfig(
new HashSkipListMemTableConfig()
.setBucketCount(hashBucketCount_));
options.useFixedLengthPrefixExtractor(prefixSize_);
break;
default:
System.err.format(
"unable to detect the specified memtable, " +
"use the default memtable factory %s%n",
options.memTableFactoryName());
break;
}
if (usePlainTable_) {
options.setTableFormatConfig(
new PlainTableConfig().setKeySize(keySize_));
} else {
BlockBasedTableConfig table_options = new BlockBasedTableConfig();
table_options.setBlockSize((Long)flags_.get(Flag.block_size))
.setBlockCacheSize((Long)flags_.get(Flag.cache_size))
.setCacheNumShardBits(
(Integer)flags_.get(Flag.cache_numshardbits));
options.setTableFormatConfig(table_options);
}
options.setWriteBufferSize(
(Long)flags_.get(Flag.write_buffer_size));
options.setMaxWriteBufferNumber(
(Integer)flags_.get(Flag.max_write_buffer_number));
options.setMaxBackgroundCompactions(
(Integer)flags_.get(Flag.max_background_compactions));
options.getEnv().setBackgroundThreads(
(Integer)flags_.get(Flag.max_background_compactions));
options.setMaxBackgroundFlushes(
(Integer)flags_.get(Flag.max_background_flushes));
options.setMaxBackgroundJobs((Integer) flags_.get(Flag.max_background_jobs));
options.setMaxOpenFiles(
(Integer)flags_.get(Flag.open_files));
options.setUseFsync(
(Boolean)flags_.get(Flag.use_fsync));
options.setWalDir(
(String)flags_.get(Flag.wal_dir));
options.setDeleteObsoleteFilesPeriodMicros(
(Integer)flags_.get(Flag.delete_obsolete_files_period_micros));
options.setTableCacheNumshardbits(
(Integer)flags_.get(Flag.table_cache_numshardbits));
options.setAllowMmapReads(
(Boolean)flags_.get(Flag.mmap_read));
options.setAllowMmapWrites(
(Boolean)flags_.get(Flag.mmap_write));
options.setAdviseRandomOnOpen(
(Boolean)flags_.get(Flag.advise_random_on_open));
options.setUseAdaptiveMutex(
(Boolean)flags_.get(Flag.use_adaptive_mutex));
options.setBytesPerSync(
(Long)flags_.get(Flag.bytes_per_sync));
options.setBloomLocality(
(Integer)flags_.get(Flag.bloom_locality));
options.setMinWriteBufferNumberToMerge(
(Integer)flags_.get(Flag.min_write_buffer_number_to_merge));
options.setMemtablePrefixBloomSizeRatio((Double) flags_.get(Flag.memtable_bloom_size_ratio));
options.setNumLevels(
(Integer)flags_.get(Flag.num_levels));
options.setTargetFileSizeBase(
(Integer)flags_.get(Flag.target_file_size_base));
options.setTargetFileSizeMultiplier((Integer)flags_.get(Flag.target_file_size_multiplier));
options.setMaxBytesForLevelBase(
(Integer)flags_.get(Flag.max_bytes_for_level_base));
options.setMaxBytesForLevelMultiplier((Double) flags_.get(Flag.max_bytes_for_level_multiplier));
options.setLevelZeroStopWritesTrigger(
(Integer)flags_.get(Flag.level0_stop_writes_trigger));
options.setLevelZeroSlowdownWritesTrigger(
(Integer)flags_.get(Flag.level0_slowdown_writes_trigger));
options.setLevelZeroFileNumCompactionTrigger(
(Integer)flags_.get(Flag.level0_file_num_compaction_trigger));
options.setMaxCompactionBytes(
(Long) flags_.get(Flag.max_compaction_bytes));
options.setDisableAutoCompactions(
(Boolean)flags_.get(Flag.disable_auto_compactions));
options.setMaxSuccessiveMerges(
(Integer)flags_.get(Flag.max_successive_merges));
options.setWalTtlSeconds((Long)flags_.get(Flag.wal_ttl_seconds));
options.setWalSizeLimitMB((Long)flags_.get(Flag.wal_size_limit_MB));
if(flags_.get(Flag.java_comparator) != null) {
options.setComparator(
(AbstractComparator)flags_.get(Flag.java_comparator));
}
/* TODO(yhchiang): enable the following parameters
options.setCompressionType((String)flags_.get(Flag.compression_type));
options.setCompressionLevel((Integer)flags_.get(Flag.compression_level));
options.setMinLevelToCompress((Integer)flags_.get(Flag.min_level_to_compress));
options.setHdfs((String)flags_.get(Flag.hdfs)); // env
options.setStatistics((Boolean)flags_.get(Flag.statistics));
options.setUniversalSizeRatio(
(Integer)flags_.get(Flag.universal_size_ratio));
options.setUniversalMinMergeWidth(
(Integer)flags_.get(Flag.universal_min_merge_width));
options.setUniversalMaxMergeWidth(
(Integer)flags_.get(Flag.universal_max_merge_width));
options.setUniversalMaxSizeAmplificationPercent(
(Integer)flags_.get(Flag.universal_max_size_amplification_percent));
options.setUniversalCompressionSizePercent(
(Integer)flags_.get(Flag.universal_compression_size_percent));
// TODO(yhchiang): add RocksDB.openForReadOnly() to enable Flag.readonly
// TODO(yhchiang): enable Flag.merge_operator by switch
options.setAccessHintOnCompactionStart(
(String)flags_.get(Flag.compaction_fadvice));
// available values of fadvice are "NONE", "NORMAL", "SEQUENTIAL", "WILLNEED" for fadvice
*/
}
private void run() throws RocksDBException {
if (!useExisting_) {
destroyDb();
}
Options options = new Options();
prepareOptions(options);
open(options);
printHeader(options);
for (String benchmark : benchmarks_) {
List<Callable<Stats>> tasks = new ArrayList<Callable<Stats>>();
List<Callable<Stats>> bgTasks = new ArrayList<Callable<Stats>>();
WriteOptions writeOpt = new WriteOptions();
prepareWriteOptions(writeOpt);
ReadOptions readOpt = new ReadOptions();
prepareReadOptions(readOpt);
int currentTaskId = 0;
boolean known = true;
switch (benchmark) {
case "fillseq":
tasks.add(new WriteSequentialTask(
currentTaskId++, randSeed_, num_, num_, writeOpt, 1));
break;
case "fillbatch":
tasks.add(
new WriteSequentialTask(currentTaskId++, randSeed_, num_, num_, writeOpt, 1000));
break;
case "fillrandom":
tasks.add(new WriteRandomTask(
currentTaskId++, randSeed_, num_, num_, writeOpt, 1));
break;
case "filluniquerandom":
tasks.add(new WriteUniqueRandomTask(
currentTaskId++, randSeed_, num_, num_, writeOpt, 1));
break;
case "fillsync":
writeOpt.setSync(true);
tasks.add(new WriteRandomTask(
currentTaskId++, randSeed_, num_ / 1000, num_ / 1000,
writeOpt, 1));
break;
case "readseq":
for (int t = 0; t < threadNum_; ++t) {
tasks.add(new ReadSequentialTask(
currentTaskId++, randSeed_, reads_ / threadNum_, num_));
}
break;
case "readrandom":
for (int t = 0; t < threadNum_; ++t) {
tasks.add(new ReadRandomTask(
currentTaskId++, randSeed_, reads_ / threadNum_, num_));
}
break;
case "readwhilewriting":
WriteTask writeTask = new WriteRandomTask(
-1, randSeed_, Long.MAX_VALUE, num_, writeOpt, 1, writesPerSeconds_);
writeTask.stats_.setExcludeFromMerge();
bgTasks.add(writeTask);
for (int t = 0; t < threadNum_; ++t) {
tasks.add(new ReadRandomTask(
currentTaskId++, randSeed_, reads_ / threadNum_, num_));
}
break;
case "readhot":
for (int t = 0; t < threadNum_; ++t) {
tasks.add(new ReadRandomTask(
currentTaskId++, randSeed_, reads_ / threadNum_, num_ / 100));
}
break;
case "delete":
destroyDb();
open(options);
break;
default:
known = false;
System.err.println("Unknown benchmark: " + benchmark);
break;
}
if (known) {
ExecutorService executor = Executors.newCachedThreadPool();
ExecutorService bgExecutor = Executors.newCachedThreadPool();
try {
// measure only the main executor time
List<Future<Stats>> bgResults = new ArrayList<Future<Stats>>();
for (Callable bgTask : bgTasks) {
bgResults.add(bgExecutor.submit(bgTask));
}
start();
List<Future<Stats>> results = executor.invokeAll(tasks);
executor.shutdown();
boolean finished = executor.awaitTermination(10, TimeUnit.SECONDS);
if (!finished) {
System.out.format(
"Benchmark %s was not finished before timeout.",
benchmark);
executor.shutdownNow();
}
setFinished(true);
bgExecutor.shutdown();
finished = bgExecutor.awaitTermination(10, TimeUnit.SECONDS);
if (!finished) {
System.out.format(
"Benchmark %s was not finished before timeout.",
benchmark);
bgExecutor.shutdownNow();
}
stop(benchmark, results, currentTaskId);
} catch (InterruptedException e) {
System.err.println(e);
}
}
writeOpt.dispose();
readOpt.dispose();
}
options.dispose();
db_.close();
}
private void printHeader(Options options) {
int kKeySize = 16;
System.out.printf("Keys: %d bytes each\n", kKeySize);
System.out.printf("Values: %d bytes each (%d bytes after compression)\n",
valueSize_,
(int) (valueSize_ * compressionRatio_ + 0.5));
System.out.printf("Entries: %d\n", num_);
System.out.printf("RawSize: %.1f MB (estimated)\n",
((double)(kKeySize + valueSize_) * num_) / SizeUnit.MB);
System.out.printf("FileSize: %.1f MB (estimated)\n",
(((kKeySize + valueSize_ * compressionRatio_) * num_) / SizeUnit.MB));
System.out.format("Memtable Factory: %s%n", options.memTableFactoryName());
System.out.format("Prefix: %d bytes%n", prefixSize_);
System.out.format("Compression: %s%n", compressionType_);
printWarnings();
System.out.printf("------------------------------------------------\n");
}
void printWarnings() {
boolean assertsEnabled = false;
assert assertsEnabled = true; // Intentional side effect!!!
if (assertsEnabled) {
System.out.printf(
"WARNING: Assertions are enabled; benchmarks unnecessarily slow\n");
}
}
private void open(Options options) throws RocksDBException {
System.out.println("Using database directory: " + databaseDir_);
db_ = RocksDB.open(options, databaseDir_);
}
private void start() {
setFinished(false);
startTime_ = System.nanoTime();
}
private void stop(
String benchmark, List<Future<Stats>> results, int concurrentThreads) {
long endTime = System.nanoTime();
double elapsedSeconds =
1.0d * (endTime - startTime_) / TimeUnit.SECONDS.toNanos(1);
Stats stats = new Stats(-1);
int taskFinishedCount = 0;
for (Future<Stats> result : results) {
if (result.isDone()) {
try {
Stats taskStats = result.get(3, TimeUnit.SECONDS);
if (!result.isCancelled()) {
taskFinishedCount++;
}
stats.merge(taskStats);
} catch (Exception e) {
// then it's not successful, the output will indicate this
}
}
}
String extra = "";
if (benchmark.indexOf("read") >= 0) {
extra = String.format(" %d / %d found; ", stats.found_, stats.done_);
} else {
extra = String.format(" %d ops done; ", stats.done_);
}
System.out.printf(
"%-16s : %11.5f micros/op; %6.1f MB/s;%s %d / %d task(s) finished.\n",
benchmark, elapsedSeconds / stats.done_ * 1e6,
(stats.bytes_ / 1048576.0) / elapsedSeconds, extra,
taskFinishedCount, concurrentThreads);
}
public void generateKeyFromLong(byte[] slice, long n) {
assert(n >= 0);
int startPos = 0;
if (keysPerPrefix_ > 0) {
long numPrefix = (num_ + keysPerPrefix_ - 1) / keysPerPrefix_;
long prefix = n % numPrefix;
int bytesToFill = Math.min(prefixSize_, 8);
for (int i = 0; i < bytesToFill; ++i) {
slice[i] = (byte) (prefix % 256);
prefix /= 256;
}
for (int i = 8; i < bytesToFill; ++i) {
slice[i] = '0';
}
startPos = bytesToFill;
}
for (int i = slice.length - 1; i >= startPos; --i) {
slice[i] = (byte) ('0' + (n % 10));
n /= 10;
}
}
private void destroyDb() {
if (db_ != null) {
db_.close();
}
// TODO(yhchiang): develop our own FileUtil
// FileUtil.deleteDir(databaseDir_);
}
private void printStats() {
}
static void printHelp() {
System.out.println("usage:");
for (Flag flag : Flag.values()) {
System.out.format(" --%s%n\t%s%n",
flag.name(),
flag.desc());
if (flag.getDefaultValue() != null) {
System.out.format("\tDEFAULT: %s%n",
flag.getDefaultValue().toString());
}
}
}
public static void main(String[] args) throws Exception {
Map<Flag, Object> flags = new EnumMap<Flag, Object>(Flag.class);
for (Flag flag : Flag.values()) {
if (flag.getDefaultValue() != null) {
flags.put(flag, flag.getDefaultValue());
}
}
for (String arg : args) {
boolean valid = false;
if (arg.equals("--help") || arg.equals("-h")) {
printHelp();
System.exit(0);
}
if (arg.startsWith("--")) {
try {
String[] parts = arg.substring(2).split("=");
if (parts.length >= 1) {
Flag key = Flag.valueOf(parts[0]);
if (key != null) {
Object value = null;
if (parts.length >= 2) {
value = key.parseValue(parts[1]);
}
flags.put(key, value);
valid = true;
}
}
}
catch (Exception e) {
}
}
if (!valid) {
System.err.println("Invalid argument " + arg);
System.exit(1);
}
}
new DbBenchmark(flags).run();
}
private enum Flag {
benchmarks(Arrays.asList("fillseq", "readrandom", "fillrandom"),
"Comma-separated list of operations to run in the specified order\n"
+ "\tActual benchmarks:\n"
+ "\t\tfillseq -- write N values in sequential key order in async mode.\n"
+ "\t\tfillrandom -- write N values in random key order in async mode.\n"
+ "\t\tfillbatch -- write N/1000 batch where each batch has 1000 values\n"
+ "\t\t in sequential key order in sync mode.\n"
+ "\t\tfillsync -- write N/100 values in random key order in sync mode.\n"
+ "\t\tfill100K -- write N/1000 100K values in random order in async mode.\n"
+ "\t\treadseq -- read N times sequentially.\n"
+ "\t\treadrandom -- read N times in random order.\n"
+ "\t\treadhot -- read N times in random order from 1% section of DB.\n"
+ "\t\treadwhilewriting -- measure the read performance of multiple readers\n"
+ "\t\t with a bg single writer. The write rate of the bg\n"
+ "\t\t is capped by --writes_per_second.\n"
+ "\tMeta Operations:\n"
+ "\t\tdelete -- delete DB") {
@Override public Object parseValue(String value) {
return new ArrayList<String>(Arrays.asList(value.split(",")));
}
},
compression_ratio(0.5d,
"Arrange to generate values that shrink to this fraction of\n" +
"\ttheir original size after compression.") {
@Override public Object parseValue(String value) {
return Double.parseDouble(value);
}
},
use_existing_db(false,
"If true, do not destroy the existing database. If you set this\n" +
"\tflag and also specify a benchmark that wants a fresh database,\n" +
"\tthat benchmark will fail.") {
@Override public Object parseValue(String value) {
return parseBoolean(value);
}
},
num(1000000,
"Number of key/values to place in database.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
threads(1,
"Number of concurrent threads to run.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
reads(null,
"Number of read operations to do. If negative, do --nums reads.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
key_size(16,
"The size of each key in bytes.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
value_size(100,
"The size of each value in bytes.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
write_buffer_size(4L * SizeUnit.MB,
"Number of bytes to buffer in memtable before compacting\n" +
"\t(initialized to default value by 'main'.)") {
@Override public Object parseValue(String value) {
return Long.parseLong(value);
}
},
max_write_buffer_number(2,
"The number of in-memory memtables. Each memtable is of size\n" +
"\twrite_buffer_size.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
prefix_size(0, "Controls the prefix size for HashSkipList, HashLinkedList,\n" +
"\tand plain table.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
keys_per_prefix(0, "Controls the average number of keys generated\n" +
"\tper prefix, 0 means no special handling of the prefix,\n" +
"\ti.e. use the prefix comes with the generated random number.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
memtablerep("skip_list",
"The memtable format. Available options are\n" +
"\tskip_list,\n" +
"\tvector,\n" +
"\thash_linkedlist,\n" +
"\thash_skiplist (prefix_hash.)") {
@Override public Object parseValue(String value) {
return value;
}
},
hash_bucket_count(SizeUnit.MB,
"The number of hash buckets used in the hash-bucket-based\n" +
"\tmemtables. Memtables that currently support this argument are\n" +
"\thash_linkedlist and hash_skiplist.") {
@Override public Object parseValue(String value) {
return Long.parseLong(value);
}
},
writes_per_second(10000,
"The write-rate of the background writer used in the\n" +
"\t`readwhilewriting` benchmark. Non-positive number indicates\n" +
"\tusing an unbounded write-rate in `readwhilewriting` benchmark.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
use_plain_table(false,
"Use plain-table sst format.") {
@Override public Object parseValue(String value) {
return parseBoolean(value);
}
},
cache_size(-1L,
"Number of bytes to use as a cache of uncompressed data.\n" +
"\tNegative means use default settings.") {
@Override public Object parseValue(String value) {
return Long.parseLong(value);
}
},
seed(0L,
"Seed base for random number generators.") {
@Override public Object parseValue(String value) {
return Long.parseLong(value);
}
},
num_levels(7,
"The total number of levels.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
numdistinct(1000L,
"Number of distinct keys to use. Used in RandomWithVerify to\n" +
"\tread/write on fewer keys so that gets are more likely to find the\n" +
"\tkey and puts are more likely to update the same key.") {
@Override public Object parseValue(String value) {
return Long.parseLong(value);
}
},
merge_keys(-1L,
"Number of distinct keys to use for MergeRandom and\n" +
"\tReadRandomMergeRandom.\n" +
"\tIf negative, there will be FLAGS_num keys.") {
@Override public Object parseValue(String value) {
return Long.parseLong(value);
}
},
bloom_locality(0,"Control bloom filter probes locality.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
duration(0,"Time in seconds for the random-ops tests to run.\n" +
"\tWhen 0 then num & reads determine the test duration.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
num_multi_db(0,
"Number of DBs used in the benchmark. 0 means single DB.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
histogram(false,"Print histogram of operation timings.") {
@Override public Object parseValue(String value) {
return parseBoolean(value);
}
},
min_write_buffer_number_to_merge(
defaultOptions_.minWriteBufferNumberToMerge(),
"The minimum number of write buffers that will be merged together\n" +
"\tbefore writing to storage. This is cheap because it is an\n" +
"\tin-memory merge. If this feature is not enabled, then all these\n" +
"\twrite buffers are flushed to L0 as separate files and this\n" +
"\tincreases read amplification because a get request has to check\n" +
"\tin all of these files. Also, an in-memory merge may result in\n" +
"\twriting less data to storage if there are duplicate records\n" +
"\tin each of these individual write buffers.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
max_background_compactions(
defaultOptions_.maxBackgroundCompactions(),
"The maximum number of concurrent background compactions\n" +
"\tthat can occur in parallel.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
max_background_flushes(
defaultOptions_.maxBackgroundFlushes(),
"The maximum number of concurrent background flushes\n" +
"\tthat can occur in parallel.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
max_background_jobs(defaultOptions_.maxBackgroundJobs(),
"The maximum number of concurrent background jobs\n"
+ "\tthat can occur in parallel.") {
@Override
public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
/* TODO(yhchiang): enable the following
compaction_style((int32_t) defaultOptions_.compactionStyle(),
"style of compaction: level-based vs universal.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},*/
universal_size_ratio(0,
"Percentage flexibility while comparing file size\n" +
"\t(for universal compaction only).") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
universal_min_merge_width(0,"The minimum number of files in a\n" +
"\tsingle compaction run (for universal compaction only).") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
universal_max_merge_width(0,"The max number of files to compact\n" +
"\tin universal style compaction.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
universal_max_size_amplification_percent(0,
"The max size amplification for universal style compaction.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
universal_compression_size_percent(-1,
"The percentage of the database to compress for universal\n" +
"\tcompaction. -1 means compress everything.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
block_size(defaultBlockBasedTableOptions_.blockSize(),
"Number of bytes in a block.") {
@Override public Object parseValue(String value) {
return Long.parseLong(value);
}
},
compressed_cache_size(-1L,
"Number of bytes to use as a cache of compressed data.") {
@Override public Object parseValue(String value) {
return Long.parseLong(value);
}
},
open_files(defaultOptions_.maxOpenFiles(),
"Maximum number of files to keep open at the same time\n" +
"\t(use default if == 0)") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
bloom_bits(-1,"Bloom filter bits per key. Negative means\n" +
"\tuse default settings.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
memtable_bloom_size_ratio(0.0d, "Ratio of memtable used by the bloom filter.\n"
+ "\t0 means no bloom filter.") {
@Override public Object parseValue(String value) {
return Double.parseDouble(value);
}
},
cache_numshardbits(-1,"Number of shards for the block cache\n" +
"\tis 2 ** cache_numshardbits. Negative means use default settings.\n" +
"\tThis is applied only if FLAGS_cache_size is non-negative.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
verify_checksum(false,"Verify checksum for every block read\n" +
"\tfrom storage.") {
@Override public Object parseValue(String value) {
return parseBoolean(value);
}
},
statistics(false,"Database statistics.") {
@Override public Object parseValue(String value) {
return parseBoolean(value);
}
},
writes(-1L, "Number of write operations to do. If negative, do\n" +
"\t--num reads.") {
@Override public Object parseValue(String value) {
return Long.parseLong(value);
}
},
sync(false,"Sync all writes to disk.") {
@Override public Object parseValue(String value) {
return parseBoolean(value);
}
},
use_fsync(false,"If true, issue fsync instead of fdatasync.") {
@Override public Object parseValue(String value) {
return parseBoolean(value);
}
},
disable_wal(false,"If true, do not write WAL for write.") {
@Override public Object parseValue(String value) {
return parseBoolean(value);
}
},
wal_dir("", "If not empty, use the given dir for WAL.") {
@Override public Object parseValue(String value) {
return value;
}
},
target_file_size_base(2 * 1048576,"Target file size at level-1") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
target_file_size_multiplier(1,
"A multiplier to compute target level-N file size (N >= 2)") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
max_bytes_for_level_base(10 * 1048576,
"Max bytes for level-1") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
max_bytes_for_level_multiplier(10.0d,
"A multiplier to compute max bytes for level-N (N >= 2)") {
@Override public Object parseValue(String value) {
return Double.parseDouble(value);
}
},
level0_stop_writes_trigger(12,"Number of files in level-0\n" +
"\tthat will trigger put stop.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
level0_slowdown_writes_trigger(8,"Number of files in level-0\n" +
"\tthat will slow down writes.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
level0_file_num_compaction_trigger(4,"Number of files in level-0\n" +
"\twhen compactions start.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
readwritepercent(90,"Ratio of reads to reads/writes (expressed\n" +
"\tas percentage) for the ReadRandomWriteRandom workload. The\n" +
"\tdefault value 90 means 90% operations out of all reads and writes\n" +
"\toperations are reads. In other words, 9 gets for every 1 put.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
mergereadpercent(70,"Ratio of merges to merges&reads (expressed\n" +
"\tas percentage) for the ReadRandomMergeRandom workload. The\n" +
"\tdefault value 70 means 70% out of all read and merge operations\n" +
"\tare merges. In other words, 7 merges for every 3 gets.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
deletepercent(2,"Percentage of deletes out of reads/writes/\n" +
"\tdeletes (used in RandomWithVerify only). RandomWithVerify\n" +
"\tcalculates writepercent as (100 - FLAGS_readwritepercent -\n" +
"\tdeletepercent), so deletepercent must be smaller than (100 -\n" +
"\tFLAGS_readwritepercent)") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
delete_obsolete_files_period_micros(0,"Option to delete\n" +
"\tobsolete files periodically. 0 means that obsolete files are\n" +
"\tdeleted after every compaction run.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
compression_type("snappy",
"Algorithm used to compress the database.") {
@Override public Object parseValue(String value) {
return value;
}
},
compression_level(-1,
"Compression level. For zlib this should be -1 for the\n" +
"\tdefault level, or between 0 and 9.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
min_level_to_compress(-1,"If non-negative, compression starts\n" +
"\tfrom this level. Levels with number < min_level_to_compress are\n" +
"\tnot compressed. Otherwise, apply compression_type to\n" +
"\tall levels.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
table_cache_numshardbits(4,"") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
stats_interval(0L, "Stats are reported every N operations when\n" +
"\tthis is greater than zero. When 0 the interval grows over time.") {
@Override public Object parseValue(String value) {
return Long.parseLong(value);
}
},
stats_per_interval(0,"Reports additional stats per interval when\n" +
"\tthis is greater than 0.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
perf_level(0,"Level of perf collection.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
soft_rate_limit(0.0d,"") {
@Override public Object parseValue(String value) {
return Double.parseDouble(value);
}
},
hard_rate_limit(0.0d,"When not equal to 0 this make threads\n" +
"\tsleep at each stats reporting interval until the compaction\n" +
"\tscore for all levels is less than or equal to this value.") {
@Override public Object parseValue(String value) {
return Double.parseDouble(value);
}
},
rate_limit_delay_max_milliseconds(1000,
"When hard_rate_limit is set then this is the max time a put will\n" +
"\tbe stalled.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
max_compaction_bytes(0L, "Limit number of bytes in one compaction to be lower than this\n" +
"\threshold. But it's not guaranteed.") {
@Override public Object parseValue(String value) {
return Long.parseLong(value);
}
},
readonly(false,"Run read only benchmarks.") {
@Override public Object parseValue(String value) {
return parseBoolean(value);
}
},
disable_auto_compactions(false,"Do not auto trigger compactions.") {
@Override public Object parseValue(String value) {
return parseBoolean(value);
}
},
wal_ttl_seconds(0L,"Set the TTL for the WAL Files in seconds.") {
@Override public Object parseValue(String value) {
return Long.parseLong(value);
}
},
wal_size_limit_MB(0L,"Set the size limit for the WAL Files\n" +
"\tin MB.") {
@Override public Object parseValue(String value) {
return Long.parseLong(value);
}
},
/* TODO(yhchiang): enable the following
direct_reads(rocksdb::EnvOptions().use_direct_reads,
"Allow direct I/O reads.") {
@Override public Object parseValue(String value) {
return parseBoolean(value);
}
},
direct_writes(rocksdb::EnvOptions().use_direct_reads,
"Allow direct I/O reads.") {
@Override public Object parseValue(String value) {
return parseBoolean(value);
}
},
*/
mmap_read(false,
"Allow reads to occur via mmap-ing files.") {
@Override public Object parseValue(String value) {
return parseBoolean(value);
}
},
mmap_write(false,
"Allow writes to occur via mmap-ing files.") {
@Override public Object parseValue(String value) {
return parseBoolean(value);
}
},
advise_random_on_open(defaultOptions_.adviseRandomOnOpen(),
"Advise random access on table file open.") {
@Override public Object parseValue(String value) {
return parseBoolean(value);
}
},
compaction_fadvice("NORMAL",
"Access pattern advice when a file is compacted.") {
@Override public Object parseValue(String value) {
return value;
}
},
use_tailing_iterator(false,
"Use tailing iterator to access a series of keys instead of get.") {
@Override public Object parseValue(String value) {
return parseBoolean(value);
}
},
use_adaptive_mutex(defaultOptions_.useAdaptiveMutex(),
"Use adaptive mutex.") {
@Override public Object parseValue(String value) {
return parseBoolean(value);
}
},
bytes_per_sync(defaultOptions_.bytesPerSync(),
"Allows OS to incrementally sync files to disk while they are\n" +
"\tbeing written, in the background. Issue one request for every\n" +
"\tbytes_per_sync written. 0 turns it off.") {
@Override public Object parseValue(String value) {
return Long.parseLong(value);
}
},
filter_deletes(false," On true, deletes use bloom-filter and drop\n" +
"\tthe delete if key not present.") {
@Override public Object parseValue(String value) {
return parseBoolean(value);
}
},
max_successive_merges(0,"Maximum number of successive merge\n" +
"\toperations on a key in the memtable.") {
@Override public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
db(getTempDir("rocksdb-jni"),
"Use the db with the following name.") {
@Override public Object parseValue(String value) {
return value;
}
},
use_mem_env(false, "Use RocksMemEnv instead of default filesystem based\n" +
"environment.") {
@Override public Object parseValue(String value) {
return parseBoolean(value);
}
},
java_comparator(null, "Class name of a Java Comparator to use instead\n" +
"\tof the default C++ ByteWiseComparatorImpl. Must be available on\n" +
"\tthe classpath") {
@Override
protected Object parseValue(final String value) {
try {
final ComparatorOptions copt = new ComparatorOptions();
final Class<AbstractComparator> clsComparator =
(Class<AbstractComparator>)Class.forName(value);
final Constructor cstr =
clsComparator.getConstructor(ComparatorOptions.class);
return cstr.newInstance(copt);
} catch(final ClassNotFoundException cnfe) {
throw new IllegalArgumentException("Java Comparator '" + value + "'" +
" not found on the classpath", cnfe);
} catch(final NoSuchMethodException nsme) {
throw new IllegalArgumentException("Java Comparator '" + value + "'" +
" does not have a public ComparatorOptions constructor", nsme);
} catch(final IllegalAccessException | InstantiationException
| InvocationTargetException ie) {
throw new IllegalArgumentException("Unable to construct Java" +
" Comparator '" + value + "'", ie);
}
}
};
private Flag(Object defaultValue, String desc) {
defaultValue_ = defaultValue;
desc_ = desc;
}
public Object getDefaultValue() {
return defaultValue_;
}
public String desc() {
return desc_;
}
public boolean parseBoolean(String value) {
if (value.equals("1")) {
return true;
} else if (value.equals("0")) {
return false;
}
return Boolean.parseBoolean(value);
}
protected abstract Object parseValue(String value);
private final Object defaultValue_;
private final String desc_;
}
private final static String DEFAULT_TEMP_DIR = "/tmp";
private static String getTempDir(final String dirName) {
try {
return Files.createTempDirectory(dirName).toAbsolutePath().toString();
} catch(final IOException ioe) {
System.err.println("Unable to create temp directory, defaulting to: " +
DEFAULT_TEMP_DIR);
return DEFAULT_TEMP_DIR + File.pathSeparator + dirName;
}
}
private static class RandomGenerator {
private final byte[] data_;
private int dataLength_;
private int position_;
private double compressionRatio_;
Random rand_;
private RandomGenerator(long seed, double compressionRatio) {
// We use a limited amount of data over and over again and ensure
// that it is larger than the compression window (32KB), and also
byte[] value = new byte[100];
// large enough to serve all typical value sizes we want to write.
rand_ = new Random(seed);
dataLength_ = value.length * 10000;
data_ = new byte[dataLength_];
compressionRatio_ = compressionRatio;
int pos = 0;
while (pos < dataLength_) {
compressibleBytes(value);
System.arraycopy(value, 0, data_, pos,
Math.min(value.length, dataLength_ - pos));
pos += value.length;
}
}
private void compressibleBytes(byte[] value) {
int baseLength = value.length;
if (compressionRatio_ < 1.0d) {
baseLength = (int) (compressionRatio_ * value.length + 0.5);
}
if (baseLength <= 0) {
baseLength = 1;
}
int pos;
for (pos = 0; pos < baseLength; ++pos) {
value[pos] = (byte) (' ' + rand_.nextInt(95)); // ' ' .. '~'
}
while (pos < value.length) {
System.arraycopy(value, 0, value, pos,
Math.min(baseLength, value.length - pos));
pos += baseLength;
}
}
private void generate(byte[] value) {
if (position_ + value.length > data_.length) {
position_ = 0;
assert(value.length <= data_.length);
}
position_ += value.length;
System.arraycopy(data_, position_ - value.length,
value, 0, value.length);
}
}
boolean isFinished() {
synchronized(finishLock_) {
return isFinished_;
}
}
void setFinished(boolean flag) {
synchronized(finishLock_) {
isFinished_ = flag;
}
}
RocksDB db_;
final List<String> benchmarks_;
final int num_;
final int reads_;
final int keySize_;
final int valueSize_;
final int threadNum_;
final int writesPerSeconds_;
final long randSeed_;
final boolean useExisting_;
final String databaseDir_;
double compressionRatio_;
RandomGenerator gen_;
long startTime_;
// env
boolean useMemenv_;
// memtable related
final int maxWriteBufferNumber_;
final int prefixSize_;
final int keysPerPrefix_;
final String memtable_;
final long hashBucketCount_;
// sst format related
boolean usePlainTable_;
Object finishLock_;
boolean isFinished_;
Map<Flag, Object> flags_;
// as the scope of a static member equals to the scope of the problem,
// we let its c++ pointer to be disposed in its finalizer.
static Options defaultOptions_ = new Options();
static BlockBasedTableConfig defaultBlockBasedTableOptions_ =
new BlockBasedTableConfig();
String compressionType_;
CompressionType compression_;
}
| facebook/rocksdb | java/benchmark/src/main/java/org/rocksdb/benchmark/DbBenchmark.java |
2,711 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.kafka.trogdor.workload;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.kafka.trogdor.task.TaskController;
import org.apache.kafka.trogdor.task.TaskSpec;
import org.apache.kafka.trogdor.task.TaskWorker;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
/**
* The specification for a benchmark that produces messages to a set of topics.
*
* To configure a transactional producer, a #{@link TransactionGenerator} must be passed in.
* Said generator works in lockstep with the producer by instructing it what action to take next in regards to a transaction.
*
* An example JSON representation which will result in a producer that creates three topics (foo1, foo2, foo3)
* with three partitions each and produces to them:
* #{@code
* {
* "class": "org.apache.kafka.trogdor.workload.ProduceBenchSpec",
* "durationMs": 10000000,
* "producerNode": "node0",
* "bootstrapServers": "localhost:9092",
* "targetMessagesPerSec": 10,
* "maxMessages": 100,
* "activeTopics": {
* "foo[1-3]": {
* "numPartitions": 3,
* "replicationFactor": 1
* }
* },
* "inactiveTopics": {
* "foo[4-5]": {
* "numPartitions": 3,
* "replicationFactor": 1
* }
* }
* }
* }
*/
public class ProduceBenchSpec extends TaskSpec {
private final String producerNode;
private final String bootstrapServers;
private final int targetMessagesPerSec;
private final long maxMessages;
private final PayloadGenerator keyGenerator;
private final PayloadGenerator valueGenerator;
private final Optional<TransactionGenerator> transactionGenerator;
private final Map<String, String> producerConf;
private final Map<String, String> adminClientConf;
private final Map<String, String> commonClientConf;
private final TopicsSpec activeTopics;
private final TopicsSpec inactiveTopics;
private final boolean useConfiguredPartitioner;
private final boolean skipFlush;
@SuppressWarnings("this-escape")
@JsonCreator
public ProduceBenchSpec(@JsonProperty("startMs") long startMs,
@JsonProperty("durationMs") long durationMs,
@JsonProperty("producerNode") String producerNode,
@JsonProperty("bootstrapServers") String bootstrapServers,
@JsonProperty("targetMessagesPerSec") int targetMessagesPerSec,
@JsonProperty("maxMessages") long maxMessages,
@JsonProperty("keyGenerator") PayloadGenerator keyGenerator,
@JsonProperty("valueGenerator") PayloadGenerator valueGenerator,
@JsonProperty("transactionGenerator") Optional<TransactionGenerator> txGenerator,
@JsonProperty("producerConf") Map<String, String> producerConf,
@JsonProperty("commonClientConf") Map<String, String> commonClientConf,
@JsonProperty("adminClientConf") Map<String, String> adminClientConf,
@JsonProperty("activeTopics") TopicsSpec activeTopics,
@JsonProperty("inactiveTopics") TopicsSpec inactiveTopics,
@JsonProperty("useConfiguredPartitioner") boolean useConfiguredPartitioner,
@JsonProperty("skipFlush") boolean skipFlush) {
super(startMs, durationMs);
this.producerNode = (producerNode == null) ? "" : producerNode;
this.bootstrapServers = (bootstrapServers == null) ? "" : bootstrapServers;
this.targetMessagesPerSec = targetMessagesPerSec;
this.maxMessages = maxMessages;
this.keyGenerator = keyGenerator == null ?
new SequentialPayloadGenerator(4, 0) : keyGenerator;
this.valueGenerator = valueGenerator == null ?
new ConstantPayloadGenerator(512, new byte[0]) : valueGenerator;
this.transactionGenerator = txGenerator == null ? Optional.empty() : txGenerator;
this.producerConf = configOrEmptyMap(producerConf);
this.commonClientConf = configOrEmptyMap(commonClientConf);
this.adminClientConf = configOrEmptyMap(adminClientConf);
this.activeTopics = (activeTopics == null) ?
TopicsSpec.EMPTY : activeTopics.immutableCopy();
this.inactiveTopics = (inactiveTopics == null) ?
TopicsSpec.EMPTY : inactiveTopics.immutableCopy();
this.useConfiguredPartitioner = useConfiguredPartitioner;
this.skipFlush = skipFlush;
}
@JsonProperty
public String producerNode() {
return producerNode;
}
@JsonProperty
public String bootstrapServers() {
return bootstrapServers;
}
@JsonProperty
public int targetMessagesPerSec() {
return targetMessagesPerSec;
}
@JsonProperty
public long maxMessages() {
return maxMessages;
}
@JsonProperty
public PayloadGenerator keyGenerator() {
return keyGenerator;
}
@JsonProperty
public PayloadGenerator valueGenerator() {
return valueGenerator;
}
@JsonProperty
public Optional<TransactionGenerator> transactionGenerator() {
return transactionGenerator;
}
@JsonProperty
public Map<String, String> producerConf() {
return producerConf;
}
@JsonProperty
public Map<String, String> commonClientConf() {
return commonClientConf;
}
@JsonProperty
public Map<String, String> adminClientConf() {
return adminClientConf;
}
@JsonProperty
public TopicsSpec activeTopics() {
return activeTopics;
}
@JsonProperty
public TopicsSpec inactiveTopics() {
return inactiveTopics;
}
@JsonProperty
public boolean useConfiguredPartitioner() {
return useConfiguredPartitioner;
}
@JsonProperty
public boolean skipFlush() {
return skipFlush;
}
@Override
public TaskController newController(String id) {
return topology -> Collections.singleton(producerNode);
}
@Override
public TaskWorker newTaskWorker(String id) {
return new ProduceBenchWorker(id, this);
}
}
| apache/kafka | trogdor/src/main/java/org/apache/kafka/trogdor/workload/ProduceBenchSpec.java |
2,712 | /**
* Copyright (c) 2013-2024 Nikita Koksharov
*
* 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 org.redisson;
import java.util.concurrent.CompletableFuture;
/**
*
* Nikita Koksharov
*
*/
public interface PubSubEntry<E> {
void acquire();
int release();
CompletableFuture<E> getPromise();
}
| redisson/redisson | redisson/src/main/java/org/redisson/PubSubEntry.java |
2,713 | // $Id: ary.java,v 1.1 2004-05-22 07:27:00 bfulgham Exp $
// http://www.bagley.org/~doug/shootout/
// this program is modified from:
// http://cm.bell-labs.com/cm/cs/who/bwk/interps/pap.html
// Timing Trials, or, the Trials of Timing: Experiments with Scripting
// and User-Interface Languages</a> by Brian W. Kernighan and
// Christopher J. Van Wyk.
import java.io.*;
import java.util.*;
public class ary {
public static void main(String args[]) {
int i, j, k, n = Integer.parseInt(args[0]);
int x[] = new int[n];
int y[] = new int[n];
for (i = 0; i < n; i++)
x[i] = i + 1;
for (k = 0; k < 1000; k++ )
for (j = n-1; j >= 0; j--)
y[j] += x[j];
System.out.println(y[0] + " " + y[n-1]);
}
}
| groovy/groovy-core | benchmark/bench/ary.java |
2,714 | /**
Copyright (c) 2012-2014 Microsoft Corporation
Module Name:
Context.java
Abstract:
Author:
@author Christoph Wintersteiger (cwinter) 2012-03-15
Notes:
**/
package com.microsoft.z3;
import static com.microsoft.z3.Constructor.of;
import com.microsoft.z3.enumerations.Z3_ast_print_mode;
import java.util.Map;
/**
* The main interaction with Z3 happens via the Context.
* For applications that spawn an unbounded number of contexts,
* the proper use is within a try-with-resources
* scope so that the Context object gets garbage collected in
* a predictable way. Contexts maintain all data-structures
* related to terms and formulas that are created relative
* to them.
**/
@SuppressWarnings("unchecked")
public class Context implements AutoCloseable {
private long m_ctx;
static final Object creation_lock = new Object();
public Context () {
synchronized (creation_lock) {
m_ctx = Native.mkContextRc(0);
init();
}
}
protected Context (long m_ctx) {
synchronized (creation_lock) {
this.m_ctx = m_ctx;
init();
}
}
/**
* Constructor.
* Remarks:
* The following parameters can be set:
* - proof (Boolean) Enable proof generation
* - debug_ref_count (Boolean) Enable debug support for Z3_ast reference counting
* - trace (Boolean) Tracing support for VCC
* - trace_file_name (String) Trace out file for VCC traces
* - timeout (unsigned) default timeout (in milliseconds) used for solvers
* - well_sorted_check type checker
* - auto_config use heuristics to automatically select solver and configure it
* - model model generation for solvers, this parameter can be overwritten when creating a solver
* - model_validate validate models produced by solvers
* - unsat_core unsat-core generation for solvers, this parameter can be overwritten when creating a solver
* Note that in previous versions of Z3, this constructor was also used to set global and
* module parameters. For this purpose we should now use {@code Global.setParameter}
**/
public Context(Map<String, String> settings) {
synchronized (creation_lock) {
long cfg = Native.mkConfig();
for (Map.Entry<String, String> kv : settings.entrySet()) {
Native.setParamValue(cfg, kv.getKey(), kv.getValue());
}
m_ctx = Native.mkContextRc(cfg);
Native.delConfig(cfg);
init();
}
}
private void init() {
setPrintMode(Z3_ast_print_mode.Z3_PRINT_SMTLIB2_COMPLIANT);
Native.setInternalErrorHandler(m_ctx);
}
/**
* Creates a new symbol using an integer.
* Remarks: Not all integers can be passed to this function.
* The legal range of unsigned integers is 0 to 2^30-1.
**/
public IntSymbol mkSymbol(int i)
{
return new IntSymbol(this, i);
}
/**
* Create a symbol using a string.
**/
public StringSymbol mkSymbol(String name)
{
return new StringSymbol(this, name);
}
/**
* Create an array of symbols.
**/
Symbol[] mkSymbols(String[] names)
{
if (names == null)
return new Symbol[0];
Symbol[] result = new Symbol[names.length];
for (int i = 0; i < names.length; ++i)
result[i] = mkSymbol(names[i]);
return result;
}
private BoolSort m_boolSort = null;
private IntSort m_intSort = null;
private RealSort m_realSort = null;
private SeqSort<CharSort> m_stringSort = null;
/**
* Retrieves the Boolean sort of the context.
**/
public BoolSort getBoolSort()
{
if (m_boolSort == null) {
m_boolSort = new BoolSort(this);
}
return m_boolSort;
}
/**
* Retrieves the Integer sort of the context.
**/
public IntSort getIntSort()
{
if (m_intSort == null) {
m_intSort = new IntSort(this);
}
return m_intSort;
}
/**
* Retrieves the Real sort of the context.
**/
public RealSort getRealSort()
{
if (m_realSort == null) {
m_realSort = new RealSort(this);
}
return m_realSort;
}
/**
* Create a new Boolean sort.
**/
public BoolSort mkBoolSort()
{
return new BoolSort(this);
}
/**
* Creates character sort object.
**/
public CharSort mkCharSort()
{
return new CharSort(this);
}
/**
* Retrieves the String sort of the context.
**/
public SeqSort<CharSort> getStringSort()
{
if (m_stringSort == null) {
m_stringSort = mkStringSort();
}
return m_stringSort;
}
/**
* Create a new uninterpreted sort.
**/
public UninterpretedSort mkUninterpretedSort(Symbol s)
{
checkContextMatch(s);
return new UninterpretedSort(this, s);
}
/**
* Create a new uninterpreted sort.
**/
public UninterpretedSort mkUninterpretedSort(String str)
{
return mkUninterpretedSort(mkSymbol(str));
}
/**
* Create a new integer sort.
**/
public IntSort mkIntSort()
{
return new IntSort(this);
}
/**
* Create a real sort.
**/
public RealSort mkRealSort()
{
return new RealSort(this);
}
/**
* Create a new bit-vector sort.
**/
public BitVecSort mkBitVecSort(int size)
{
return new BitVecSort(this, Native.mkBvSort(nCtx(), size));
}
/**
* Create a new array sort.
**/
public final <D extends Sort, R extends Sort> ArraySort<D, R> mkArraySort(D domain, R range)
{
checkContextMatch(domain);
checkContextMatch(range);
return new ArraySort<>(this, domain, range);
}
/**
* Create a new array sort.
**/
public final <R extends Sort> ArraySort<Sort, R> mkArraySort(Sort[] domains, R range)
{
checkContextMatch(domains);
checkContextMatch(range);
return new ArraySort<>(this, domains, range);
}
/**
* Create a new string sort
**/
public SeqSort<CharSort> mkStringSort()
{
return new SeqSort<>(this, Native.mkStringSort(nCtx()));
}
/**
* Create a new sequence sort
**/
public final <R extends Sort> SeqSort<R> mkSeqSort(R s)
{
return new SeqSort<>(this, Native.mkSeqSort(nCtx(), s.getNativeObject()));
}
/**
* Create a new regular expression sort
**/
public final <R extends Sort> ReSort<R> mkReSort(R s)
{
return new ReSort<>(this, Native.mkReSort(nCtx(), s.getNativeObject()));
}
/**
* Create a new tuple sort.
**/
public TupleSort mkTupleSort(Symbol name, Symbol[] fieldNames,
Sort[] fieldSorts)
{
checkContextMatch(name);
checkContextMatch(fieldNames);
checkContextMatch(fieldSorts);
return new TupleSort(this, name, fieldNames.length, fieldNames,
fieldSorts);
}
/**
* Create a new enumeration sort.
**/
public final <R> EnumSort<R> mkEnumSort(Symbol name, Symbol... enumNames)
{
checkContextMatch(name);
checkContextMatch(enumNames);
return new EnumSort<>(this, name, enumNames);
}
/**
* Create a new enumeration sort.
**/
public final <R> EnumSort<R> mkEnumSort(String name, String... enumNames)
{
return new EnumSort<>(this, mkSymbol(name), mkSymbols(enumNames));
}
/**
* Create a new list sort.
**/
public final <R extends Sort> ListSort<R> mkListSort(Symbol name, R elemSort)
{
checkContextMatch(name);
checkContextMatch(elemSort);
return new ListSort<>(this, name, elemSort);
}
/**
* Create a new list sort.
**/
public final <R extends Sort> ListSort<R> mkListSort(String name, R elemSort)
{
checkContextMatch(elemSort);
return new ListSort<>(this, mkSymbol(name), elemSort);
}
/**
* Create a new finite domain sort.
**/
public final <R> FiniteDomainSort<R> mkFiniteDomainSort(Symbol name, long size)
{
checkContextMatch(name);
return new FiniteDomainSort<>(this, name, size);
}
/**
* Create a new finite domain sort.
**/
public final <R> FiniteDomainSort<R> mkFiniteDomainSort(String name, long size)
{
return new FiniteDomainSort<>(this, mkSymbol(name), size);
}
/**
* Create a datatype constructor.
* @param name constructor name
* @param recognizer name of recognizer function.
* @param fieldNames names of the constructor fields.
* @param sorts field sorts, 0 if the field sort refers to a recursive sort.
* @param sortRefs reference to datatype sort that is an argument to the
* constructor; if the corresponding sort reference is 0, then the value in sort_refs should be
* an index referring to one of the recursive datatypes that is
* declared.
**/
public final <R> Constructor<R> mkConstructor(Symbol name, Symbol recognizer,
Symbol[] fieldNames, Sort[] sorts, int[] sortRefs)
{
return of(this, name, recognizer, fieldNames, sorts, sortRefs);
}
/**
* Create a datatype constructor.
**/
public final <R> Constructor<R> mkConstructor(String name, String recognizer,
String[] fieldNames, Sort[] sorts, int[] sortRefs)
{
return of(this, mkSymbol(name), mkSymbol(recognizer), mkSymbols(fieldNames), sorts, sortRefs);
}
/**
* Create a new datatype sort.
**/
public final <R> DatatypeSort<R> mkDatatypeSort(Symbol name, Constructor<R>[] constructors)
{
checkContextMatch(name);
checkContextMatch(constructors);
return new DatatypeSort<>(this, name, constructors);
}
/**
* Create a new datatype sort.
**/
public final <R> DatatypeSort<R> mkDatatypeSort(String name, Constructor<R>[] constructors)
{
checkContextMatch(constructors);
return new DatatypeSort<>(this, mkSymbol(name), constructors);
}
/**
* Create mutually recursive datatypes.
* @param names names of datatype sorts
* @param c list of constructors, one list per sort.
**/
public DatatypeSort<Object>[] mkDatatypeSorts(Symbol[] names, Constructor<Object>[][] c)
{
checkContextMatch(names);
int n = names.length;
ConstructorList<Object>[] cla = new ConstructorList[n];
long[] n_constr = new long[n];
for (int i = 0; i < n; i++)
{
Constructor<Object>[] constructor = c[i];
checkContextMatch(constructor);
cla[i] = new ConstructorList<>(this, constructor);
n_constr[i] = cla[i].getNativeObject();
}
long[] n_res = new long[n];
Native.mkDatatypes(nCtx(), n, Symbol.arrayToNative(names), n_res,
n_constr);
DatatypeSort<Object>[] res = new DatatypeSort[n];
for (int i = 0; i < n; i++)
res[i] = new DatatypeSort<>(this, n_res[i]);
return res;
}
/**
* Create mutually recursive data-types.
**/
public DatatypeSort<Object>[] mkDatatypeSorts(String[] names, Constructor<Object>[][] c)
{
return mkDatatypeSorts(mkSymbols(names), c);
}
/**
* Update a datatype field at expression t with value v.
* The function performs a record update at t. The field
* that is passed in as argument is updated with value v,
* the remaining fields of t are unchanged.
**/
public final <F extends Sort, R extends Sort> Expr<R> mkUpdateField(FuncDecl<F> field, Expr<R> t, Expr<F> v)
throws Z3Exception
{
return (Expr<R>) Expr.create(this,
Native.datatypeUpdateField
(nCtx(), field.getNativeObject(),
t.getNativeObject(), v.getNativeObject()));
}
/**
* Creates a new function declaration.
**/
public final <R extends Sort> FuncDecl<R> mkFuncDecl(Symbol name, Sort[] domain, R range)
{
checkContextMatch(name);
checkContextMatch(domain);
checkContextMatch(range);
return new FuncDecl<>(this, name, domain, range);
}
public final <R extends Sort> FuncDecl<R> mkPropagateFunction(Symbol name, Sort[] domain, R range)
{
checkContextMatch(name);
checkContextMatch(domain);
checkContextMatch(range);
long f = Native.solverPropagateDeclare(
this.nCtx(),
name.getNativeObject(),
AST.arrayLength(domain),
AST.arrayToNative(domain),
range.getNativeObject());
return new FuncDecl<>(this, f);
}
/**
* Creates a new function declaration.
**/
public final <R extends Sort> FuncDecl<R> mkFuncDecl(Symbol name, Sort domain, R range)
{
checkContextMatch(name);
checkContextMatch(domain);
checkContextMatch(range);
Sort[] q = new Sort[] { domain };
return new FuncDecl<>(this, name, q, range);
}
/**
* Creates a new function declaration.
**/
public final <R extends Sort> FuncDecl<R> mkFuncDecl(String name, Sort[] domain, R range)
{
checkContextMatch(domain);
checkContextMatch(range);
return new FuncDecl<>(this, mkSymbol(name), domain, range);
}
/**
* Creates a new function declaration.
**/
public final <R extends Sort> FuncDecl<R> mkFuncDecl(String name, Sort domain, R range)
{
checkContextMatch(domain);
checkContextMatch(range);
Sort[] q = new Sort[] { domain };
return new FuncDecl<>(this, mkSymbol(name), q, range);
}
/**
* Creates a new recursive function declaration.
**/
public final <R extends Sort> FuncDecl<R> mkRecFuncDecl(Symbol name, Sort[] domain, R range)
{
checkContextMatch(name);
checkContextMatch(domain);
checkContextMatch(range);
return new FuncDecl<>(this, name, domain, range, true);
}
/**
* Bind a definition to a recursive function declaration.
* The function must have previously been created using
* MkRecFuncDecl. The body may contain recursive uses of the function or
* other mutually recursive functions.
*/
public final <R extends Sort> void AddRecDef(FuncDecl<R> f, Expr<?>[] args, Expr<R> body)
{
checkContextMatch(f);
checkContextMatch(args);
checkContextMatch(body);
long[] argsNative = AST.arrayToNative(args);
Native.addRecDef(nCtx(), f.getNativeObject(), args.length, argsNative, body.getNativeObject());
}
/**
* Creates a fresh function declaration with a name prefixed with
* {@code prefix}.
* @see #mkFuncDecl(String,Sort,Sort)
* @see #mkFuncDecl(String,Sort[],Sort)
**/
public final <R extends Sort> FuncDecl<R> mkFreshFuncDecl(String prefix, Sort[] domain, R range)
{
checkContextMatch(domain);
checkContextMatch(range);
return new FuncDecl<>(this, prefix, domain, range);
}
/**
* Creates a new constant function declaration.
**/
public final <R extends Sort> FuncDecl<R> mkConstDecl(Symbol name, R range)
{
checkContextMatch(name);
checkContextMatch(range);
return new FuncDecl<>(this, name, null, range);
}
/**
* Creates a new constant function declaration.
**/
public final <R extends Sort> FuncDecl<R> mkConstDecl(String name, R range)
{
checkContextMatch(range);
return new FuncDecl<>(this, mkSymbol(name), null, range);
}
/**
* Creates a fresh constant function declaration with a name prefixed with
* {@code prefix}.
* @see #mkFuncDecl(String,Sort,Sort)
* @see #mkFuncDecl(String,Sort[],Sort)
**/
public final <R extends Sort> FuncDecl<R> mkFreshConstDecl(String prefix, R range)
{
checkContextMatch(range);
return new FuncDecl<>(this, prefix, null, range);
}
/**
* Creates a new bound variable.
* @param index The de-Bruijn index of the variable
* @param ty The sort of the variable
**/
public final <R extends Sort> Expr<R> mkBound(int index, R ty)
{
return (Expr<R>) Expr.create(this,
Native.mkBound(nCtx(), index, ty.getNativeObject()));
}
/**
* Create a quantifier pattern.
**/
@SafeVarargs
public final Pattern mkPattern(Expr<?>... terms)
{
if (terms.length == 0)
throw new Z3Exception("Cannot create a pattern from zero terms");
long[] termsNative = AST.arrayToNative(terms);
return new Pattern(this, Native.mkPattern(nCtx(), terms.length,
termsNative));
}
/**
* Creates a new Constant of sort {@code range} and named
* {@code name}.
**/
public final <R extends Sort> Expr<R> mkConst(Symbol name, R range)
{
checkContextMatch(name);
checkContextMatch(range);
return (Expr<R>) Expr.create(
this,
Native.mkConst(nCtx(), name.getNativeObject(),
range.getNativeObject()));
}
/**
* Creates a new Constant of sort {@code range} and named
* {@code name}.
**/
public final <R extends Sort> Expr<R> mkConst(String name, R range)
{
return mkConst(mkSymbol(name), range);
}
/**
* Creates a fresh Constant of sort {@code range} and a name
* prefixed with {@code prefix}.
**/
public final <R extends Sort> Expr<R> mkFreshConst(String prefix, R range)
{
checkContextMatch(range);
return (Expr<R>) Expr.create(this,
Native.mkFreshConst(nCtx(), prefix, range.getNativeObject()));
}
/**
* Creates a fresh constant from the FuncDecl {@code f}.
* @param f A decl of a 0-arity function
**/
public final <R extends Sort> Expr<R> mkConst(FuncDecl<R> f)
{
return mkApp(f, (Expr<?>[]) null);
}
/**
* Create a Boolean constant.
**/
public BoolExpr mkBoolConst(Symbol name)
{
return (BoolExpr) mkConst(name, getBoolSort());
}
/**
* Create a Boolean constant.
**/
public BoolExpr mkBoolConst(String name)
{
return (BoolExpr) mkConst(mkSymbol(name), getBoolSort());
}
/**
* Creates an integer constant.
**/
public IntExpr mkIntConst(Symbol name)
{
return (IntExpr) mkConst(name, getIntSort());
}
/**
* Creates an integer constant.
**/
public IntExpr mkIntConst(String name)
{
return (IntExpr) mkConst(name, getIntSort());
}
/**
* Creates a real constant.
**/
public RealExpr mkRealConst(Symbol name)
{
return (RealExpr) mkConst(name, getRealSort());
}
/**
* Creates a real constant.
**/
public RealExpr mkRealConst(String name)
{
return (RealExpr) mkConst(name, getRealSort());
}
/**
* Creates a bit-vector constant.
**/
public BitVecExpr mkBVConst(Symbol name, int size)
{
return (BitVecExpr) mkConst(name, mkBitVecSort(size));
}
/**
* Creates a bit-vector constant.
**/
public BitVecExpr mkBVConst(String name, int size)
{
return (BitVecExpr) mkConst(name, mkBitVecSort(size));
}
/**
* Create a new function application.
**/
@SafeVarargs
public final <R extends Sort> Expr<R> mkApp(FuncDecl<R> f, Expr<?>... args)
{
checkContextMatch(f);
checkContextMatch(args);
return Expr.create(this, f, args);
}
/**
* The true Term.
**/
public BoolExpr mkTrue()
{
return new BoolExpr(this, Native.mkTrue(nCtx()));
}
/**
* The false Term.
**/
public BoolExpr mkFalse()
{
return new BoolExpr(this, Native.mkFalse(nCtx()));
}
/**
* Creates a Boolean value.
**/
public BoolExpr mkBool(boolean value)
{
return value ? mkTrue() : mkFalse();
}
/**
* Creates the equality {@code x = y}
**/
public BoolExpr mkEq(Expr<?> x, Expr<?> y)
{
checkContextMatch(x);
checkContextMatch(y);
return new BoolExpr(this, Native.mkEq(nCtx(), x.getNativeObject(),
y.getNativeObject()));
}
/**
* Creates a {@code distinct} term.
**/
@SafeVarargs
public final BoolExpr mkDistinct(Expr<?>... args)
{
checkContextMatch(args);
return new BoolExpr(this, Native.mkDistinct(nCtx(), args.length,
AST.arrayToNative(args)));
}
/**
* Create an expression representing {@code not(a)}.
**/
public final BoolExpr mkNot(Expr<BoolSort> a)
{
checkContextMatch(a);
return new BoolExpr(this, Native.mkNot(nCtx(), a.getNativeObject()));
}
/**
* Create an expression representing an if-then-else:
* {@code ite(t1, t2, t3)}.
* @param t1 An expression with Boolean sort
* @param t2 An expression
* @param t3 An expression with the same sort as {@code t2}
**/
public final <R extends Sort> Expr<R> mkITE(Expr<BoolSort> t1, Expr<? extends R> t2, Expr<? extends R> t3)
{
checkContextMatch(t1);
checkContextMatch(t2);
checkContextMatch(t3);
return (Expr<R>) Expr.create(this, Native.mkIte(nCtx(), t1.getNativeObject(),
t2.getNativeObject(), t3.getNativeObject()));
}
/**
* Create an expression representing {@code t1 iff t2}.
**/
public BoolExpr mkIff(Expr<BoolSort> t1, Expr<BoolSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BoolExpr(this, Native.mkIff(nCtx(), t1.getNativeObject(),
t2.getNativeObject()));
}
/**
* Create an expression representing {@code t1 -> t2}.
**/
public BoolExpr mkImplies(Expr<BoolSort> t1, Expr<BoolSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BoolExpr(this, Native.mkImplies(nCtx(),
t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Create an expression representing {@code t1 xor t2}.
**/
public BoolExpr mkXor(Expr<BoolSort> t1, Expr<BoolSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BoolExpr(this, Native.mkXor(nCtx(), t1.getNativeObject(),
t2.getNativeObject()));
}
/**
* Create an expression representing {@code t[0] and t[1] and ...}.
**/
@SafeVarargs
public final BoolExpr mkAnd(Expr<BoolSort>... t)
{
checkContextMatch(t);
return new BoolExpr(this, Native.mkAnd(nCtx(), t.length,
AST.arrayToNative(t)));
}
/**
* Create an expression representing {@code t[0] or t[1] or ...}.
**/
@SafeVarargs
public final BoolExpr mkOr(Expr<BoolSort>... t)
{
checkContextMatch(t);
return new BoolExpr(this, Native.mkOr(nCtx(), t.length,
AST.arrayToNative(t)));
}
/**
* Create an expression representing {@code t[0] + t[1] + ...}.
**/
@SafeVarargs
public final <R extends ArithSort> ArithExpr<R> mkAdd(Expr<? extends R>... t)
{
checkContextMatch(t);
return (ArithExpr<R>) Expr.create(this,
Native.mkAdd(nCtx(), t.length, AST.arrayToNative(t)));
}
/**
* Create an expression representing {@code t[0] * t[1] * ...}.
**/
@SafeVarargs
public final <R extends ArithSort> ArithExpr<R> mkMul(Expr<? extends R>... t)
{
checkContextMatch(t);
return (ArithExpr<R>) Expr.create(this,
Native.mkMul(nCtx(), t.length, AST.arrayToNative(t)));
}
/**
* Create an expression representing {@code t[0] - t[1] - ...}.
**/
@SafeVarargs
public final <R extends ArithSort> ArithExpr<R> mkSub(Expr<? extends R>... t)
{
checkContextMatch(t);
return (ArithExpr<R>) Expr.create(this,
Native.mkSub(nCtx(), t.length, AST.arrayToNative(t)));
}
/**
* Create an expression representing {@code -t}.
**/
public final <R extends ArithSort> ArithExpr<R> mkUnaryMinus(Expr<R> t)
{
checkContextMatch(t);
return (ArithExpr<R>) Expr.create(this,
Native.mkUnaryMinus(nCtx(), t.getNativeObject()));
}
/**
* Create an expression representing {@code t1 / t2}.
**/
public final <R extends ArithSort> ArithExpr<R> mkDiv(Expr<? extends R> t1, Expr<? extends R> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return (ArithExpr<R>) Expr.create(this, Native.mkDiv(nCtx(),
t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Create an expression representing {@code t1 mod t2}.
* Remarks: The
* arguments must have int type.
**/
public IntExpr mkMod(Expr<IntSort> t1, Expr<IntSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new IntExpr(this, Native.mkMod(nCtx(), t1.getNativeObject(),
t2.getNativeObject()));
}
/**
* Create an expression representing {@code t1 rem t2}.
* Remarks: The
* arguments must have int type.
**/
public IntExpr mkRem(Expr<IntSort> t1, Expr<IntSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new IntExpr(this, Native.mkRem(nCtx(), t1.getNativeObject(),
t2.getNativeObject()));
}
/**
* Create an expression representing {@code t1 ^ t2}.
**/
public final <R extends ArithSort> ArithExpr<R> mkPower(Expr<? extends R> t1,
Expr<? extends R> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return (ArithExpr<R>) Expr.create(
this,
Native.mkPower(nCtx(), t1.getNativeObject(),
t2.getNativeObject()));
}
/**
* Create an expression representing {@code t1 < t2}
**/
public BoolExpr mkLt(Expr<? extends ArithSort> t1, Expr<? extends ArithSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BoolExpr(this, Native.mkLt(nCtx(), t1.getNativeObject(),
t2.getNativeObject()));
}
/**
* Create an expression representing {@code t1 <= t2}
**/
public BoolExpr mkLe(Expr<? extends ArithSort> t1, Expr<? extends ArithSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BoolExpr(this, Native.mkLe(nCtx(), t1.getNativeObject(),
t2.getNativeObject()));
}
/**
* Create an expression representing {@code t1 > t2}
**/
public BoolExpr mkGt(Expr<? extends ArithSort> t1, Expr<? extends ArithSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BoolExpr(this, Native.mkGt(nCtx(), t1.getNativeObject(),
t2.getNativeObject()));
}
/**
* Create an expression representing {@code t1 >= t2}
**/
public BoolExpr mkGe(Expr<? extends ArithSort> t1, Expr<? extends ArithSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BoolExpr(this, Native.mkGe(nCtx(), t1.getNativeObject(),
t2.getNativeObject()));
}
/**
* Coerce an integer to a real.
* Remarks: There is also a converse operation
* exposed. It follows the semantics prescribed by the SMT-LIB standard.
*
* You can take the floor of a real by creating an auxiliary integer Term
* {@code k} and asserting
* {@code MakeInt2Real(k) <= t1 < MkInt2Real(k)+1}. The argument
* must be of integer sort.
**/
public RealExpr mkInt2Real(Expr<IntSort> t)
{
checkContextMatch(t);
return new RealExpr(this,
Native.mkInt2real(nCtx(), t.getNativeObject()));
}
/**
* Coerce a real to an integer.
* Remarks: The semantics of this function
* follows the SMT-LIB standard for the function to_int. The argument must
* be of real sort.
**/
public IntExpr mkReal2Int(Expr<RealSort> t)
{
checkContextMatch(t);
return new IntExpr(this, Native.mkReal2int(nCtx(), t.getNativeObject()));
}
/**
* Creates an expression that checks whether a real number is an integer.
**/
public BoolExpr mkIsInteger(Expr<RealSort> t)
{
checkContextMatch(t);
return new BoolExpr(this, Native.mkIsInt(nCtx(), t.getNativeObject()));
}
/**
* Bitwise negation.
* Remarks: The argument must have a bit-vector
* sort.
**/
public BitVecExpr mkBVNot(Expr<BitVecSort> t)
{
checkContextMatch(t);
return new BitVecExpr(this, Native.mkBvnot(nCtx(), t.getNativeObject()));
}
/**
* Take conjunction of bits in a vector, return vector of length 1.
*
* Remarks: The argument must have a bit-vector sort.
**/
public BitVecExpr mkBVRedAND(Expr<BitVecSort> t)
{
checkContextMatch(t);
return new BitVecExpr(this, Native.mkBvredand(nCtx(),
t.getNativeObject()));
}
/**
* Take disjunction of bits in a vector, return vector of length 1.
*
* Remarks: The argument must have a bit-vector sort.
**/
public BitVecExpr mkBVRedOR(Expr<BitVecSort> t)
{
checkContextMatch(t);
return new BitVecExpr(this, Native.mkBvredor(nCtx(),
t.getNativeObject()));
}
/**
* Bitwise conjunction.
* Remarks: The arguments must have a bit-vector
* sort.
**/
public BitVecExpr mkBVAND(Expr<BitVecSort> t1, Expr<BitVecSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BitVecExpr(this, Native.mkBvand(nCtx(),
t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Bitwise disjunction.
* Remarks: The arguments must have a bit-vector
* sort.
**/
public BitVecExpr mkBVOR(Expr<BitVecSort> t1, Expr<BitVecSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BitVecExpr(this, Native.mkBvor(nCtx(), t1.getNativeObject(),
t2.getNativeObject()));
}
/**
* Bitwise XOR.
* Remarks: The arguments must have a bit-vector
* sort.
**/
public BitVecExpr mkBVXOR(Expr<BitVecSort> t1, Expr<BitVecSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BitVecExpr(this, Native.mkBvxor(nCtx(),
t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Bitwise NAND.
* Remarks: The arguments must have a bit-vector
* sort.
**/
public BitVecExpr mkBVNAND(Expr<BitVecSort> t1, Expr<BitVecSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BitVecExpr(this, Native.mkBvnand(nCtx(),
t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Bitwise NOR.
* Remarks: The arguments must have a bit-vector
* sort.
**/
public BitVecExpr mkBVNOR(Expr<BitVecSort> t1, Expr<BitVecSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BitVecExpr(this, Native.mkBvnor(nCtx(),
t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Bitwise XNOR.
* Remarks: The arguments must have a bit-vector
* sort.
**/
public BitVecExpr mkBVXNOR(Expr<BitVecSort> t1, Expr<BitVecSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BitVecExpr(this, Native.mkBvxnor(nCtx(),
t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Standard two's complement unary minus.
* Remarks: The arguments must have a
* bit-vector sort.
**/
public BitVecExpr mkBVNeg(Expr<BitVecSort> t)
{
checkContextMatch(t);
return new BitVecExpr(this, Native.mkBvneg(nCtx(), t.getNativeObject()));
}
/**
* Two's complement addition.
* Remarks: The arguments must have the same
* bit-vector sort.
**/
public BitVecExpr mkBVAdd(Expr<BitVecSort> t1, Expr<BitVecSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BitVecExpr(this, Native.mkBvadd(nCtx(),
t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Two's complement subtraction.
* Remarks: The arguments must have the same
* bit-vector sort.
**/
public BitVecExpr mkBVSub(Expr<BitVecSort> t1, Expr<BitVecSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BitVecExpr(this, Native.mkBvsub(nCtx(),
t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Two's complement multiplication.
* Remarks: The arguments must have the
* same bit-vector sort.
**/
public BitVecExpr mkBVMul(Expr<BitVecSort> t1, Expr<BitVecSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BitVecExpr(this, Native.mkBvmul(nCtx(),
t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Unsigned division.
* Remarks: It is defined as the floor of
* {@code t1/t2} if \c t2 is different from zero. If {@code t2} is
* zero, then the result is undefined. The arguments must have the same
* bit-vector sort.
**/
public BitVecExpr mkBVUDiv(Expr<BitVecSort> t1, Expr<BitVecSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BitVecExpr(this, Native.mkBvudiv(nCtx(),
t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Signed division.
* Remarks: It is defined in the following way:
*
* - The \c floor of {@code t1/t2} if \c t2 is different from zero, and
* {@code t1*t2 >= 0}.
*
* - The \c ceiling of {@code t1/t2} if \c t2 is different from zero,
* and {@code t1*t2 < 0}.
*
* If {@code t2} is zero, then the result is undefined. The arguments
* must have the same bit-vector sort.
**/
public BitVecExpr mkBVSDiv(Expr<BitVecSort> t1, Expr<BitVecSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BitVecExpr(this, Native.mkBvsdiv(nCtx(),
t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Unsigned remainder.
* Remarks: It is defined as
* {@code t1 - (t1 /u t2) * t2}, where {@code /u} represents
* unsigned division. If {@code t2} is zero, then the result is
* undefined. The arguments must have the same bit-vector sort.
**/
public BitVecExpr mkBVURem(Expr<BitVecSort> t1, Expr<BitVecSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BitVecExpr(this, Native.mkBvurem(nCtx(),
t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Signed remainder.
* Remarks: It is defined as
* {@code t1 - (t1 /s t2) * t2}, where {@code /s} represents
* signed division. The most significant bit (sign) of the result is equal
* to the most significant bit of \c t1.
*
* If {@code t2} is zero, then the result is undefined. The arguments
* must have the same bit-vector sort.
**/
public BitVecExpr mkBVSRem(Expr<BitVecSort> t1, Expr<BitVecSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BitVecExpr(this, Native.mkBvsrem(nCtx(),
t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Two's complement signed remainder (sign follows divisor).
* Remarks: If
* {@code t2} is zero, then the result is undefined. The arguments must
* have the same bit-vector sort.
**/
public BitVecExpr mkBVSMod(Expr<BitVecSort> t1, Expr<BitVecSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BitVecExpr(this, Native.mkBvsmod(nCtx(),
t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Unsigned less-than
* Remarks: The arguments must have the same bit-vector
* sort.
**/
public BoolExpr mkBVULT(Expr<BitVecSort> t1, Expr<BitVecSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BoolExpr(this, Native.mkBvult(nCtx(), t1.getNativeObject(),
t2.getNativeObject()));
}
/**
* Two's complement signed less-than
* Remarks: The arguments must have the
* same bit-vector sort.
**/
public BoolExpr mkBVSLT(Expr<BitVecSort> t1, Expr<BitVecSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BoolExpr(this, Native.mkBvslt(nCtx(), t1.getNativeObject(),
t2.getNativeObject()));
}
/**
* Unsigned less-than or equal to.
* Remarks: The arguments must have the
* same bit-vector sort.
**/
public BoolExpr mkBVULE(Expr<BitVecSort> t1, Expr<BitVecSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BoolExpr(this, Native.mkBvule(nCtx(), t1.getNativeObject(),
t2.getNativeObject()));
}
/**
* Two's complement signed less-than or equal to.
* Remarks: The arguments
* must have the same bit-vector sort.
**/
public BoolExpr mkBVSLE(Expr<BitVecSort> t1, Expr<BitVecSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BoolExpr(this, Native.mkBvsle(nCtx(), t1.getNativeObject(),
t2.getNativeObject()));
}
/**
* Unsigned greater than or equal to.
* Remarks: The arguments must have the
* same bit-vector sort.
**/
public BoolExpr mkBVUGE(Expr<BitVecSort> t1, Expr<BitVecSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BoolExpr(this, Native.mkBvuge(nCtx(), t1.getNativeObject(),
t2.getNativeObject()));
}
/**
* Two's complement signed greater than or equal to.
* Remarks: The arguments
* must have the same bit-vector sort.
**/
public BoolExpr mkBVSGE(Expr<BitVecSort> t1, Expr<BitVecSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BoolExpr(this, Native.mkBvsge(nCtx(), t1.getNativeObject(),
t2.getNativeObject()));
}
/**
* Unsigned greater-than.
* Remarks: The arguments must have the same
* bit-vector sort.
**/
public BoolExpr mkBVUGT(Expr<BitVecSort> t1, Expr<BitVecSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BoolExpr(this, Native.mkBvugt(nCtx(), t1.getNativeObject(),
t2.getNativeObject()));
}
/**
* Two's complement signed greater-than.
* Remarks: The arguments must have
* the same bit-vector sort.
**/
public BoolExpr mkBVSGT(Expr<BitVecSort> t1, Expr<BitVecSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BoolExpr(this, Native.mkBvsgt(nCtx(), t1.getNativeObject(),
t2.getNativeObject()));
}
/**
* Bit-vector concatenation.
* Remarks: The arguments must have a bit-vector
* sort.
*
* @return The result is a bit-vector of size {@code n1+n2}, where
* {@code n1} ({@code n2}) is the size of {@code t1}
* ({@code t2}).
*
**/
public BitVecExpr mkConcat(Expr<BitVecSort> t1, Expr<BitVecSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BitVecExpr(this, Native.mkConcat(nCtx(),
t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Bit-vector extraction.
* Remarks: Extract the bits {@code high}
* down to {@code low} from a bitvector of size {@code m} to
* yield a new bitvector of size {@code n}, where
* {@code n = high - low + 1}. The argument {@code t} must
* have a bit-vector sort.
**/
public BitVecExpr mkExtract(int high, int low, Expr<BitVecSort> t)
{
checkContextMatch(t);
return new BitVecExpr(this, Native.mkExtract(nCtx(), high, low,
t.getNativeObject()));
}
/**
* Bit-vector sign extension.
* Remarks: Sign-extends the given bit-vector to
* the (signed) equivalent bitvector of size {@code m+i}, where \c m is
* the size of the given bit-vector. The argument {@code t} must
* have a bit-vector sort.
**/
public BitVecExpr mkSignExt(int i, Expr<BitVecSort> t)
{
checkContextMatch(t);
return new BitVecExpr(this, Native.mkSignExt(nCtx(), i,
t.getNativeObject()));
}
/**
* Bit-vector zero extension.
* Remarks: Extend the given bit-vector with
* zeros to the (unsigned) equivalent bitvector of size {@code m+i},
* where \c m is the size of the given bit-vector. The argument {@code t}
* must have a bit-vector sort.
**/
public BitVecExpr mkZeroExt(int i, Expr<BitVecSort> t)
{
checkContextMatch(t);
return new BitVecExpr(this, Native.mkZeroExt(nCtx(), i,
t.getNativeObject()));
}
/**
* Bit-vector repetition.
* Remarks: The argument {@code t} must
* have a bit-vector sort.
**/
public BitVecExpr mkRepeat(int i, Expr<BitVecSort> t)
{
checkContextMatch(t);
return new BitVecExpr(this, Native.mkRepeat(nCtx(), i,
t.getNativeObject()));
}
/**
* Shift left.
* Remarks: It is equivalent to multiplication by
* {@code 2^x} where \c x is the value of {@code t2}.
*
* NB. The semantics of shift operations varies between environments. This
* definition does not necessarily capture directly the semantics of the
* programming language or assembly architecture you are modeling.
*
* The arguments must have a bit-vector sort.
**/
public BitVecExpr mkBVSHL(Expr<BitVecSort> t1, Expr<BitVecSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BitVecExpr(this, Native.mkBvshl(nCtx(),
t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Logical shift right
* Remarks: It is equivalent to unsigned division by
* {@code 2^x} where \c x is the value of {@code t2}.
*
* NB. The semantics of shift operations varies between environments. This
* definition does not necessarily capture directly the semantics of the
* programming language or assembly architecture you are modeling.
*
* The arguments must have a bit-vector sort.
**/
public BitVecExpr mkBVLSHR(Expr<BitVecSort> t1, Expr<BitVecSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BitVecExpr(this, Native.mkBvlshr(nCtx(),
t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Arithmetic shift right
* Remarks: It is like logical shift right except
* that the most significant bits of the result always copy the most
* significant bit of the second argument.
*
* NB. The semantics of shift operations varies between environments. This
* definition does not necessarily capture directly the semantics of the
* programming language or assembly architecture you are modeling.
*
* The arguments must have a bit-vector sort.
**/
public BitVecExpr mkBVASHR(Expr<BitVecSort> t1, Expr<BitVecSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BitVecExpr(this, Native.mkBvashr(nCtx(),
t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Rotate Left.
* Remarks: Rotate bits of \c t to the left \c i times. The
* argument {@code t} must have a bit-vector sort.
**/
public BitVecExpr mkBVRotateLeft(int i, Expr<BitVecSort> t)
{
checkContextMatch(t);
return new BitVecExpr(this, Native.mkRotateLeft(nCtx(), i,
t.getNativeObject()));
}
/**
* Rotate Right.
* Remarks: Rotate bits of \c t to the right \c i times. The
* argument {@code t} must have a bit-vector sort.
**/
public BitVecExpr mkBVRotateRight(int i, Expr<BitVecSort> t)
{
checkContextMatch(t);
return new BitVecExpr(this, Native.mkRotateRight(nCtx(), i,
t.getNativeObject()));
}
/**
* Rotate Left.
* Remarks: Rotate bits of {@code t1} to the left
* {@code t2} times. The arguments must have the same bit-vector
* sort.
**/
public BitVecExpr mkBVRotateLeft(Expr<BitVecSort> t1, Expr<BitVecSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BitVecExpr(this, Native.mkExtRotateLeft(nCtx(),
t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Rotate Right.
* Remarks: Rotate bits of {@code t1} to the
* right{@code t2} times. The arguments must have the same
* bit-vector sort.
**/
public BitVecExpr mkBVRotateRight(Expr<BitVecSort> t1, Expr<BitVecSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BitVecExpr(this, Native.mkExtRotateRight(nCtx(),
t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Create an {@code n} bit bit-vector from the integer argument
* {@code t}.
* Remarks: NB. This function is essentially treated
* as uninterpreted. So you cannot expect Z3 to precisely reflect the
* semantics of this function when solving constraints with this function.
*
* The argument must be of integer sort.
**/
public BitVecExpr mkInt2BV(int n, Expr<IntSort> t)
{
checkContextMatch(t);
return new BitVecExpr(this, Native.mkInt2bv(nCtx(), n,
t.getNativeObject()));
}
/**
* Create an integer from the bit-vector argument {@code t}.
* Remarks: If \c is_signed is false, then the bit-vector \c t1 is treated
* as unsigned. So the result is non-negative and in the range
* {@code [0..2^N-1]}, where N are the number of bits in {@code t}.
* If \c is_signed is true, \c t1 is treated as a signed
* bit-vector.
*
* NB. This function is essentially treated as uninterpreted. So you cannot
* expect Z3 to precisely reflect the semantics of this function when
* solving constraints with this function.
*
* The argument must be of bit-vector sort.
**/
public IntExpr mkBV2Int(Expr<BitVecSort> t, boolean signed)
{
checkContextMatch(t);
return new IntExpr(this, Native.mkBv2int(nCtx(), t.getNativeObject(),
(signed)));
}
/**
* Create a predicate that checks that the bit-wise addition does not
* overflow.
* Remarks: The arguments must be of bit-vector sort.
**/
public BoolExpr mkBVAddNoOverflow(Expr<BitVecSort> t1, Expr<BitVecSort> t2,
boolean isSigned)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BoolExpr(this, Native.mkBvaddNoOverflow(nCtx(), t1
.getNativeObject(), t2.getNativeObject(), (isSigned)));
}
/**
* Create a predicate that checks that the bit-wise addition does not
* underflow.
* Remarks: The arguments must be of bit-vector sort.
**/
public BoolExpr mkBVAddNoUnderflow(Expr<BitVecSort> t1, Expr<BitVecSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BoolExpr(this, Native.mkBvaddNoUnderflow(nCtx(),
t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Create a predicate that checks that the bit-wise subtraction does not
* overflow.
* Remarks: The arguments must be of bit-vector sort.
**/
public BoolExpr mkBVSubNoOverflow(Expr<BitVecSort> t1, Expr<BitVecSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BoolExpr(this, Native.mkBvsubNoOverflow(nCtx(),
t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Create a predicate that checks that the bit-wise subtraction does not
* underflow.
* Remarks: The arguments must be of bit-vector sort.
**/
public BoolExpr mkBVSubNoUnderflow(Expr<BitVecSort> t1, Expr<BitVecSort> t2,
boolean isSigned)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BoolExpr(this, Native.mkBvsubNoUnderflow(nCtx(), t1
.getNativeObject(), t2.getNativeObject(), (isSigned)));
}
/**
* Create a predicate that checks that the bit-wise signed division does not
* overflow.
* Remarks: The arguments must be of bit-vector sort.
**/
public BoolExpr mkBVSDivNoOverflow(Expr<BitVecSort> t1, Expr<BitVecSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BoolExpr(this, Native.mkBvsdivNoOverflow(nCtx(),
t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Create a predicate that checks that the bit-wise negation does not
* overflow.
* Remarks: The arguments must be of bit-vector sort.
**/
public BoolExpr mkBVNegNoOverflow(Expr<BitVecSort> t)
{
checkContextMatch(t);
return new BoolExpr(this, Native.mkBvnegNoOverflow(nCtx(),
t.getNativeObject()));
}
/**
* Create a predicate that checks that the bit-wise multiplication does not
* overflow.
* Remarks: The arguments must be of bit-vector sort.
**/
public BoolExpr mkBVMulNoOverflow(Expr<BitVecSort> t1, Expr<BitVecSort> t2,
boolean isSigned)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BoolExpr(this, Native.mkBvmulNoOverflow(nCtx(), t1
.getNativeObject(), t2.getNativeObject(), (isSigned)));
}
/**
* Create a predicate that checks that the bit-wise multiplication does not
* underflow.
* Remarks: The arguments must be of bit-vector sort.
**/
public BoolExpr mkBVMulNoUnderflow(Expr<BitVecSort> t1, Expr<BitVecSort> t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new BoolExpr(this, Native.mkBvmulNoUnderflow(nCtx(),
t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Create an array constant.
**/
public final <D extends Sort, R extends Sort> ArrayExpr<D, R> mkArrayConst(Symbol name, D domain, R range)
{
return (ArrayExpr<D, R>) mkConst(name, mkArraySort(domain, range));
}
/**
* Create an array constant.
**/
public final <D extends Sort, R extends Sort> ArrayExpr<D, R> mkArrayConst(String name, D domain, R range)
{
return (ArrayExpr<D, R>) mkConst(mkSymbol(name), mkArraySort(domain, range));
}
/**
* Array read.
* Remarks: The argument {@code a} is the array and
* {@code i} is the index of the array that gets read.
*
* The node {@code a} must have an array sort
* {@code [domain -> range]}, and {@code i} must have the sort
* {@code domain}. The sort of the result is {@code range}.
*
* @see #mkArraySort(Sort[], R)
* @see #mkStore(Expr<ArraySort<D, R>> a, Expr<D> i, Expr<R> v)
**/
public final <D extends Sort, R extends Sort> Expr<R> mkSelect(Expr<ArraySort<D, R>> a, Expr<D> i)
{
checkContextMatch(a);
checkContextMatch(i);
return (Expr<R>) Expr.create(
this,
Native.mkSelect(nCtx(), a.getNativeObject(),
i.getNativeObject()));
}
/**
* Array read.
* Remarks: The argument {@code a} is the array and
* {@code args} are the indices of the array that gets read.
*
* The node {@code a} must have an array sort
* {@code [domains -> range]}, and {@code args} must have the sorts
* {@code domains}. The sort of the result is {@code range}.
*
* @see #mkArraySort(Sort[], R)
* @see #mkStore(Expr<ArraySort<D, R>> a, Expr<D> i, Expr<R> v)
**/
public final <R extends Sort> Expr<R> mkSelect(Expr<ArraySort<Sort, R>> a, Expr<?>[] args)
{
checkContextMatch(a);
checkContextMatch(args);
return (Expr<R>) Expr.create(
this,
Native.mkSelectN(nCtx(), a.getNativeObject(), args.length, AST.arrayToNative(args)));
}
/**
* Array update.
* Remarks: The node {@code a} must have an array sort
* {@code [domain -> range]}, {@code i} must have sort
* {@code domain}, {@code v} must have sort range. The sort of the
* result is {@code [domain -> range]}. The semantics of this function
* is given by the theory of arrays described in the SMT-LIB standard. See
* http://smtlib.org for more details. The result of this function is an
* array that is equal to {@code a} (with respect to
* {@code select}) on all indices except for {@code i}, where it
* maps to {@code v} (and the {@code select} of {@code a}
* with respect to {@code i} may be a different value).
* @see #mkArraySort(Sort[], R)
* @see #mkSelect(Expr<ArraySort<D, R>> a, Expr<D> i)
**/
public final <D extends Sort, R extends Sort> ArrayExpr<D, R> mkStore(Expr<ArraySort<D, R>> a, Expr<D> i, Expr<R> v)
{
checkContextMatch(a);
checkContextMatch(i);
checkContextMatch(v);
return new ArrayExpr<>(this, Native.mkStore(nCtx(), a.getNativeObject(),
i.getNativeObject(), v.getNativeObject()));
}
/**
* Array update.
* Remarks: The node {@code a} must have an array sort
* {@code [domains -> range]}, {@code i} must have sort
* {@code domain}, {@code v} must have sort range. The sort of the
* result is {@code [domains -> range]}. The semantics of this function
* is given by the theory of arrays described in the SMT-LIB standard. See
* http://smtlib.org for more details. The result of this function is an
* array that is equal to {@code a} (with respect to
* {@code select}) on all indices except for {@code args}, where it
* maps to {@code v} (and the {@code select} of {@code a}
* with respect to {@code args} may be a different value).
* @see #mkArraySort(Sort[], R)
* @see #mkSelect(Expr<ArraySort<D, R>> a, Expr<D> i)
**/
public final <R extends Sort> ArrayExpr<Sort, R> mkStore(Expr<ArraySort<Sort, R>> a, Expr<?>[] args, Expr<R> v)
{
checkContextMatch(a);
checkContextMatch(args);
checkContextMatch(v);
return new ArrayExpr<>(this, Native.mkStoreN(nCtx(), a.getNativeObject(),
args.length, AST.arrayToNative(args), v.getNativeObject()));
}
/**
* Create a constant array.
* Remarks: The resulting term is an array, such
* that a {@code select} on an arbitrary index produces the value
* {@code v}.
* @see #mkArraySort(Sort[], R)
* @see #mkSelect(Expr<ArraySort<D, R>> a, Expr<D> i)
*
**/
public final <D extends Sort, R extends Sort> ArrayExpr<D, R> mkConstArray(D domain, Expr<R> v)
{
checkContextMatch(domain);
checkContextMatch(v);
return new ArrayExpr<>(this, Native.mkConstArray(nCtx(),
domain.getNativeObject(), v.getNativeObject()));
}
/**
* Maps f on the argument arrays.
* Remarks: Each element of
* {@code args} must be of an array sort
* {@code [domain_i -> range_i]}. The function declaration
* {@code f} must have type {@code range_1 .. range_n -> range}.
* {@code v} must have sort range. The sort of the result is
* {@code [domain_i -> range]}.
* @see #mkArraySort(Sort[], R)
* @see #mkSelect(Expr<ArraySort<D, R>> a, Expr<D> i)
* @see #mkStore(Expr<ArraySort<D, R>> a, Expr<D> i, Expr<R> v)
**/
@SafeVarargs
public final <D extends Sort, R1 extends Sort, R2 extends Sort> ArrayExpr<D, R2> mkMap(FuncDecl<R2> f, Expr<ArraySort<D, R1>>... args)
{
checkContextMatch(f);
checkContextMatch(args);
return (ArrayExpr<D, R2>) Expr.create(this, Native.mkMap(nCtx(),
f.getNativeObject(), AST.arrayLength(args),
AST.arrayToNative(args)));
}
/**
* Access the array default value.
* Remarks: Produces the default range
* value, for arrays that can be represented as finite maps with a default
* range value.
**/
public final <D extends Sort, R extends Sort> Expr<R> mkTermArray(Expr<ArraySort<D, R>> array)
{
checkContextMatch(array);
return (Expr<R>) Expr.create(this,
Native.mkArrayDefault(nCtx(), array.getNativeObject()));
}
/**
* Create Extentionality index. Two arrays are equal if and only if they are equal on the index returned by MkArrayExt.
**/
public final <D extends Sort, R extends Sort> Expr<D> mkArrayExt(Expr<ArraySort<D, R>> arg1, Expr<ArraySort<D, R>> arg2)
{
checkContextMatch(arg1);
checkContextMatch(arg2);
return (Expr<D>) Expr.create(this, Native.mkArrayExt(nCtx(), arg1.getNativeObject(), arg2.getNativeObject()));
}
/**
* Create a set type.
**/
public final <D extends Sort> SetSort<D> mkSetSort(D ty)
{
checkContextMatch(ty);
return new SetSort<>(this, ty);
}
/**
* Create an empty set.
**/
public final <D extends Sort> ArrayExpr<D, BoolSort> mkEmptySet(D domain)
{
checkContextMatch(domain);
return (ArrayExpr<D, BoolSort>) Expr.create(this,
Native.mkEmptySet(nCtx(), domain.getNativeObject()));
}
/**
* Create the full set.
**/
public final <D extends Sort> ArrayExpr<D, BoolSort> mkFullSet(D domain)
{
checkContextMatch(domain);
return (ArrayExpr<D, BoolSort>) Expr.create(this,
Native.mkFullSet(nCtx(), domain.getNativeObject()));
}
/**
* Add an element to the set.
**/
public final <D extends Sort> ArrayExpr<D, BoolSort> mkSetAdd(Expr<ArraySort<D, BoolSort>> set, Expr<D> element)
{
checkContextMatch(set);
checkContextMatch(element);
return (ArrayExpr<D, BoolSort>) Expr.create(this,
Native.mkSetAdd(nCtx(), set.getNativeObject(),
element.getNativeObject()));
}
/**
* Remove an element from a set.
**/
public final <D extends Sort> ArrayExpr<D, BoolSort> mkSetDel(Expr<ArraySort<D, BoolSort>> set, Expr<D> element)
{
checkContextMatch(set);
checkContextMatch(element);
return (ArrayExpr<D, BoolSort>)Expr.create(this,
Native.mkSetDel(nCtx(), set.getNativeObject(),
element.getNativeObject()));
}
/**
* Take the union of a list of sets.
**/
@SafeVarargs
public final <D extends Sort> ArrayExpr<D, BoolSort> mkSetUnion(Expr<ArraySort<D, BoolSort>>... args)
{
checkContextMatch(args);
return (ArrayExpr<D, BoolSort>)Expr.create(this,
Native.mkSetUnion(nCtx(), args.length,
AST.arrayToNative(args)));
}
/**
* Take the intersection of a list of sets.
**/
@SafeVarargs
public final <D extends Sort> ArrayExpr<D, BoolSort> mkSetIntersection(Expr<ArraySort<D, BoolSort>>... args)
{
checkContextMatch(args);
return (ArrayExpr<D, BoolSort>) Expr.create(this,
Native.mkSetIntersect(nCtx(), args.length,
AST.arrayToNative(args)));
}
/**
* Take the difference between two sets.
**/
public final <D extends Sort> ArrayExpr<D, BoolSort> mkSetDifference(Expr<ArraySort<D, BoolSort>> arg1, Expr<ArraySort<D, BoolSort>> arg2)
{
checkContextMatch(arg1);
checkContextMatch(arg2);
return (ArrayExpr<D, BoolSort>) Expr.create(this,
Native.mkSetDifference(nCtx(), arg1.getNativeObject(),
arg2.getNativeObject()));
}
/**
* Take the complement of a set.
**/
public final <D extends Sort> ArrayExpr<D, BoolSort> mkSetComplement(Expr<ArraySort<D, BoolSort>> arg)
{
checkContextMatch(arg);
return (ArrayExpr<D, BoolSort>)Expr.create(this,
Native.mkSetComplement(nCtx(), arg.getNativeObject()));
}
/**
* Check for set membership.
**/
public final <D extends Sort> BoolExpr mkSetMembership(Expr<D> elem, Expr<ArraySort<D, BoolSort>> set)
{
checkContextMatch(elem);
checkContextMatch(set);
return (BoolExpr) Expr.create(this,
Native.mkSetMember(nCtx(), elem.getNativeObject(),
set.getNativeObject()));
}
/**
* Check for subsetness of sets.
**/
public final <D extends Sort> BoolExpr mkSetSubset(Expr<ArraySort<D, BoolSort>> arg1, Expr<ArraySort<D, BoolSort>> arg2)
{
checkContextMatch(arg1);
checkContextMatch(arg2);
return (BoolExpr) Expr.create(this,
Native.mkSetSubset(nCtx(), arg1.getNativeObject(),
arg2.getNativeObject()));
}
/**
* Sequences, Strings and regular expressions.
*/
/**
* Create the empty sequence.
*/
public final <R extends Sort> SeqExpr<R> mkEmptySeq(R s)
{
checkContextMatch(s);
return (SeqExpr<R>) Expr.create(this, Native.mkSeqEmpty(nCtx(), s.getNativeObject()));
}
/**
* Create the singleton sequence.
*/
public final <R extends Sort> SeqExpr<R> mkUnit(Expr<R> elem)
{
checkContextMatch(elem);
return (SeqExpr<R>) Expr.create(this, Native.mkSeqUnit(nCtx(), elem.getNativeObject()));
}
/**
* Create a string constant.
*/
public SeqExpr<CharSort> mkString(String s)
{
StringBuilder buf = new StringBuilder();
for (int i = 0; i < s.length(); ++i) {
int code = s.codePointAt(i);
if (code <= 32 || 127 < code)
buf.append(String.format("\\u{%x}", code));
else
buf.append(s.charAt(i));
}
return (SeqExpr<CharSort>) Expr.create(this, Native.mkString(nCtx(), buf.toString()));
}
/**
* Convert an integer expression to a string.
*/
public SeqExpr<CharSort> intToString(Expr<IntSort> e)
{
return (SeqExpr<CharSort>) Expr.create(this, Native.mkIntToStr(nCtx(), e.getNativeObject()));
}
/**
* Convert an unsigned bitvector expression to a string.
*/
public SeqExpr<CharSort> ubvToString(Expr<BitVecSort> e)
{
return (SeqExpr<CharSort>) Expr.create(this, Native.mkUbvToStr(nCtx(), e.getNativeObject()));
}
/**
* Convert an signed bitvector expression to a string.
*/
public SeqExpr<CharSort> sbvToString(Expr<BitVecSort> e)
{
return (SeqExpr<CharSort>) Expr.create(this, Native.mkSbvToStr(nCtx(), e.getNativeObject()));
}
/**
* Convert an integer expression to a string.
*/
public IntExpr stringToInt(Expr<SeqSort<CharSort>> e)
{
return (IntExpr) Expr.create(this, Native.mkStrToInt(nCtx(), e.getNativeObject()));
}
/**
* Concatenate sequences.
*/
@SafeVarargs
public final <R extends Sort> SeqExpr<R> mkConcat(Expr<SeqSort<R>>... t)
{
checkContextMatch(t);
return (SeqExpr<R>) Expr.create(this, Native.mkSeqConcat(nCtx(), t.length, AST.arrayToNative(t)));
}
/**
* Retrieve the length of a given sequence.
*/
public final <R extends Sort> IntExpr mkLength(Expr<SeqSort<R>> s)
{
checkContextMatch(s);
return (IntExpr) Expr.create(this, Native.mkSeqLength(nCtx(), s.getNativeObject()));
}
/**
* Check for sequence prefix.
*/
public final <R extends Sort> BoolExpr mkPrefixOf(Expr<SeqSort<R>> s1, Expr<SeqSort<R>> s2)
{
checkContextMatch(s1, s2);
return (BoolExpr) Expr.create(this, Native.mkSeqPrefix(nCtx(), s1.getNativeObject(), s2.getNativeObject()));
}
/**
* Check for sequence suffix.
*/
public final <R extends Sort> BoolExpr mkSuffixOf(Expr<SeqSort<R>> s1, Expr<SeqSort<R>> s2)
{
checkContextMatch(s1, s2);
return (BoolExpr)Expr.create(this, Native.mkSeqSuffix(nCtx(), s1.getNativeObject(), s2.getNativeObject()));
}
/**
* Check for sequence containment of s2 in s1.
*/
public final <R extends Sort> BoolExpr mkContains(Expr<SeqSort<R>> s1, Expr<SeqSort<R>> s2)
{
checkContextMatch(s1, s2);
return (BoolExpr) Expr.create(this, Native.mkSeqContains(nCtx(), s1.getNativeObject(), s2.getNativeObject()));
}
/**
* Check if the string s1 is lexicographically strictly less than s2.
*/
public BoolExpr MkStringLt(Expr<SeqSort<CharSort>> s1, Expr<SeqSort<CharSort>> s2)
{
checkContextMatch(s1, s2);
return new BoolExpr(this, Native.mkStrLt(nCtx(), s1.getNativeObject(), s2.getNativeObject()));
}
/**
* Check if the string s1 is lexicographically less or equal to s2.
*/
public BoolExpr MkStringLe(Expr<SeqSort<CharSort>> s1, Expr<SeqSort<CharSort>> s2)
{
checkContextMatch(s1, s2);
return new BoolExpr(this, Native.mkStrLe(nCtx(), s1.getNativeObject(), s2.getNativeObject()));
}
/**
* Retrieve sequence of length one at index.
*/
public final <R extends Sort> SeqExpr<R> mkAt(Expr<SeqSort<R>> s, Expr<IntSort> index)
{
checkContextMatch(s, index);
return (SeqExpr<R>) Expr.create(this, Native.mkSeqAt(nCtx(), s.getNativeObject(), index.getNativeObject()));
}
/**
* Retrieve element at index.
*/
public final <R extends Sort> Expr<R> mkNth(Expr<SeqSort<R>> s, Expr<IntSort> index)
{
checkContextMatch(s, index);
return (Expr<R>) Expr.create(this, Native.mkSeqNth(nCtx(), s.getNativeObject(), index.getNativeObject()));
}
/**
* Extract subsequence.
*/
public final <R extends Sort> SeqExpr<R> mkExtract(Expr<SeqSort<R>> s, Expr<IntSort> offset, Expr<IntSort> length)
{
checkContextMatch(s, offset, length);
return (SeqExpr<R>) Expr.create(this, Native.mkSeqExtract(nCtx(), s.getNativeObject(), offset.getNativeObject(), length.getNativeObject()));
}
/**
* Extract index of sub-string starting at offset.
*/
public final <R extends Sort> IntExpr mkIndexOf(Expr<SeqSort<R>> s, Expr<SeqSort<R>> substr, Expr<IntSort> offset)
{
checkContextMatch(s, substr, offset);
return (IntExpr)Expr.create(this, Native.mkSeqIndex(nCtx(), s.getNativeObject(), substr.getNativeObject(), offset.getNativeObject()));
}
/**
* Replace the first occurrence of src by dst in s.
*/
public final <R extends Sort> SeqExpr<R> mkReplace(Expr<SeqSort<R>> s, Expr<SeqSort<R>> src, Expr<SeqSort<R>> dst)
{
checkContextMatch(s, src, dst);
return (SeqExpr<R>) Expr.create(this, Native.mkSeqReplace(nCtx(), s.getNativeObject(), src.getNativeObject(), dst.getNativeObject()));
}
/**
* Convert a regular expression that accepts sequence s.
*/
public final <R extends Sort> ReExpr<SeqSort<R>> mkToRe(Expr<SeqSort<R>> s)
{
checkContextMatch(s);
return (ReExpr<SeqSort<R>>) Expr.create(this, Native.mkSeqToRe(nCtx(), s.getNativeObject()));
}
/**
* Check for regular expression membership.
*/
public final <R extends Sort> BoolExpr mkInRe(Expr<SeqSort<R>> s, ReExpr<SeqSort<R>> re)
{
checkContextMatch(s, re);
return (BoolExpr) Expr.create(this, Native.mkSeqInRe(nCtx(), s.getNativeObject(), re.getNativeObject()));
}
/**
* Take the Kleene star of a regular expression.
*/
public final <R extends Sort> ReExpr<R> mkStar(Expr<ReSort<R>> re)
{
checkContextMatch(re);
return (ReExpr<R>) Expr.create(this, Native.mkReStar(nCtx(), re.getNativeObject()));
}
/**
* Create power regular expression.
*/
public final <R extends Sort> ReExpr<R> mkPower(Expr<ReSort<R>> re, int n)
{
return (ReExpr<R>) Expr.create(this, Native.mkRePower(nCtx(), re.getNativeObject(), n));
}
/**
* Take the lower and upper-bounded Kleene star of a regular expression.
*/
public final <R extends Sort> ReExpr<R> mkLoop(Expr<ReSort<R>> re, int lo, int hi)
{
return (ReExpr<R>) Expr.create(this, Native.mkReLoop(nCtx(), re.getNativeObject(), lo, hi));
}
/**
* Take the lower-bounded Kleene star of a regular expression.
*/
public final <R extends Sort> ReExpr<R> mkLoop(Expr<ReSort<R>> re, int lo)
{
return (ReExpr<R>) Expr.create(this, Native.mkReLoop(nCtx(), re.getNativeObject(), lo, 0));
}
/**
* Take the Kleene plus of a regular expression.
*/
public final <R extends Sort> ReExpr<R> mkPlus(Expr<ReSort<R>> re)
{
checkContextMatch(re);
return (ReExpr<R>) Expr.create(this, Native.mkRePlus(nCtx(), re.getNativeObject()));
}
/**
* Create the optional regular expression.
*/
public final <R extends Sort> ReExpr<R> mkOption(Expr<ReSort<R>> re)
{
checkContextMatch(re);
return (ReExpr<R>) Expr.create(this, Native.mkReOption(nCtx(), re.getNativeObject()));
}
/**
* Create the complement regular expression.
*/
public final <R extends Sort> ReExpr<R> mkComplement(Expr<ReSort<R>> re)
{
checkContextMatch(re);
return (ReExpr<R>) Expr.create(this, Native.mkReComplement(nCtx(), re.getNativeObject()));
}
/**
* Create the concatenation of regular languages.
*/
@SafeVarargs
public final <R extends Sort> ReExpr<R> mkConcat(ReExpr<R>... t)
{
checkContextMatch(t);
return (ReExpr<R>) Expr.create(this, Native.mkReConcat(nCtx(), t.length, AST.arrayToNative(t)));
}
/**
* Create the union of regular languages.
*/
@SafeVarargs
public final <R extends Sort> ReExpr<R> mkUnion(Expr<ReSort<R>>... t)
{
checkContextMatch(t);
return (ReExpr<R>) Expr.create(this, Native.mkReUnion(nCtx(), t.length, AST.arrayToNative(t)));
}
/**
* Create the intersection of regular languages.
*/
@SafeVarargs
public final <R extends Sort> ReExpr<R> mkIntersect(Expr<ReSort<R>>... t)
{
checkContextMatch(t);
return (ReExpr<R>) Expr.create(this, Native.mkReIntersect(nCtx(), t.length, AST.arrayToNative(t)));
}
/**
* Create a difference regular expression.
*/
public final <R extends Sort> ReExpr<R> mkDiff(Expr<ReSort<R>> a, Expr<ReSort<R>> b)
{
checkContextMatch(a, b);
return (ReExpr<R>) Expr.create(this, Native.mkReDiff(nCtx(), a.getNativeObject(), b.getNativeObject()));
}
/**
* Create the empty regular expression.
* Corresponds to re.none
*/
public final <R extends Sort> ReExpr<R> mkEmptyRe(ReSort<R> s)
{
return (ReExpr<R>) Expr.create(this, Native.mkReEmpty(nCtx(), s.getNativeObject()));
}
/**
* Create the full regular expression.
* Corresponds to re.all
*/
public final <R extends Sort> ReExpr<R> mkFullRe(ReSort<R> s)
{
return (ReExpr<R>) Expr.create(this, Native.mkReFull(nCtx(), s.getNativeObject()));
}
/**
* Create regular expression that accepts all characters
* R has to be a sequence sort.
* Corresponds to re.allchar
*/
public final <R extends Sort> ReExpr<R> mkAllcharRe(ReSort<R> s)
{
return (ReExpr<R>) Expr.create(this, Native.mkReAllchar(nCtx(), s.getNativeObject()));
}
/**
* Create a range expression.
*/
public final ReExpr<SeqSort<CharSort>> mkRange(Expr<SeqSort<CharSort>> lo, Expr<SeqSort<CharSort>> hi)
{
checkContextMatch(lo, hi);
return (ReExpr<SeqSort<CharSort>>) Expr.create(this, Native.mkReRange(nCtx(), lo.getNativeObject(), hi.getNativeObject()));
}
/**
* Create less than or equal to between two characters.
*/
public BoolExpr mkCharLe(Expr<CharSort> ch1, Expr<CharSort> ch2)
{
checkContextMatch(ch1, ch2);
return (BoolExpr) Expr.create(this, Native.mkCharLe(nCtx(), ch1.getNativeObject(), ch2.getNativeObject()));
}
/**
* Create an integer (code point) from character.
*/
public IntExpr charToInt(Expr<CharSort> ch)
{
checkContextMatch(ch);
return (IntExpr) Expr.create(this, Native.mkCharToInt(nCtx(), ch.getNativeObject()));
}
/**
* Create a bit-vector (code point) from character.
*/
public BitVecExpr charToBv(Expr<CharSort> ch)
{
checkContextMatch(ch);
return (BitVecExpr) Expr.create(this, Native.mkCharToBv(nCtx(), ch.getNativeObject()));
}
/**
* Create a character from a bit-vector (code point).
*/
public Expr<CharSort> charFromBv(BitVecExpr bv)
{
checkContextMatch(bv);
return (Expr<CharSort>) Expr.create(this, Native.mkCharFromBv(nCtx(), bv.getNativeObject()));
}
/**
* Create a check if the character is a digit.
*/
public BoolExpr mkIsDigit(Expr<CharSort> ch)
{
checkContextMatch(ch);
return (BoolExpr) Expr.create(this, Native.mkCharIsDigit(nCtx(), ch.getNativeObject()));
}
/**
* Create an at-most-k constraint.
*/
public BoolExpr mkAtMost(Expr<BoolSort>[] args, int k)
{
checkContextMatch(args);
return (BoolExpr) Expr.create(this, Native.mkAtmost(nCtx(), args.length, AST.arrayToNative(args), k));
}
/**
* Create an at-least-k constraint.
*/
public BoolExpr mkAtLeast(Expr<BoolSort>[] args, int k)
{
checkContextMatch(args);
return (BoolExpr) Expr.create(this, Native.mkAtleast(nCtx(), args.length, AST.arrayToNative(args), k));
}
/**
* Create a pseudo-Boolean less-or-equal constraint.
*/
public BoolExpr mkPBLe(int[] coeffs, Expr<BoolSort>[] args, int k)
{
checkContextMatch(args);
return (BoolExpr) Expr.create(this, Native.mkPble(nCtx(), args.length, AST.arrayToNative(args), coeffs, k));
}
/**
* Create a pseudo-Boolean greater-or-equal constraint.
*/
public BoolExpr mkPBGe(int[] coeffs, Expr<BoolSort>[] args, int k)
{
checkContextMatch(args);
return (BoolExpr) Expr.create(this, Native.mkPbge(nCtx(), args.length, AST.arrayToNative(args), coeffs, k));
}
/**
* Create a pseudo-Boolean equal constraint.
*/
public BoolExpr mkPBEq(int[] coeffs, Expr<BoolSort>[] args, int k)
{
checkContextMatch(args);
return (BoolExpr) Expr.create(this, Native.mkPbeq(nCtx(), args.length, AST.arrayToNative(args), coeffs, k));
}
/**
* Create a Term of a given sort.
* @param v A string representing the term value in decimal notation. If the given sort is a real, then the
* Term can be a rational, that is, a string of the form
* {@code [num]* / [num]*}.
* @param ty The sort of the
* numeral. In the current implementation, the given sort can be an int,
* real, or bit-vectors of arbitrary size.
*
* @return A Term with value {@code v} and sort {@code ty}
**/
public final <R extends Sort> Expr<R> mkNumeral(String v, R ty)
{
checkContextMatch(ty);
return (Expr<R>) Expr.create(this,
Native.mkNumeral(nCtx(), v, ty.getNativeObject()));
}
/**
* Create a Term of a given sort. This function can be used to create
* numerals that fit in a machine integer. It is slightly faster than
* {@code MakeNumeral} since it is not necessary to parse a string.
*
* @param v Value of the numeral
* @param ty Sort of the numeral
*
* @return A Term with value {@code v} and type {@code ty}
**/
public final <R extends Sort> Expr<R> mkNumeral(int v, R ty)
{
checkContextMatch(ty);
return (Expr<R>) Expr.create(this, Native.mkInt(nCtx(), v, ty.getNativeObject()));
}
/**
* Create a Term of a given sort. This function can be used to create
* numerals that fit in a machine integer. It is slightly faster than
* {@code MakeNumeral} since it is not necessary to parse a string.
*
* @param v Value of the numeral
* @param ty Sort of the numeral
*
* @return A Term with value {@code v} and type {@code ty}
**/
public final <R extends Sort> Expr<R> mkNumeral(long v, R ty)
{
checkContextMatch(ty);
return (Expr<R>) Expr.create(this,
Native.mkInt64(nCtx(), v, ty.getNativeObject()));
}
/**
* Create a real from a fraction.
* @param num numerator of rational.
* @param den denominator of rational.
*
* @return A Term with value {@code num}/{@code den}
* and sort Real
* @see #mkNumeral(String v, R ty)
**/
public RatNum mkReal(int num, int den)
{
if (den == 0) {
throw new Z3Exception("Denominator is zero");
}
return new RatNum(this, Native.mkReal(nCtx(), num, den));
}
/**
* Create a real numeral.
* @param v A string representing the Term value in decimal notation.
*
* @return A Term with value {@code v} and sort Real
**/
public RatNum mkReal(String v)
{
return new RatNum(this, Native.mkNumeral(nCtx(), v, getRealSort()
.getNativeObject()));
}
/**
* Create a real numeral.
* @param v value of the numeral.
*
* @return A Term with value {@code v} and sort Real
**/
public RatNum mkReal(int v)
{
return new RatNum(this, Native.mkInt(nCtx(), v, getRealSort()
.getNativeObject()));
}
/**
* Create a real numeral.
* @param v value of the numeral.
*
* @return A Term with value {@code v} and sort Real
**/
public RatNum mkReal(long v)
{
return new RatNum(this, Native.mkInt64(nCtx(), v, getRealSort()
.getNativeObject()));
}
/**
* Create an integer numeral.
* @param v A string representing the Term value in decimal notation.
**/
public IntNum mkInt(String v)
{
return new IntNum(this, Native.mkNumeral(nCtx(), v, getIntSort()
.getNativeObject()));
}
/**
* Create an integer numeral.
* @param v value of the numeral.
*
* @return A Term with value {@code v} and sort Integer
**/
public IntNum mkInt(int v)
{
return new IntNum(this, Native.mkInt(nCtx(), v, getIntSort()
.getNativeObject()));
}
/**
* Create an integer numeral.
* @param v value of the numeral.
*
* @return A Term with value {@code v} and sort Integer
**/
public IntNum mkInt(long v)
{
return new IntNum(this, Native.mkInt64(nCtx(), v, getIntSort()
.getNativeObject()));
}
/**
* Create a bit-vector numeral.
* @param v A string representing the value in decimal notation.
* @param size the size of the bit-vector
**/
public BitVecNum mkBV(String v, int size)
{
return (BitVecNum) mkNumeral(v, mkBitVecSort(size));
}
/**
* Create a bit-vector numeral.
* @param v value of the numeral.
* @param size the size of the bit-vector
**/
public BitVecNum mkBV(int v, int size)
{
return (BitVecNum) mkNumeral(v, mkBitVecSort(size));
}
/**
* Create a bit-vector numeral.
* @param v value of the numeral. *
* @param size the size of the bit-vector
**/
public BitVecNum mkBV(long v, int size)
{
return (BitVecNum) mkNumeral(v, mkBitVecSort(size));
}
/**
* Create a universal Quantifier.
*
* @param sorts the sorts of the bound variables.
* @param names names of the bound variables
* @param body the body of the quantifier.
* @param weight quantifiers are associated with weights indicating the importance of using the quantifier during instantiation. By default, pass the weight 0.
* @param patterns array containing the patterns created using {@code MkPattern}.
* @param noPatterns array containing the anti-patterns created using {@code MkPattern}.
* @param quantifierID optional symbol to track quantifier.
* @param skolemID optional symbol to track skolem constants.
*
* @return Creates a forall formula, where
* {@code weight} is the weight, {@code patterns} is
* an array of patterns, {@code sorts} is an array with the sorts
* of the bound variables, {@code names} is an array with the
* 'names' of the bound variables, and {@code body} is the body
* of the quantifier. Quantifiers are associated with weights indicating the
* importance of using the quantifier during instantiation.
* Note that the bound variables are de-Bruijn indices created using {#mkBound}.
* Z3 applies the convention that the last element in {@code names} and
* {@code sorts} refers to the variable with index 0, the second to last element
* of {@code names} and {@code sorts} refers to the variable
* with index 1, etc.
**/
public Quantifier mkForall(Sort[] sorts, Symbol[] names, Expr<BoolSort> body,
int weight, Pattern[] patterns, Expr<?>[] noPatterns,
Symbol quantifierID, Symbol skolemID)
{
return Quantifier.of(this, true, sorts, names, body, weight, patterns,
noPatterns, quantifierID, skolemID);
}
/**
* Creates a universal quantifier using a list of constants that will form the set of bound variables.
* @see #mkForall(Sort[],Symbol[],Expr<BoolSort>,int,Pattern[],Expr<?>[],Symbol,Symbol)
**/
public Quantifier mkForall(Expr<?>[] boundConstants, Expr<BoolSort> body, int weight,
Pattern[] patterns, Expr<?>[] noPatterns, Symbol quantifierID,
Symbol skolemID)
{
return Quantifier.of(this, true, boundConstants, body, weight,
patterns, noPatterns, quantifierID, skolemID);
}
/**
* Creates an existential quantifier using de-Bruijn indexed variables.
* @see #mkForall(Sort[],Symbol[],Expr<BoolSort>,int,Pattern[],Expr<?>[],Symbol,Symbol)
**/
public Quantifier mkExists(Sort[] sorts, Symbol[] names, Expr<BoolSort> body,
int weight, Pattern[] patterns, Expr<?>[] noPatterns,
Symbol quantifierID, Symbol skolemID)
{
return Quantifier.of(this, false, sorts, names, body, weight,
patterns, noPatterns, quantifierID, skolemID);
}
/**
* Creates an existential quantifier using a list of constants that will form the set of bound variables.
* @see #mkForall(Sort[],Symbol[],Expr<BoolSort>,int,Pattern[],Expr<?>[],Symbol,Symbol)
**/
public Quantifier mkExists(Expr<?>[] boundConstants, Expr<BoolSort> body, int weight,
Pattern[] patterns, Expr<?>[] noPatterns, Symbol quantifierID,
Symbol skolemID)
{
return Quantifier.of(this, false, boundConstants, body, weight,
patterns, noPatterns, quantifierID, skolemID);
}
/**
* Create a Quantifier.
* @see #mkForall(Sort[],Symbol[],Expr<BoolSort>,int,Pattern[],Expr<?>[],Symbol,Symbol)
**/
public Quantifier mkQuantifier(boolean universal, Sort[] sorts,
Symbol[] names, Expr<BoolSort> body, int weight, Pattern[] patterns,
Expr<?>[] noPatterns, Symbol quantifierID, Symbol skolemID)
{
if (universal)
return mkForall(sorts, names, body, weight, patterns, noPatterns,
quantifierID, skolemID);
else
return mkExists(sorts, names, body, weight, patterns, noPatterns,
quantifierID, skolemID);
}
/**
* Create a Quantifier
* @see #mkForall(Sort[],Symbol[],Expr<BoolSort>,int,Pattern[],Expr<?>[],Symbol,Symbol)
**/
public Quantifier mkQuantifier(boolean universal, Expr<?>[] boundConstants,
Expr<BoolSort> body, int weight, Pattern[] patterns, Expr<?>[] noPatterns,
Symbol quantifierID, Symbol skolemID)
{
if (universal)
return mkForall(boundConstants, body, weight, patterns, noPatterns,
quantifierID, skolemID);
else
return mkExists(boundConstants, body, weight, patterns, noPatterns,
quantifierID, skolemID);
}
/**
* Create a lambda expression.
*
* {@code sorts} is an array
* with the sorts of the bound variables, {@code names} is an array with the
* 'names' of the bound variables, and {@code body} is the body of the
* lambda.
* Note that the bound variables are de-Bruijn indices created using {#mkBound}
* Z3 applies the convention that the last element in {@code names} and
* {@code sorts} refers to the variable with index 0, the second to last element
* of {@code names} and {@code sorts} refers to the variable
* with index 1, etc.
*
* @param sorts the sorts of the bound variables.
* @param names names of the bound variables.
* @param body the body of the quantifier.
**/
public final <R extends Sort> Lambda<R> mkLambda(Sort[] sorts, Symbol[] names, Expr<R> body)
{
return Lambda.of(this, sorts, names, body);
}
/**
* Create a lambda expression.
*
* Creates a lambda expression using a list of constants that will
* form the set of bound variables.
**/
public final <R extends Sort> Lambda<R> mkLambda(Expr<?>[] boundConstants, Expr<R> body)
{
return Lambda.of(this, boundConstants, body);
}
/**
* Selects the format used for pretty-printing expressions.
* Remarks: The
* default mode for pretty printing expressions is to produce SMT-LIB style
* output where common subexpressions are printed at each occurrence. The
* mode is called Z3_PRINT_SMTLIB_FULL. To print shared common
* subexpressions only once, use the Z3_PRINT_LOW_LEVEL mode. To print in
* way that conforms to SMT-LIB standards and uses let expressions to share
* common sub-expressions use Z3_PRINT_SMTLIB_COMPLIANT.
* @see AST#toString
* @see Pattern#toString
* @see FuncDecl#toString
* @see Sort#toString
**/
public void setPrintMode(Z3_ast_print_mode value)
{
Native.setAstPrintMode(nCtx(), value.toInt());
}
/**
* Convert a benchmark into an SMT-LIB formatted string.
* @param name Name of the benchmark. The argument is optional.
*
* @param logic The benchmark logic.
* @param status The status string (sat, unsat, or unknown)
* @param attributes Other attributes, such as source, difficulty or
* category.
* @param assumptions Auxiliary assumptions.
* @param formula Formula to be checked for consistency in conjunction with assumptions.
*
* @return A string representation of the benchmark.
**/
public String benchmarkToSMTString(String name, String logic,
String status, String attributes, Expr<BoolSort>[] assumptions,
Expr<BoolSort> formula)
{
return Native.benchmarkToSmtlibString(nCtx(), name, logic, status,
attributes, assumptions.length,
AST.arrayToNative(assumptions), formula.getNativeObject());
}
/**
* Parse the given string using the SMT-LIB2 parser.
*
* @return A conjunction of assertions.
*
* If the string contains push/pop commands, the
* set of assertions returned are the ones in the
* last scope level.
**/
public BoolExpr[] parseSMTLIB2String(String str, Symbol[] sortNames,
Sort[] sorts, Symbol[] declNames, FuncDecl<?>[] decls)
{
int csn = Symbol.arrayLength(sortNames);
int cs = Sort.arrayLength(sorts);
int cdn = Symbol.arrayLength(declNames);
int cd = AST.arrayLength(decls);
if (csn != cs || cdn != cd) {
throw new Z3Exception("Argument size mismatch");
}
ASTVector v = new ASTVector(this, Native.parseSmtlib2String(nCtx(),
str, AST.arrayLength(sorts), Symbol.arrayToNative(sortNames),
AST.arrayToNative(sorts), AST.arrayLength(decls),
Symbol.arrayToNative(declNames), AST.arrayToNative(decls)));
return v.ToBoolExprArray();
}
/**
* Parse the given file using the SMT-LIB2 parser.
* @see #parseSMTLIB2String
**/
public BoolExpr[] parseSMTLIB2File(String fileName, Symbol[] sortNames,
Sort[] sorts, Symbol[] declNames, FuncDecl<?>[] decls)
{
int csn = Symbol.arrayLength(sortNames);
int cs = Sort.arrayLength(sorts);
int cdn = Symbol.arrayLength(declNames);
int cd = AST.arrayLength(decls);
if (csn != cs || cdn != cd)
throw new Z3Exception("Argument size mismatch");
ASTVector v = new ASTVector(this, Native.parseSmtlib2File(nCtx(),
fileName, AST.arrayLength(sorts),
Symbol.arrayToNative(sortNames), AST.arrayToNative(sorts),
AST.arrayLength(decls), Symbol.arrayToNative(declNames),
AST.arrayToNative(decls)));
return v.ToBoolExprArray();
}
/**
* Creates a new Goal.
* Remarks: Note that the Context must have been
* created with proof generation support if {@code proofs} is set
* to true here.
* @param models Indicates whether model generation should be enabled.
* @param unsatCores Indicates whether unsat core generation should be enabled.
* @param proofs Indicates whether proof generation should be
* enabled.
**/
public Goal mkGoal(boolean models, boolean unsatCores, boolean proofs)
{
return new Goal(this, models, unsatCores, proofs);
}
/**
* Creates a new ParameterSet.
**/
public Params mkParams()
{
return new Params(this);
}
/**
* The number of supported tactics.
**/
public int getNumTactics()
{
return Native.getNumTactics(nCtx());
}
/**
* The names of all supported tactics.
**/
public String[] getTacticNames()
{
int n = getNumTactics();
String[] res = new String[n];
for (int i = 0; i < n; i++)
res[i] = Native.getTacticName(nCtx(), i);
return res;
}
/**
* Returns a string containing a description of the tactic with the given
* name.
**/
public String getTacticDescription(String name)
{
return Native.tacticGetDescr(nCtx(), name);
}
/**
* Creates a new Tactic.
**/
public Tactic mkTactic(String name)
{
return new Tactic(this, name);
}
/**
* Create a tactic that applies {@code t1} to a Goal and then
* {@code t2} to every subgoal produced by {@code t1}
**/
public Tactic andThen(Tactic t1, Tactic t2, Tactic... ts)
{
checkContextMatch(t1);
checkContextMatch(t2);
checkContextMatch(ts);
long last = 0;
if (ts != null && ts.length > 0)
{
last = ts[ts.length - 1].getNativeObject();
for (int i = ts.length - 2; i >= 0; i--) {
last = Native.tacticAndThen(nCtx(), ts[i].getNativeObject(),
last);
}
}
if (last != 0)
{
last = Native.tacticAndThen(nCtx(), t2.getNativeObject(), last);
return new Tactic(this, Native.tacticAndThen(nCtx(),
t1.getNativeObject(), last));
} else
return new Tactic(this, Native.tacticAndThen(nCtx(),
t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Create a tactic that applies {@code t1} to a Goal and then
* {@code t2} to every subgoal produced by {@code t1}
*
* Remarks: Shorthand for {@code AndThen}.
**/
public Tactic then(Tactic t1, Tactic t2, Tactic... ts)
{
return andThen(t1, t2, ts);
}
/**
* Create a tactic that first applies {@code t1} to a Goal and if
* it fails then returns the result of {@code t2} applied to the
* Goal.
**/
public Tactic orElse(Tactic t1, Tactic t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new Tactic(this, Native.tacticOrElse(nCtx(),
t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Create a tactic that applies {@code t} to a goal for {@code ms} milliseconds.
* Remarks: If {@code t} does not
* terminate within {@code ms} milliseconds, then it fails.
*
**/
public Tactic tryFor(Tactic t, int ms)
{
checkContextMatch(t);
return new Tactic(this, Native.tacticTryFor(nCtx(),
t.getNativeObject(), ms));
}
/**
* Create a tactic that applies {@code t} to a given goal if the
* probe {@code p} evaluates to true.
* Remarks: If {@code p} evaluates to false, then the new tactic behaves like the
* {@code skip} tactic.
**/
public Tactic when(Probe p, Tactic t)
{
checkContextMatch(t);
checkContextMatch(p);
return new Tactic(this, Native.tacticWhen(nCtx(), p.getNativeObject(),
t.getNativeObject()));
}
/**
* Create a tactic that applies {@code t1} to a given goal if the
* probe {@code p} evaluates to true and {@code t2}
* otherwise.
**/
public Tactic cond(Probe p, Tactic t1, Tactic t2)
{
checkContextMatch(p);
checkContextMatch(t1);
checkContextMatch(t2);
return new Tactic(this, Native.tacticCond(nCtx(), p.getNativeObject(),
t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Create a tactic that keeps applying {@code t} until the goal
* is not modified anymore or the maximum number of iterations {@code max} is reached.
**/
public Tactic repeat(Tactic t, int max)
{
checkContextMatch(t);
return new Tactic(this, Native.tacticRepeat(nCtx(),
t.getNativeObject(), max));
}
/**
* Create a tactic that just returns the given goal.
**/
public Tactic skip()
{
return new Tactic(this, Native.tacticSkip(nCtx()));
}
/**
* Create a tactic always fails.
**/
public Tactic fail()
{
return new Tactic(this, Native.tacticFail(nCtx()));
}
/**
* Create a tactic that fails if the probe {@code p} evaluates to
* false.
**/
public Tactic failIf(Probe p)
{
checkContextMatch(p);
return new Tactic(this,
Native.tacticFailIf(nCtx(), p.getNativeObject()));
}
/**
* Create a tactic that fails if the goal is not trivially satisfiable (i.e.,
* empty) or trivially unsatisfiable (i.e., contains `false').
**/
public Tactic failIfNotDecided()
{
return new Tactic(this, Native.tacticFailIfNotDecided(nCtx()));
}
/**
* Create a tactic that applies {@code t} using the given set of
* parameters {@code p}.
**/
public Tactic usingParams(Tactic t, Params p)
{
checkContextMatch(t);
checkContextMatch(p);
return new Tactic(this, Native.tacticUsingParams(nCtx(),
t.getNativeObject(), p.getNativeObject()));
}
/**
* Create a tactic that applies {@code t} using the given set of
* parameters {@code p}.
* Remarks: Alias for
* {@code UsingParams}
**/
public Tactic with(Tactic t, Params p)
{
return usingParams(t, p);
}
/**
* Create a tactic that applies the given tactics in parallel until one of them succeeds (i.e., the first that doesn't fail).
**/
public Tactic parOr(Tactic... t)
{
checkContextMatch(t);
return new Tactic(this, Native.tacticParOr(nCtx(),
Tactic.arrayLength(t), Tactic.arrayToNative(t)));
}
/**
* Create a tactic that applies {@code t1} to a given goal and
* then {@code t2} to every subgoal produced by {@code t1}. The subgoals are processed in parallel.
**/
public Tactic parAndThen(Tactic t1, Tactic t2)
{
checkContextMatch(t1);
checkContextMatch(t2);
return new Tactic(this, Native.tacticParAndThen(nCtx(),
t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Interrupt the execution of a Z3 procedure.
* Remarks: This procedure can be
* used to interrupt: solvers, simplifiers and tactics.
**/
public void interrupt()
{
Native.interrupt(nCtx());
}
/**
* The number of supported simplifiers.
**/
public int getNumSimplifiers()
{
return Native.getNumSimplifiers(nCtx());
}
/**
* The names of all supported simplifiers.
**/
public String[] getSimplifierNames()
{
int n = getNumSimplifiers();
String[] res = new String[n];
for (int i = 0; i < n; i++)
res[i] = Native.getSimplifierName(nCtx(), i);
return res;
}
/**
* Returns a string containing a description of the simplifier with the given
* name.
**/
public String getSimplifierDescription(String name)
{
return Native.simplifierGetDescr(nCtx(), name);
}
/**
* Creates a new Simplifier.
**/
public Simplifier mkSimplifier(String name)
{
return new Simplifier(this, name);
}
/**
* Create a simplifier that applies {@code t1} and then {@code t1}
**/
public Simplifier andThen(Simplifier t1, Simplifier t2, Simplifier... ts)
{
checkContextMatch(t1);
checkContextMatch(t2);
checkContextMatch(ts);
long last = 0;
if (ts != null && ts.length > 0)
{
last = ts[ts.length - 1].getNativeObject();
for (int i = ts.length - 2; i >= 0; i--) {
last = Native.simplifierAndThen(nCtx(), ts[i].getNativeObject(),
last);
}
}
if (last != 0)
{
last = Native.simplifierAndThen(nCtx(), t2.getNativeObject(), last);
return new Simplifier(this, Native.simplifierAndThen(nCtx(),
t1.getNativeObject(), last));
} else
return new Simplifier(this, Native.simplifierAndThen(nCtx(),
t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Create a simplifier that applies {@code t1} and then {@code t2}
*
* Remarks: Shorthand for {@code AndThen}.
**/
public Simplifier then(Simplifier t1, Simplifier t2, Simplifier... ts)
{
return andThen(t1, t2, ts);
}
/**
* Create a simplifier that applies {@code t} using the given set of
* parameters {@code p}.
**/
public Simplifier usingParams(Simplifier t, Params p)
{
checkContextMatch(t);
checkContextMatch(p);
return new Simplifier(this, Native.simplifierUsingParams(nCtx(),
t.getNativeObject(), p.getNativeObject()));
}
/**
* Create a simplifier that applies {@code t} using the given set of
* parameters {@code p}.
* Remarks: Alias for
* {@code UsingParams}
**/
public Simplifier with(Simplifier t, Params p)
{
return usingParams(t, p);
}
/**
* The number of supported Probes.
**/
public int getNumProbes()
{
return Native.getNumProbes(nCtx());
}
/**
* The names of all supported Probes.
**/
public String[] getProbeNames()
{
int n = getNumProbes();
String[] res = new String[n];
for (int i = 0; i < n; i++)
res[i] = Native.getProbeName(nCtx(), i);
return res;
}
/**
* Returns a string containing a description of the probe with the given
* name.
**/
public String getProbeDescription(String name)
{
return Native.probeGetDescr(nCtx(), name);
}
/**
* Creates a new Probe.
**/
public Probe mkProbe(String name)
{
return new Probe(this, name);
}
/**
* Create a probe that always evaluates to {@code val}.
**/
public Probe constProbe(double val)
{
return new Probe(this, Native.probeConst(nCtx(), val));
}
/**
* Create a probe that evaluates to {@code true} when the value returned by
* {@code p1} is less than the value returned by {@code p2}
**/
public Probe lt(Probe p1, Probe p2)
{
checkContextMatch(p1);
checkContextMatch(p2);
return new Probe(this, Native.probeLt(nCtx(), p1.getNativeObject(),
p2.getNativeObject()));
}
/**
* Create a probe that evaluates to {@code true} when the value returned by
* {@code p1} is greater than the value returned by {@code p2}
**/
public Probe gt(Probe p1, Probe p2)
{
checkContextMatch(p1);
checkContextMatch(p2);
return new Probe(this, Native.probeGt(nCtx(), p1.getNativeObject(),
p2.getNativeObject()));
}
/**
* Create a probe that evaluates to {@code true} when the value returned by
* {@code p1} is less than or equal the value returned by
* {@code p2}
**/
public Probe le(Probe p1, Probe p2)
{
checkContextMatch(p1);
checkContextMatch(p2);
return new Probe(this, Native.probeLe(nCtx(), p1.getNativeObject(),
p2.getNativeObject()));
}
/**
* Create a probe that evaluates to {@code true} when the value returned by
* {@code p1} is greater than or equal the value returned by
* {@code p2}
**/
public Probe ge(Probe p1, Probe p2)
{
checkContextMatch(p1);
checkContextMatch(p2);
return new Probe(this, Native.probeGe(nCtx(), p1.getNativeObject(),
p2.getNativeObject()));
}
/**
* Create a probe that evaluates to {@code true} when the value returned by
* {@code p1} is equal to the value returned by {@code p2}
**/
public Probe eq(Probe p1, Probe p2)
{
checkContextMatch(p1);
checkContextMatch(p2);
return new Probe(this, Native.probeEq(nCtx(), p1.getNativeObject(),
p2.getNativeObject()));
}
/**
* Create a probe that evaluates to {@code true} when the value {@code p1} and {@code p2} evaluate to {@code true}.
**/
public Probe and(Probe p1, Probe p2)
{
checkContextMatch(p1);
checkContextMatch(p2);
return new Probe(this, Native.probeAnd(nCtx(), p1.getNativeObject(),
p2.getNativeObject()));
}
/**
* Create a probe that evaluates to {@code true} when the value {@code p1} or {@code p2} evaluate to {@code true}.
**/
public Probe or(Probe p1, Probe p2)
{
checkContextMatch(p1);
checkContextMatch(p2);
return new Probe(this, Native.probeOr(nCtx(), p1.getNativeObject(),
p2.getNativeObject()));
}
/**
* Create a probe that evaluates to {@code true} when the value {@code p} does not evaluate to {@code true}.
**/
public Probe not(Probe p)
{
checkContextMatch(p);
return new Probe(this, Native.probeNot(nCtx(), p.getNativeObject()));
}
/**
* Creates a new (incremental) solver.
* Remarks: This solver also uses a set
* of builtin tactics for handling the first check-sat command, and
* check-sat commands that take more than a given number of milliseconds to
* be solved.
**/
public Solver mkSolver()
{
return mkSolver((Symbol) null);
}
/**
* Creates a new (incremental) solver.
* Remarks: This solver also uses a set
* of builtin tactics for handling the first check-sat command, and
* check-sat commands that take more than a given number of milliseconds to
* be solved.
**/
public Solver mkSolver(Symbol logic)
{
if (logic == null)
return new Solver(this, Native.mkSolver(nCtx()));
else
return new Solver(this, Native.mkSolverForLogic(nCtx(),
logic.getNativeObject()));
}
/**
* Creates a new (incremental) solver.
* @see #mkSolver(Symbol)
**/
public Solver mkSolver(String logic)
{
return mkSolver(mkSymbol(logic));
}
/**
* Creates a new (incremental) solver.
**/
public Solver mkSimpleSolver()
{
return new Solver(this, Native.mkSimpleSolver(nCtx()));
}
/**
* Creates a solver that is implemented using the given tactic.
* Remarks:
* The solver supports the commands {@code Push} and {@code Pop},
* but it will always solve each check from scratch.
**/
public Solver mkSolver(Tactic t)
{
return new Solver(this, Native.mkSolverFromTactic(nCtx(),
t.getNativeObject()));
}
/**
* Creates a solver that is uses the simplifier pre-processing.
**/
public Solver mkSolver(Solver s, Simplifier simp)
{
return new Solver(this, Native.solverAddSimplifier(nCtx(), s.getNativeObject(), simp.getNativeObject()));
}
/**
* Create a Fixedpoint context.
**/
public Fixedpoint mkFixedpoint()
{
return new Fixedpoint(this);
}
/**
* Create a Optimize context.
**/
public Optimize mkOptimize()
{
return new Optimize(this);
}
/**
* Create the floating-point RoundingMode sort.
* @throws Z3Exception
**/
public FPRMSort mkFPRoundingModeSort()
{
return new FPRMSort(this);
}
/**
* Create a numeral of RoundingMode sort which represents the NearestTiesToEven rounding mode.
* @throws Z3Exception
**/
public FPRMExpr mkFPRoundNearestTiesToEven()
{
return new FPRMExpr(this, Native.mkFpaRoundNearestTiesToEven(nCtx()));
}
/**
* Create a numeral of RoundingMode sort which represents the NearestTiesToEven rounding mode.
* @throws Z3Exception
**/
public FPRMNum mkFPRNE()
{
return new FPRMNum(this, Native.mkFpaRne(nCtx()));
}
/**
* Create a numeral of RoundingMode sort which represents the NearestTiesToAway rounding mode.
* @throws Z3Exception
**/
public FPRMNum mkFPRoundNearestTiesToAway()
{
return new FPRMNum(this, Native.mkFpaRoundNearestTiesToAway(nCtx()));
}
/**
* Create a numeral of RoundingMode sort which represents the NearestTiesToAway rounding mode.
* @throws Z3Exception
**/
public FPRMNum mkFPRNA()
{
return new FPRMNum(this, Native.mkFpaRna(nCtx()));
}
/**
* Create a numeral of RoundingMode sort which represents the RoundTowardPositive rounding mode.
* @throws Z3Exception
**/
public FPRMNum mkFPRoundTowardPositive()
{
return new FPRMNum(this, Native.mkFpaRoundTowardPositive(nCtx()));
}
/**
* Create a numeral of RoundingMode sort which represents the RoundTowardPositive rounding mode.
* @throws Z3Exception
**/
public FPRMNum mkFPRTP()
{
return new FPRMNum(this, Native.mkFpaRtp(nCtx()));
}
/**
* Create a numeral of RoundingMode sort which represents the RoundTowardNegative rounding mode.
* @throws Z3Exception
**/
public FPRMNum mkFPRoundTowardNegative()
{
return new FPRMNum(this, Native.mkFpaRoundTowardNegative(nCtx()));
}
/**
* Create a numeral of RoundingMode sort which represents the RoundTowardNegative rounding mode.
* @throws Z3Exception
**/
public FPRMNum mkFPRTN()
{
return new FPRMNum(this, Native.mkFpaRtn(nCtx()));
}
/**
* Create a numeral of RoundingMode sort which represents the RoundTowardZero rounding mode.
* @throws Z3Exception
**/
public FPRMNum mkFPRoundTowardZero()
{
return new FPRMNum(this, Native.mkFpaRoundTowardZero(nCtx()));
}
/**
* Create a numeral of RoundingMode sort which represents the RoundTowardZero rounding mode.
* @throws Z3Exception
**/
public FPRMNum mkFPRTZ()
{
return new FPRMNum(this, Native.mkFpaRtz(nCtx()));
}
/**
* Create a FloatingPoint sort.
* @param ebits exponent bits in the FloatingPoint sort.
* @param sbits significand bits in the FloatingPoint sort.
* @throws Z3Exception
**/
public FPSort mkFPSort(int ebits, int sbits)
{
return new FPSort(this, ebits, sbits);
}
/**
* Create the half-precision (16-bit) FloatingPoint sort.
* @throws Z3Exception
**/
public FPSort mkFPSortHalf()
{
return new FPSort(this, Native.mkFpaSortHalf(nCtx()));
}
/**
* Create the half-precision (16-bit) FloatingPoint sort.
* @throws Z3Exception
**/
public FPSort mkFPSort16()
{
return new FPSort(this, Native.mkFpaSort16(nCtx()));
}
/**
* Create the single-precision (32-bit) FloatingPoint sort.
* @throws Z3Exception
**/
public FPSort mkFPSortSingle()
{
return new FPSort(this, Native.mkFpaSortSingle(nCtx()));
}
/**
* Create the single-precision (32-bit) FloatingPoint sort.
* @throws Z3Exception
**/
public FPSort mkFPSort32()
{
return new FPSort(this, Native.mkFpaSort32(nCtx()));
}
/**
* Create the double-precision (64-bit) FloatingPoint sort.
* @throws Z3Exception
**/
public FPSort mkFPSortDouble()
{
return new FPSort(this, Native.mkFpaSortDouble(nCtx()));
}
/**
* Create the double-precision (64-bit) FloatingPoint sort.
* @throws Z3Exception
**/
public FPSort mkFPSort64()
{
return new FPSort(this, Native.mkFpaSort64(nCtx()));
}
/**
* Create the quadruple-precision (128-bit) FloatingPoint sort.
* @throws Z3Exception
**/
public FPSort mkFPSortQuadruple()
{
return new FPSort(this, Native.mkFpaSortQuadruple(nCtx()));
}
/**
* Create the quadruple-precision (128-bit) FloatingPoint sort.
* @throws Z3Exception
**/
public FPSort mkFPSort128()
{
return new FPSort(this, Native.mkFpaSort128(nCtx()));
}
/**
* Create a NaN of sort s.
* @param s FloatingPoint sort.
* @throws Z3Exception
**/
public FPNum mkFPNaN(FPSort s)
{
return new FPNum(this, Native.mkFpaNan(nCtx(), s.getNativeObject()));
}
/**
* Create a floating-point infinity of sort s.
* @param s FloatingPoint sort.
* @param negative indicates whether the result should be negative.
* @throws Z3Exception
**/
public FPNum mkFPInf(FPSort s, boolean negative)
{
return new FPNum(this, Native.mkFpaInf(nCtx(), s.getNativeObject(), negative));
}
/**
* Create a floating-point zero of sort s.
* @param s FloatingPoint sort.
* @param negative indicates whether the result should be negative.
* @throws Z3Exception
**/
public FPNum mkFPZero(FPSort s, boolean negative)
{
return new FPNum(this, Native.mkFpaZero(nCtx(), s.getNativeObject(), negative));
}
/**
* Create a numeral of FloatingPoint sort from a float.
* @param v numeral value.
* @param s FloatingPoint sort.
* @throws Z3Exception
**/
public FPNum mkFPNumeral(float v, FPSort s)
{
return new FPNum(this, Native.mkFpaNumeralFloat(nCtx(), v, s.getNativeObject()));
}
/**
* Create a numeral of FloatingPoint sort from a double.
* @param v numeral value.
* @param s FloatingPoint sort.
* @throws Z3Exception
**/
public FPNum mkFPNumeral(double v, FPSort s)
{
return new FPNum(this, Native.mkFpaNumeralDouble(nCtx(), v, s.getNativeObject()));
}
/**
* Create a numeral of FloatingPoint sort from an int.
* @param v numeral value.
* @param s FloatingPoint sort.
* @throws Z3Exception
**/
public FPNum mkFPNumeral(int v, FPSort s)
{
return new FPNum(this, Native.mkFpaNumeralInt(nCtx(), v, s.getNativeObject()));
}
/**
* Create a numeral of FloatingPoint sort from a sign bit and two integers.
* @param sgn the sign.
* @param exp the exponent.
* @param sig the significand.
* @param s FloatingPoint sort.
* @throws Z3Exception
**/
public FPNum mkFPNumeral(boolean sgn, int exp, int sig, FPSort s)
{
return new FPNum(this, Native.mkFpaNumeralIntUint(nCtx(), sgn, exp, sig, s.getNativeObject()));
}
/**
* Create a numeral of FloatingPoint sort from a sign bit and two 64-bit integers.
* @param sgn the sign.
* @param exp the exponent.
* @param sig the significand.
* @param s FloatingPoint sort.
* @throws Z3Exception
**/
public FPNum mkFPNumeral(boolean sgn, long exp, long sig, FPSort s)
{
return new FPNum(this, Native.mkFpaNumeralInt64Uint64(nCtx(), sgn, exp, sig, s.getNativeObject()));
}
/**
* Create a numeral of FloatingPoint sort from a float.
* @param v numeral value.
* @param s FloatingPoint sort.
* @throws Z3Exception
**/
public FPNum mkFP(float v, FPSort s)
{
return mkFPNumeral(v, s);
}
/**
* Create a numeral of FloatingPoint sort from a double.
* @param v numeral value.
* @param s FloatingPoint sort.
* @throws Z3Exception
**/
public FPNum mkFP(double v, FPSort s)
{
return mkFPNumeral(v, s);
}
/**
* Create a numeral of FloatingPoint sort from an int.
* @param v numeral value.
* @param s FloatingPoint sort.
* @throws Z3Exception
**/
public FPNum mkFP(int v, FPSort s)
{
return mkFPNumeral(v, s);
}
/**
* Create a numeral of FloatingPoint sort from a sign bit and two integers.
* @param sgn the sign.
* @param exp the exponent.
* @param sig the significand.
* @param s FloatingPoint sort.
* @throws Z3Exception
**/
public FPNum mkFP(boolean sgn, int exp, int sig, FPSort s)
{
return mkFPNumeral(sgn, exp, sig, s);
}
/**
* Create a numeral of FloatingPoint sort from a sign bit and two 64-bit integers.
* @param sgn the sign.
* @param exp the exponent.
* @param sig the significand.
* @param s FloatingPoint sort.
* @throws Z3Exception
**/
public FPNum mkFP(boolean sgn, long exp, long sig, FPSort s)
{
return mkFPNumeral(sgn, exp, sig, s);
}
/**
* Floating-point absolute value
* @param t floating-point term
* @throws Z3Exception
**/
public FPExpr mkFPAbs(Expr<FPSort> t)
{
return new FPExpr(this, Native.mkFpaAbs(nCtx(), t.getNativeObject()));
}
/**
* Floating-point negation
* @param t floating-point term
* @throws Z3Exception
**/
public FPExpr mkFPNeg(Expr<FPSort> t)
{
return new FPExpr(this, Native.mkFpaNeg(nCtx(), t.getNativeObject()));
}
/**
* Floating-point addition
* @param rm rounding mode term
* @param t1 floating-point term
* @param t2 floating-point term
* @throws Z3Exception
**/
public FPExpr mkFPAdd(Expr<FPRMSort> rm, Expr<FPSort> t1, Expr<FPSort> t2)
{
return new FPExpr(this, Native.mkFpaAdd(nCtx(), rm.getNativeObject(), t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Floating-point subtraction
* @param rm rounding mode term
* @param t1 floating-point term
* @param t2 floating-point term
* @throws Z3Exception
**/
public FPExpr mkFPSub(Expr<FPRMSort> rm, Expr<FPSort> t1, Expr<FPSort> t2)
{
return new FPExpr(this, Native.mkFpaSub(nCtx(), rm.getNativeObject(), t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Floating-point multiplication
* @param rm rounding mode term
* @param t1 floating-point term
* @param t2 floating-point term
* @throws Z3Exception
**/
public FPExpr mkFPMul(Expr<FPRMSort> rm, Expr<FPSort> t1, Expr<FPSort> t2)
{
return new FPExpr(this, Native.mkFpaMul(nCtx(), rm.getNativeObject(), t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Floating-point division
* @param rm rounding mode term
* @param t1 floating-point term
* @param t2 floating-point term
* @throws Z3Exception
**/
public FPExpr mkFPDiv(Expr<FPRMSort> rm, Expr<FPSort> t1, Expr<FPSort> t2)
{
return new FPExpr(this, Native.mkFpaDiv(nCtx(), rm.getNativeObject(), t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Floating-point fused multiply-add
* @param rm rounding mode term
* @param t1 floating-point term
* @param t2 floating-point term
* @param t3 floating-point term
* Remarks:
* The result is round((t1 * t2) + t3)
* @throws Z3Exception
**/
public FPExpr mkFPFMA(Expr<FPRMSort> rm, Expr<FPSort> t1, Expr<FPSort> t2, Expr<FPSort> t3)
{
return new FPExpr(this, Native.mkFpaFma(nCtx(), rm.getNativeObject(), t1.getNativeObject(), t2.getNativeObject(), t3.getNativeObject()));
}
/**
* Floating-point square root
* @param rm rounding mode term
* @param t floating-point term
* @throws Z3Exception
**/
public FPExpr mkFPSqrt(Expr<FPRMSort> rm, Expr<FPSort> t)
{
return new FPExpr(this, Native.mkFpaSqrt(nCtx(), rm.getNativeObject(), t.getNativeObject()));
}
/**
* Floating-point remainder
* @param t1 floating-point term
* @param t2 floating-point term
* @throws Z3Exception
**/
public FPExpr mkFPRem(Expr<FPSort> t1, Expr<FPSort> t2)
{
return new FPExpr(this, Native.mkFpaRem(nCtx(), t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Floating-point roundToIntegral. Rounds a floating-point number to
* the closest integer, again represented as a floating-point number.
* @param rm term of RoundingMode sort
* @param t floating-point term
* @throws Z3Exception
**/
public FPExpr mkFPRoundToIntegral(Expr<FPRMSort> rm, Expr<FPSort> t)
{
return new FPExpr(this, Native.mkFpaRoundToIntegral(nCtx(), rm.getNativeObject(), t.getNativeObject()));
}
/**
* Minimum of floating-point numbers.
* @param t1 floating-point term
* @param t2 floating-point term
* @throws Z3Exception
**/
public FPExpr mkFPMin(Expr<FPSort> t1, Expr<FPSort> t2)
{
return new FPExpr(this, Native.mkFpaMin(nCtx(), t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Maximum of floating-point numbers.
* @param t1 floating-point term
* @param t2 floating-point term
* @throws Z3Exception
**/
public FPExpr mkFPMax(Expr<FPSort> t1, Expr<FPSort> t2)
{
return new FPExpr(this, Native.mkFpaMax(nCtx(), t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Floating-point less than or equal.
* @param t1 floating-point term
* @param t2 floating-point term
* @throws Z3Exception
**/
public BoolExpr mkFPLEq(Expr<FPSort> t1, Expr<FPSort> t2)
{
return new BoolExpr(this, Native.mkFpaLeq(nCtx(), t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Floating-point less than.
* @param t1 floating-point term
* @param t2 floating-point term
* @throws Z3Exception
**/
public BoolExpr mkFPLt(Expr<FPSort> t1, Expr<FPSort> t2)
{
return new BoolExpr(this, Native.mkFpaLt(nCtx(), t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Floating-point greater than or equal.
* @param t1 floating-point term
* @param t2 floating-point term
* @throws Z3Exception
**/
public BoolExpr mkFPGEq(Expr<FPSort> t1, Expr<FPSort> t2)
{
return new BoolExpr(this, Native.mkFpaGeq(nCtx(), t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Floating-point greater than.
* @param t1 floating-point term
* @param t2 floating-point term
* @throws Z3Exception
**/
public BoolExpr mkFPGt(Expr<FPSort> t1, Expr<FPSort> t2)
{
return new BoolExpr(this, Native.mkFpaGt(nCtx(), t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Floating-point equality.
* @param t1 floating-point term
* @param t2 floating-point term
* Remarks:
* Note that this is IEEE 754 equality (as opposed to standard =).
* @throws Z3Exception
**/
public BoolExpr mkFPEq(Expr<FPSort> t1, Expr<FPSort> t2)
{
return new BoolExpr(this, Native.mkFpaEq(nCtx(), t1.getNativeObject(), t2.getNativeObject()));
}
/**
* Predicate indicating whether t is a normal floating-point number.\
* @param t floating-point term
* @throws Z3Exception
**/
public BoolExpr mkFPIsNormal(Expr<FPSort> t)
{
return new BoolExpr(this, Native.mkFpaIsNormal(nCtx(), t.getNativeObject()));
}
/**
* Predicate indicating whether t is a subnormal floating-point number.\
* @param t floating-point term
* @throws Z3Exception
**/
public BoolExpr mkFPIsSubnormal(Expr<FPSort> t)
{
return new BoolExpr(this, Native.mkFpaIsSubnormal(nCtx(), t.getNativeObject()));
}
/**
* Predicate indicating whether t is a floating-point number with zero value, i.e., +0 or -0.
* @param t floating-point term
* @throws Z3Exception
**/
public BoolExpr mkFPIsZero(Expr<FPSort> t)
{
return new BoolExpr(this, Native.mkFpaIsZero(nCtx(), t.getNativeObject()));
}
/**
* Predicate indicating whether t is a floating-point number representing +oo or -oo.
* @param t floating-point term
* @throws Z3Exception
**/
public BoolExpr mkFPIsInfinite(Expr<FPSort> t)
{
return new BoolExpr(this, Native.mkFpaIsInfinite(nCtx(), t.getNativeObject()));
}
/**
* Predicate indicating whether t is a NaN.
* @param t floating-point term
* @throws Z3Exception
**/
public BoolExpr mkFPIsNaN(Expr<FPSort> t)
{
return new BoolExpr(this, Native.mkFpaIsNan(nCtx(), t.getNativeObject()));
}
/**
* Predicate indicating whether t is a negative floating-point number.
* @param t floating-point term
* @throws Z3Exception
**/
public BoolExpr mkFPIsNegative(Expr<FPSort> t)
{
return new BoolExpr(this, Native.mkFpaIsNegative(nCtx(), t.getNativeObject()));
}
/**
* Predicate indicating whether t is a positive floating-point number.
* @param t floating-point term
* @throws Z3Exception
**/
public BoolExpr mkFPIsPositive(Expr<FPSort> t)
{
return new BoolExpr(this, Native.mkFpaIsPositive(nCtx(), t.getNativeObject()));
}
/**
* Create an expression of FloatingPoint sort from three bit-vector expressions.
* @param sgn bit-vector term (of size 1) representing the sign.
* @param sig bit-vector term representing the significand.
* @param exp bit-vector term representing the exponent.
* Remarks:
* This is the operator named `fp' in the SMT FP theory definition.
* Note that sgn is required to be a bit-vector of size 1. Significand and exponent
* are required to be greater than 1 and 2 respectively. The FloatingPoint sort
* of the resulting expression is automatically determined from the bit-vector sizes
* of the arguments.
* @throws Z3Exception
**/
public FPExpr mkFP(Expr<BitVecSort> sgn, Expr<BitVecSort> sig, Expr<BitVecSort> exp)
{
return new FPExpr(this, Native.mkFpaFp(nCtx(), sgn.getNativeObject(), sig.getNativeObject(), exp.getNativeObject()));
}
/**
* Conversion of a single IEEE 754-2008 bit-vector into a floating-point number.
* @param bv bit-vector value (of size m).
* @param s FloatingPoint sort (ebits+sbits == m)
* Remarks:
* Produces a term that represents the conversion of a bit-vector term bv to a
* floating-point term of sort s. The bit-vector size of bv (m) must be equal
* to ebits+sbits of s. The format of the bit-vector is as defined by the
* IEEE 754-2008 interchange format.
* @throws Z3Exception
**/
public FPExpr mkFPToFP(Expr<BitVecSort> bv, FPSort s)
{
return new FPExpr(this, Native.mkFpaToFpBv(nCtx(), bv.getNativeObject(), s.getNativeObject()));
}
/**
* Conversion of a FloatingPoint term into another term of different FloatingPoint sort.
* @param rm RoundingMode term.
* @param t FloatingPoint term.
* @param s FloatingPoint sort.
* Remarks:
* Produces a term that represents the conversion of a floating-point term t to a
* floating-point term of sort s. If necessary, the result will be rounded according
* to rounding mode rm.
* @throws Z3Exception
**/
public FPExpr mkFPToFP(Expr<FPRMSort> rm, FPExpr t, FPSort s)
{
return new FPExpr(this, Native.mkFpaToFpFloat(nCtx(), rm.getNativeObject(), t.getNativeObject(), s.getNativeObject()));
}
/**
* Conversion of a term of real sort into a term of FloatingPoint sort.
* @param rm RoundingMode term.
* @param t term of Real sort.
* @param s FloatingPoint sort.
* Remarks:
* Produces a term that represents the conversion of term t of real sort into a
* floating-point term of sort s. If necessary, the result will be rounded according
* to rounding mode rm.
* @throws Z3Exception
**/
public FPExpr mkFPToFP(Expr<FPRMSort> rm, RealExpr t, FPSort s)
{
return new FPExpr(this, Native.mkFpaToFpReal(nCtx(), rm.getNativeObject(), t.getNativeObject(), s.getNativeObject()));
}
/**
* Conversion of a 2's complement signed bit-vector term into a term of FloatingPoint sort.
* @param rm RoundingMode term.
* @param t term of bit-vector sort.
* @param s FloatingPoint sort.
* @param signed flag indicating whether t is interpreted as signed or unsigned bit-vector.
* Remarks:
* Produces a term that represents the conversion of the bit-vector term t into a
* floating-point term of sort s. The bit-vector t is taken to be in signed
* 2's complement format (when signed==true, otherwise unsigned). If necessary, the
* result will be rounded according to rounding mode rm.
* @throws Z3Exception
**/
public FPExpr mkFPToFP(Expr<FPRMSort> rm, Expr<BitVecSort> t, FPSort s, boolean signed)
{
if (signed)
return new FPExpr(this, Native.mkFpaToFpSigned(nCtx(), rm.getNativeObject(), t.getNativeObject(), s.getNativeObject()));
else
return new FPExpr(this, Native.mkFpaToFpUnsigned(nCtx(), rm.getNativeObject(), t.getNativeObject(), s.getNativeObject()));
}
/**
* Conversion of a floating-point number to another FloatingPoint sort s.
* @param s FloatingPoint sort
* @param rm floating-point rounding mode term
* @param t floating-point term
* Remarks:
* Produces a term that represents the conversion of a floating-point term t to a different
* FloatingPoint sort s. If necessary, rounding according to rm is applied.
* @throws Z3Exception
**/
public FPExpr mkFPToFP(FPSort s, Expr<FPRMSort> rm, Expr<FPSort> t)
{
return new FPExpr(this, Native.mkFpaToFpFloat(nCtx(), s.getNativeObject(), rm.getNativeObject(), t.getNativeObject()));
}
/**
* Conversion of a floating-point term into a bit-vector.
* @param rm RoundingMode term.
* @param t FloatingPoint term
* @param sz Size of the resulting bit-vector.
* @param signed Indicates whether the result is a signed or unsigned bit-vector.
* Remarks:
* Produces a term that represents the conversion of the floating-point term t into a
* bit-vector term of size sz in 2's complement format (signed when signed==true). If necessary,
* the result will be rounded according to rounding mode rm.
* @throws Z3Exception
**/
public BitVecExpr mkFPToBV(Expr<FPRMSort> rm, Expr<FPSort> t, int sz, boolean signed)
{
if (signed)
return new BitVecExpr(this, Native.mkFpaToSbv(nCtx(), rm.getNativeObject(), t.getNativeObject(), sz));
else
return new BitVecExpr(this, Native.mkFpaToUbv(nCtx(), rm.getNativeObject(), t.getNativeObject(), sz));
}
/**
* Conversion of a floating-point term into a real-numbered term.
* @param t FloatingPoint term
* Remarks:
* Produces a term that represents the conversion of the floating-point term t into a
* real number. Note that this type of conversion will often result in non-linear
* constraints over real terms.
* @throws Z3Exception
**/
public RealExpr mkFPToReal(Expr<FPSort> t)
{
return new RealExpr(this, Native.mkFpaToReal(nCtx(), t.getNativeObject()));
}
/**
* Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format.
* @param t FloatingPoint term.
* Remarks:
* The size of the resulting bit-vector is automatically determined. Note that
* IEEE 754-2008 allows multiple different representations of NaN. This conversion
* knows only one NaN and it will always produce the same bit-vector representation of
* that NaN.
* @throws Z3Exception
**/
public BitVecExpr mkFPToIEEEBV(Expr<FPSort> t)
{
return new BitVecExpr(this, Native.mkFpaToIeeeBv(nCtx(), t.getNativeObject()));
}
/**
* Conversion of a real-sorted significand and an integer-sorted exponent into a term of FloatingPoint sort.
* @param rm RoundingMode term.
* @param exp Exponent term of Int sort.
* @param sig Significand term of Real sort.
* @param s FloatingPoint sort.
* Remarks:
* Produces a term that represents the conversion of sig * 2^exp into a
* floating-point term of sort s. If necessary, the result will be rounded
* according to rounding mode rm.
* @throws Z3Exception
**/
public BitVecExpr mkFPToFP(Expr<FPRMSort> rm, Expr<IntSort> exp, Expr<RealSort> sig, FPSort s)
{
return new BitVecExpr(this, Native.mkFpaToFpIntReal(nCtx(), rm.getNativeObject(), exp.getNativeObject(), sig.getNativeObject(), s.getNativeObject()));
}
/**
* Creates or a linear order.
* @param index The index of the order.
* @param sort The sort of the order.
*/
public final <R extends Sort> FuncDecl<BoolSort> mkLinearOrder(R sort, int index) {
return (FuncDecl<BoolSort>) FuncDecl.create(
this,
Native.mkLinearOrder(
nCtx(),
sort.getNativeObject(),
index
)
);
}
/**
* Creates or a partial order.
* @param index The index of the order.
* @param sort The sort of the order.
*/
public final <R extends Sort> FuncDecl<BoolSort> mkPartialOrder(R sort, int index) {
return (FuncDecl<BoolSort>) FuncDecl.create(
this,
Native.mkPartialOrder(
nCtx(),
sort.getNativeObject(),
index
)
);
}
/**
* Wraps an AST.
* Remarks: This function is used for transitions between
* native and managed objects. Note that {@code nativeObject}
* must be a native object obtained from Z3 (e.g., through
* {@code UnwrapAST}) and that it must have a correct reference count.
* @see Native#incRef
* @see #unwrapAST
* @param nativeObject The native pointer to wrap.
**/
public AST wrapAST(long nativeObject)
{
return AST.create(this, nativeObject);
}
/**
* Unwraps an AST.
* Remarks: This function is used for transitions between
* native and managed objects. It returns the native pointer to the AST.
* Note that AST objects are reference counted and unwrapping an AST
* disables automatic reference counting, i.e., all references to the IntPtr
* that is returned must be handled externally and through native calls (see
* e.g.,
* @see Native#incRef
* @see #wrapAST
* @param a The AST to unwrap.
**/
public long unwrapAST(AST a)
{
return a.getNativeObject();
}
/**
* Return a string describing all available parameters to
* {@code Expr.Simplify}.
**/
public String SimplifyHelp()
{
return Native.simplifyGetHelp(nCtx());
}
/**
* Retrieves parameter descriptions for simplifier.
**/
public ParamDescrs getSimplifyParameterDescriptions()
{
return new ParamDescrs(this, Native.simplifyGetParamDescrs(nCtx()));
}
/**
* Update a mutable configuration parameter.
* Remarks: The list of all
* configuration parameters can be obtained using the Z3 executable:
* {@code z3.exe -ini?} Only a few configuration parameters are mutable
* once the context is created. An exception is thrown when trying to modify
* an immutable parameter.
**/
public void updateParamValue(String id, String value)
{
Native.updateParamValue(nCtx(), id, value);
}
public long nCtx()
{
if (m_ctx == 0)
throw new Z3Exception("Context closed");
return m_ctx;
}
void checkContextMatch(Z3Object other)
{
if (this != other.getContext())
throw new Z3Exception("Context mismatch");
}
void checkContextMatch(Z3Object other1, Z3Object other2)
{
checkContextMatch(other1);
checkContextMatch(other2);
}
void checkContextMatch(Z3Object other1, Z3Object other2, Z3Object other3)
{
checkContextMatch(other1);
checkContextMatch(other2);
checkContextMatch(other3);
}
void checkContextMatch(Z3Object[] arr)
{
if (arr != null)
for (Z3Object a : arr)
checkContextMatch(a);
}
private Z3ReferenceQueue m_RefQueue = new Z3ReferenceQueue(this);
Z3ReferenceQueue getReferenceQueue() { return m_RefQueue; }
/**
* Disposes of the context.
**/
@Override
public void close()
{
if (m_ctx == 0)
return;
m_RefQueue.forceClear();
m_boolSort = null;
m_intSort = null;
m_realSort = null;
m_stringSort = null;
m_RefQueue = null;
synchronized (creation_lock) {
Native.delContext(m_ctx);
}
m_ctx = 0;
}
}
| Z3Prover/z3 | src/api/java/Context.java |
2,715 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.benchmark.vector;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.index.IndexVersion;
import org.elasticsearch.script.field.vectors.BinaryDenseVector;
import org.elasticsearch.script.field.vectors.ByteBinaryDenseVector;
import org.elasticsearch.script.field.vectors.ByteKnnDenseVector;
import org.elasticsearch.script.field.vectors.KnnDenseVector;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OperationsPerInvocation;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
/**
* Various benchmarks for the distance functions
* used by indexed and non-indexed vectors.
* Parameters include element, dims, function, and type.
* For individual local tests it may be useful to increase
* fork, measurement, and operations per invocation. (Note
* to also update the benchmark loop if operations per invocation
* is increased.)
*/
@Fork(1)
@Warmup(iterations = 1)
@Measurement(iterations = 2)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@OperationsPerInvocation(25000)
@State(Scope.Benchmark)
public class DistanceFunctionBenchmark {
@Param({ "float", "byte" })
private String element;
@Param({ "96" })
private int dims;
@Param({ "dot", "cosine", "l1", "l2" })
private String function;
@Param({ "knn", "binary" })
private String type;
private abstract static class BenchmarkFunction {
final int dims;
private BenchmarkFunction(int dims) {
this.dims = dims;
}
abstract void execute(Consumer<Object> consumer);
}
private abstract static class KnnFloatBenchmarkFunction extends BenchmarkFunction {
final float[] docVector;
final float[] queryVector;
private KnnFloatBenchmarkFunction(int dims, boolean normalize) {
super(dims);
docVector = new float[dims];
queryVector = new float[dims];
float docMagnitude = 0f;
float queryMagnitude = 0f;
for (int i = 0; i < dims; ++i) {
docVector[i] = (float) (dims - i);
queryVector[i] = (float) i;
docMagnitude += (float) (dims - i);
queryMagnitude += (float) i;
}
docMagnitude /= dims;
queryMagnitude /= dims;
if (normalize) {
for (int i = 0; i < dims; ++i) {
docVector[i] /= docMagnitude;
queryVector[i] /= queryMagnitude;
}
}
}
}
private abstract static class BinaryFloatBenchmarkFunction extends BenchmarkFunction {
final BytesRef docVector;
final float[] docFloatVector;
final float[] queryVector;
private BinaryFloatBenchmarkFunction(int dims, boolean normalize) {
super(dims);
docFloatVector = new float[dims];
queryVector = new float[dims];
float docMagnitude = 0f;
float queryMagnitude = 0f;
for (int i = 0; i < dims; ++i) {
docFloatVector[i] = (float) (dims - i);
queryVector[i] = (float) i;
docMagnitude += (float) (dims - i);
queryMagnitude += (float) i;
}
docMagnitude /= dims;
queryMagnitude /= dims;
ByteBuffer byteBuffer = ByteBuffer.allocate(dims * 4 + 4);
for (int i = 0; i < dims; ++i) {
if (normalize) {
docFloatVector[i] /= docMagnitude;
queryVector[i] /= queryMagnitude;
}
byteBuffer.putFloat(docFloatVector[i]);
}
byteBuffer.putFloat(docMagnitude);
this.docVector = new BytesRef(byteBuffer.array());
}
}
private abstract static class KnnByteBenchmarkFunction extends BenchmarkFunction {
final byte[] docVector;
final byte[] queryVector;
final float queryMagnitude;
private KnnByteBenchmarkFunction(int dims) {
super(dims);
ByteBuffer docVector = ByteBuffer.allocate(dims);
queryVector = new byte[dims];
float queryMagnitude = 0f;
for (int i = 0; i < dims; ++i) {
docVector.put((byte) (dims - i));
queryVector[i] = (byte) i;
queryMagnitude += (float) i;
}
this.docVector = docVector.array();
this.queryMagnitude = queryMagnitude / dims;
}
}
private abstract static class BinaryByteBenchmarkFunction extends BenchmarkFunction {
final BytesRef docVector;
final byte[] vectorValue;
final byte[] queryVector;
final float queryMagnitude;
private BinaryByteBenchmarkFunction(int dims) {
super(dims);
ByteBuffer docVector = ByteBuffer.allocate(dims + 4);
queryVector = new byte[dims];
vectorValue = new byte[dims];
float docMagnitude = 0f;
float queryMagnitude = 0f;
for (int i = 0; i < dims; ++i) {
docVector.put((byte) (dims - i));
vectorValue[i] = (byte) (dims - i);
queryVector[i] = (byte) i;
docMagnitude += (float) (dims - i);
queryMagnitude += (float) i;
}
docVector.putFloat(docMagnitude / dims);
this.docVector = new BytesRef(docVector.array());
this.queryMagnitude = queryMagnitude / dims;
}
}
private static class DotKnnFloatBenchmarkFunction extends KnnFloatBenchmarkFunction {
private DotKnnFloatBenchmarkFunction(int dims) {
super(dims, false);
}
@Override
public void execute(Consumer<Object> consumer) {
new KnnDenseVector(docVector).dotProduct(queryVector);
}
}
private static class DotKnnByteBenchmarkFunction extends KnnByteBenchmarkFunction {
private DotKnnByteBenchmarkFunction(int dims) {
super(dims);
}
@Override
public void execute(Consumer<Object> consumer) {
new ByteKnnDenseVector(docVector).dotProduct(queryVector);
}
}
private static class DotBinaryFloatBenchmarkFunction extends BinaryFloatBenchmarkFunction {
private DotBinaryFloatBenchmarkFunction(int dims) {
super(dims, false);
}
@Override
public void execute(Consumer<Object> consumer) {
new BinaryDenseVector(docFloatVector, docVector, dims, IndexVersion.current()).dotProduct(queryVector);
}
}
private static class DotBinaryByteBenchmarkFunction extends BinaryByteBenchmarkFunction {
private DotBinaryByteBenchmarkFunction(int dims) {
super(dims);
}
@Override
public void execute(Consumer<Object> consumer) {
new ByteBinaryDenseVector(vectorValue, docVector, dims).dotProduct(queryVector);
}
}
private static class CosineKnnFloatBenchmarkFunction extends KnnFloatBenchmarkFunction {
private CosineKnnFloatBenchmarkFunction(int dims) {
super(dims, true);
}
@Override
public void execute(Consumer<Object> consumer) {
new KnnDenseVector(docVector).cosineSimilarity(queryVector, false);
}
}
private static class CosineKnnByteBenchmarkFunction extends KnnByteBenchmarkFunction {
private CosineKnnByteBenchmarkFunction(int dims) {
super(dims);
}
@Override
public void execute(Consumer<Object> consumer) {
new ByteKnnDenseVector(docVector).cosineSimilarity(queryVector, queryMagnitude);
}
}
private static class CosineBinaryFloatBenchmarkFunction extends BinaryFloatBenchmarkFunction {
private CosineBinaryFloatBenchmarkFunction(int dims) {
super(dims, true);
}
@Override
public void execute(Consumer<Object> consumer) {
new BinaryDenseVector(docFloatVector, docVector, dims, IndexVersion.current()).cosineSimilarity(queryVector, false);
}
}
private static class CosineBinaryByteBenchmarkFunction extends BinaryByteBenchmarkFunction {
private CosineBinaryByteBenchmarkFunction(int dims) {
super(dims);
}
@Override
public void execute(Consumer<Object> consumer) {
new ByteBinaryDenseVector(vectorValue, docVector, dims).cosineSimilarity(queryVector, queryMagnitude);
}
}
private static class L1KnnFloatBenchmarkFunction extends KnnFloatBenchmarkFunction {
private L1KnnFloatBenchmarkFunction(int dims) {
super(dims, false);
}
@Override
public void execute(Consumer<Object> consumer) {
new KnnDenseVector(docVector).l1Norm(queryVector);
}
}
private static class L1KnnByteBenchmarkFunction extends KnnByteBenchmarkFunction {
private L1KnnByteBenchmarkFunction(int dims) {
super(dims);
}
@Override
public void execute(Consumer<Object> consumer) {
new ByteKnnDenseVector(docVector).l1Norm(queryVector);
}
}
private static class L1BinaryFloatBenchmarkFunction extends BinaryFloatBenchmarkFunction {
private L1BinaryFloatBenchmarkFunction(int dims) {
super(dims, true);
}
@Override
public void execute(Consumer<Object> consumer) {
new BinaryDenseVector(docFloatVector, docVector, dims, IndexVersion.current()).l1Norm(queryVector);
}
}
private static class L1BinaryByteBenchmarkFunction extends BinaryByteBenchmarkFunction {
private L1BinaryByteBenchmarkFunction(int dims) {
super(dims);
}
@Override
public void execute(Consumer<Object> consumer) {
new ByteBinaryDenseVector(vectorValue, docVector, dims).l1Norm(queryVector);
}
}
private static class L2KnnFloatBenchmarkFunction extends KnnFloatBenchmarkFunction {
private L2KnnFloatBenchmarkFunction(int dims) {
super(dims, false);
}
@Override
public void execute(Consumer<Object> consumer) {
new KnnDenseVector(docVector).l2Norm(queryVector);
}
}
private static class L2KnnByteBenchmarkFunction extends KnnByteBenchmarkFunction {
private L2KnnByteBenchmarkFunction(int dims) {
super(dims);
}
@Override
public void execute(Consumer<Object> consumer) {
new ByteKnnDenseVector(docVector).l2Norm(queryVector);
}
}
private static class L2BinaryFloatBenchmarkFunction extends BinaryFloatBenchmarkFunction {
private L2BinaryFloatBenchmarkFunction(int dims) {
super(dims, true);
}
@Override
public void execute(Consumer<Object> consumer) {
new BinaryDenseVector(docFloatVector, docVector, dims, IndexVersion.current()).l1Norm(queryVector);
}
}
private static class L2BinaryByteBenchmarkFunction extends BinaryByteBenchmarkFunction {
private L2BinaryByteBenchmarkFunction(int dims) {
super(dims);
}
@Override
public void execute(Consumer<Object> consumer) {
consumer.accept(new ByteBinaryDenseVector(vectorValue, docVector, dims).l2Norm(queryVector));
}
}
private BenchmarkFunction benchmarkFunction;
@Setup
public void setBenchmarkFunction() {
switch (element) {
case "float" -> {
switch (function) {
case "dot" -> benchmarkFunction = switch (type) {
case "knn" -> new DotKnnFloatBenchmarkFunction(dims);
case "binary" -> new DotBinaryFloatBenchmarkFunction(dims);
default -> throw new UnsupportedOperationException("unexpected type [" + type + "]");
};
case "cosine" -> benchmarkFunction = switch (type) {
case "knn" -> new CosineKnnFloatBenchmarkFunction(dims);
case "binary" -> new CosineBinaryFloatBenchmarkFunction(dims);
default -> throw new UnsupportedOperationException("unexpected type [" + type + "]");
};
case "l1" -> benchmarkFunction = switch (type) {
case "knn" -> new L1KnnFloatBenchmarkFunction(dims);
case "binary" -> new L1BinaryFloatBenchmarkFunction(dims);
default -> throw new UnsupportedOperationException("unexpected type [" + type + "]");
};
case "l2" -> benchmarkFunction = switch (type) {
case "knn" -> new L2KnnFloatBenchmarkFunction(dims);
case "binary" -> new L2BinaryFloatBenchmarkFunction(dims);
default -> throw new UnsupportedOperationException("unexpected type [" + type + "]");
};
default -> throw new UnsupportedOperationException("unexpected function [" + function + "]");
}
}
case "byte" -> {
switch (function) {
case "dot" -> benchmarkFunction = switch (type) {
case "knn" -> new DotKnnByteBenchmarkFunction(dims);
case "binary" -> new DotBinaryByteBenchmarkFunction(dims);
default -> throw new UnsupportedOperationException("unexpected type [" + type + "]");
};
case "cosine" -> benchmarkFunction = switch (type) {
case "knn" -> new CosineKnnByteBenchmarkFunction(dims);
case "binary" -> new CosineBinaryByteBenchmarkFunction(dims);
default -> throw new UnsupportedOperationException("unexpected type [" + type + "]");
};
case "l1" -> benchmarkFunction = switch (type) {
case "knn" -> new L1KnnByteBenchmarkFunction(dims);
case "binary" -> new L1BinaryByteBenchmarkFunction(dims);
default -> throw new UnsupportedOperationException("unexpected type [" + type + "]");
};
case "l2" -> benchmarkFunction = switch (type) {
case "knn" -> new L2KnnByteBenchmarkFunction(dims);
case "binary" -> new L2BinaryByteBenchmarkFunction(dims);
default -> throw new UnsupportedOperationException("unexpected type [" + type + "]");
};
default -> throw new UnsupportedOperationException("unexpected function [" + function + "]");
}
}
default -> throw new UnsupportedOperationException("unexpected element [" + element + "]");
}
;
}
@Benchmark
public void benchmark() throws IOException {
for (int i = 0; i < 25000; ++i) {
benchmarkFunction.execute(Object::toString);
}
}
}
| elastic/elasticsearch | benchmarks/src/main/java/org/elasticsearch/benchmark/vector/DistanceFunctionBenchmark.java |
2,716 | /*
* Copyright (c) 2016-present, RxJava Contributors.
*
* 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 io.reactivex.rxjava3.core;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.*;
import org.reactivestreams.Publisher;
import io.reactivex.rxjava3.functions.*;
@BenchmarkMode(Mode.Throughput)
@Warmup(iterations = 5)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@OutputTimeUnit(TimeUnit.SECONDS)
@Fork(value = 1)
@State(Scope.Thread)
public class ToFlowablePerf {
@Param({ "1", "1000", "1000000" })
public int times;
Maybe<Integer> flowable;
Flowable<Integer> flowableInner;
Observable<Integer> observable;
Observable<Integer> observableInner;
@Setup
public void setup() {
Integer[] array = new Integer[times];
Arrays.fill(array, 777);
Flowable<Integer> source = Flowable.fromArray(array);
final BiFunction<Integer, Integer, Integer> second = new BiFunction<Integer, Integer, Integer>() {
@Override
public Integer apply(Integer a, Integer b) {
return b;
}
};
flowable = source.reduce(second);
flowableInner = source.concatMap(new Function<Integer, Publisher<Integer>>() {
@Override
public Publisher<Integer> apply(Integer v) {
return Flowable.range(1, 50).reduce(second).toFlowable();
}
});
Observable<Integer> sourceObs = Observable.fromArray(array);
observable = sourceObs.reduce(second).toObservable();
observableInner = sourceObs.concatMap(new Function<Integer, Observable<Integer>>() {
@Override
public Observable<Integer> apply(Integer v) {
return Observable.range(1, 50).reduce(second).toObservable();
}
});
}
@Benchmark
public Object flowable() {
return flowable.blockingGet();
}
@Benchmark
public Object flowableInner() {
return flowableInner.blockingLast();
}
@Benchmark
public Object observable() {
return observable.blockingLast();
}
@Benchmark
public Object observableInner() {
return observableInner.blockingLast();
}
static volatile Object o;
public static void main(String[] args) {
ToFlowablePerf p = new ToFlowablePerf();
p.times = 1000000;
p.setup();
for (int j = 0; j < 15; j++) {
for (int i = 0; i < 600; i++) {
o = p.flowable();
}
System.out.println("--- " + j);
}
}
}
| ReactiveX/RxJava | src/jmh/java/io/reactivex/rxjava3/core/ToFlowablePerf.java |
2,717 | /*
* Copyright 2012-2024 the original author or authors.
*
* 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
*
* https://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 org.springframework.boot.logging.java;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import org.springframework.boot.io.ApplicationResourceLoader;
import org.springframework.boot.logging.AbstractLoggingSystem;
import org.springframework.boot.logging.LogFile;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggerConfiguration;
import org.springframework.boot.logging.LoggingInitializationContext;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.boot.logging.LoggingSystemFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
/**
* {@link LoggingSystem} for {@link Logger java.util.logging}.
*
* @author Phillip Webb
* @author Dave Syer
* @author Andy Wilkinson
* @author Ben Hale
* @since 1.0.0
*/
public class JavaLoggingSystem extends AbstractLoggingSystem {
private static final LogLevels<Level> LEVELS = new LogLevels<>();
static {
LEVELS.map(LogLevel.TRACE, Level.FINEST);
LEVELS.map(LogLevel.DEBUG, Level.FINE);
LEVELS.map(LogLevel.INFO, Level.INFO);
LEVELS.map(LogLevel.WARN, Level.WARNING);
LEVELS.map(LogLevel.ERROR, Level.SEVERE);
LEVELS.map(LogLevel.FATAL, Level.SEVERE);
LEVELS.map(LogLevel.OFF, Level.OFF);
}
private final Set<Logger> configuredLoggers = Collections.synchronizedSet(new HashSet<>());
public JavaLoggingSystem(ClassLoader classLoader) {
super(classLoader);
}
@Override
protected String[] getStandardConfigLocations() {
return new String[] { "logging.properties" };
}
@Override
public void beforeInitialize() {
super.beforeInitialize();
Logger.getLogger("").setLevel(Level.SEVERE);
}
@Override
protected void loadDefaults(LoggingInitializationContext initializationContext, LogFile logFile) {
if (logFile != null) {
loadConfiguration(getPackagedConfigFile("logging-file.properties"), logFile);
}
else {
loadConfiguration(getPackagedConfigFile("logging.properties"), null);
}
}
@Override
protected void loadConfiguration(LoggingInitializationContext initializationContext, String location,
LogFile logFile) {
loadConfiguration(location, logFile);
}
protected void loadConfiguration(String location, LogFile logFile) {
Assert.notNull(location, "Location must not be null");
try {
Resource resource = new ApplicationResourceLoader().getResource(location);
String configuration = FileCopyUtils.copyToString(new InputStreamReader(resource.getInputStream()));
if (logFile != null) {
configuration = configuration.replace("${LOG_FILE}", StringUtils.cleanPath(logFile.toString()));
}
LogManager.getLogManager().readConfiguration(new ByteArrayInputStream(configuration.getBytes()));
}
catch (Exception ex) {
throw new IllegalStateException("Could not initialize Java logging from " + location, ex);
}
}
@Override
public Set<LogLevel> getSupportedLogLevels() {
return LEVELS.getSupported();
}
@Override
public void setLogLevel(String loggerName, LogLevel level) {
if (loggerName == null || ROOT_LOGGER_NAME.equals(loggerName)) {
loggerName = "";
}
Logger logger = Logger.getLogger(loggerName);
if (logger != null) {
this.configuredLoggers.add(logger);
logger.setLevel(LEVELS.convertSystemToNative(level));
}
}
@Override
public List<LoggerConfiguration> getLoggerConfigurations() {
List<LoggerConfiguration> result = new ArrayList<>();
Enumeration<String> names = LogManager.getLogManager().getLoggerNames();
while (names.hasMoreElements()) {
result.add(getLoggerConfiguration(names.nextElement()));
}
result.sort(CONFIGURATION_COMPARATOR);
return Collections.unmodifiableList(result);
}
@Override
public LoggerConfiguration getLoggerConfiguration(String loggerName) {
Logger logger = Logger.getLogger(loggerName);
if (logger == null) {
return null;
}
LogLevel level = LEVELS.convertNativeToSystem(logger.getLevel());
LogLevel effectiveLevel = LEVELS.convertNativeToSystem(getEffectiveLevel(logger));
String name = (StringUtils.hasLength(logger.getName()) ? logger.getName() : ROOT_LOGGER_NAME);
return new LoggerConfiguration(name, level, effectiveLevel);
}
private Level getEffectiveLevel(Logger root) {
Logger logger = root;
while (logger.getLevel() == null) {
logger = logger.getParent();
}
return logger.getLevel();
}
@Override
public Runnable getShutdownHandler() {
return () -> LogManager.getLogManager().reset();
}
@Override
public void cleanUp() {
this.configuredLoggers.clear();
}
/**
* {@link LoggingSystemFactory} that returns {@link JavaLoggingSystem} if possible.
*/
@Order(Ordered.LOWEST_PRECEDENCE)
public static class Factory implements LoggingSystemFactory {
private static final boolean PRESENT = ClassUtils.isPresent("java.util.logging.LogManager",
Factory.class.getClassLoader());
@Override
public LoggingSystem getLoggingSystem(ClassLoader classLoader) {
if (PRESENT) {
return new JavaLoggingSystem(classLoader);
}
return null;
}
}
}
| spring-projects/spring-boot | spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/java/JavaLoggingSystem.java |
2,718 | package me.chanjar.weixin.cp.bean;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import me.chanjar.weixin.cp.bean.workbench.WorkBenchKeyData;
import me.chanjar.weixin.cp.bean.workbench.WorkBenchList;
import me.chanjar.weixin.cp.constant.WxCpConsts;
import java.io.Serializable;
import java.util.List;
/**
* The type Wx cp agent work bench.
*
* @author songshiyu created on : create in 16:09 2020/9/27 工作台自定义展示
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class WxCpAgentWorkBench implements Serializable {
private static final long serialVersionUID = -4136604790232843229L;
/**
* 展示类型,目前支持 “keydata”、 “image”、 “list” 、”webview”
*/
private String type;
/**
* 用户的userid
*/
private String userId;
/**
* 应用id
*/
private Long agentId;
/**
* 点击跳转url,若不填且应用设置了主页url,则跳转到主页url,否则跳到应用会话窗口
*/
private String jumpUrl;
/**
* 若应用为小程序类型,该字段填小程序pagepath,若未设置,跳到小程序主页
*/
private String pagePath;
/**
* 图片url:图片的最佳比例为3.35:1;webview:渲染展示的url
*/
private String url;
/**
* 是否覆盖用户工作台的数据。设置为true的时候,会覆盖企业所有用户当前设置的数据。若设置为false,则不会覆盖用户当前设置的所有数据
*/
private Boolean replaceUserData;
private List<WorkBenchKeyData> keyDataList;
private List<WorkBenchList> lists;
/**
* 生成模板Json字符串
*
* @return the string
*/
public String toTemplateString() {
JsonObject templateObject = new JsonObject();
templateObject.addProperty("agentid", this.agentId);
templateObject.addProperty("type", this.type);
if (this.replaceUserData != null) {
templateObject.addProperty("replace_user_data", this.replaceUserData);
}
this.handle(templateObject);
return templateObject.toString();
}
/**
* 生成用户数据Json字符串
*
* @return the string
*/
public String toUserDataString() {
JsonObject userDataObject = new JsonObject();
userDataObject.addProperty("agentid", this.agentId);
userDataObject.addProperty("userid", this.userId);
userDataObject.addProperty("type", this.type);
this.handle(userDataObject);
return userDataObject.toString();
}
/**
* 处理不用类型的工作台数据
*/
private void handle(JsonObject templateObject) {
switch (this.getType()) {
case WxCpConsts.WorkBenchType.KEYDATA: {
JsonArray keyDataArray = new JsonArray();
JsonObject itemsObject = new JsonObject();
for (WorkBenchKeyData keyDataItem : this.keyDataList) {
JsonObject keyDataObject = new JsonObject();
keyDataObject.addProperty("key", keyDataItem.getKey());
keyDataObject.addProperty("data", keyDataItem.getData());
keyDataObject.addProperty("jump_url", keyDataItem.getJumpUrl());
keyDataObject.addProperty("pagepath", keyDataItem.getPagePath());
keyDataArray.add(keyDataObject);
}
itemsObject.add("items", keyDataArray);
templateObject.add("keydata", itemsObject);
break;
}
case WxCpConsts.WorkBenchType.IMAGE: {
JsonObject image = new JsonObject();
image.addProperty("url", this.url);
image.addProperty("jump_url", this.jumpUrl);
image.addProperty("pagepath", this.pagePath);
templateObject.add("image", image);
break;
}
case WxCpConsts.WorkBenchType.LIST: {
JsonArray listArray = new JsonArray();
JsonObject itemsObject = new JsonObject();
for (WorkBenchList listItem : this.lists) {
JsonObject listObject = new JsonObject();
listObject.addProperty("title", listItem.getTitle());
listObject.addProperty("jump_url", listItem.getJumpUrl());
listObject.addProperty("pagepath", listItem.getPagePath());
listArray.add(listObject);
}
itemsObject.add("items", listArray);
templateObject.add("list", itemsObject);
break;
}
case WxCpConsts.WorkBenchType.WEBVIEW: {
JsonObject webview = new JsonObject();
webview.addProperty("url", this.url);
webview.addProperty("jump_url", this.jumpUrl);
webview.addProperty("pagepath", this.pagePath);
templateObject.add("webview", webview);
break;
}
default: {
//do nothing
}
}
}
}
| Wechat-Group/WxJava | weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpAgentWorkBench.java |
2,719 | package edu.stanford.nlp.coref.data;
import java.util.Arrays;
import java.util.Set;
import edu.stanford.nlp.util.Generics;
/** Word lists for Chinese and English used in the coref system.
*
* @author Heeyoung Lee
* @author Rob Voigt
* @author Christopher Manning
*/
public class WordLists {
private WordLists() { } // just variable declarations
//
// WordLists for English
//
public static final Set<String> reportVerbEn = Generics.newHashSet(Arrays.asList(
"accuse", "acknowledge", "add", "admit", "advise", "agree", "alert",
"allege", "announce", "answer", "apologize", "argue",
"ask", "assert", "assure", "beg", "blame", "boast",
"caution", "charge", "cite", "claim", "clarify", "command", "comment",
"compare", "complain", "concede", "conclude", "confirm", "confront", "congratulate",
"contend", "contradict", "convey", "counter", "criticize",
"debate", "decide", "declare", "defend", "demand", "demonstrate", "deny",
"describe", "determine", "disagree", "disclose", "discount", "discover", "discuss",
"dismiss", "dispute", "disregard", "doubt", "emphasize", "encourage", "endorse",
"equate", "estimate", "expect", "explain", "express", "extol", "fear", "feel",
"find", "forbid", "forecast", "foretell", "forget", "gather", "guarantee", "guess",
"hear", "hint", "hope", "illustrate", "imagine", "imply", "indicate", "inform",
"insert", "insist", "instruct", "interpret", "interview", "invite", "issue",
"justify", "learn", "maintain", "mean", "mention", "negotiate", "note",
"observe", "offer", "oppose", "order", "persuade", "pledge", "point", "point out",
"praise", "pray", "predict", "prefer", "present", "promise", "prompt", "propose",
"protest", "prove", "provoke", "question", "quote", "raise", "rally", "read",
"reaffirm", "realise", "realize", "rebut", "recall", "reckon", "recommend", "refer",
"reflect", "refuse", "refute", "reiterate", "reject", "relate", "remark",
"remember", "remind", "repeat", "reply", "report", "request", "respond",
"restate", "reveal", "rule", "say", "see", "show", "shout", "signal", "sing",
"slam", "speculate", "spoke", "spread", "state", "stipulate", "stress",
"suggest", "support", "suppose", "surmise", "suspect", "swear", "teach",
"tell", "testify", "think", "threaten", "told", "uncover", "underline",
"underscore", "urge", "voice", "vow", "warn", "welcome",
"wish", "wonder", "worry", "write"));
public static final Set<String> reportNounEn = Generics.newHashSet(Arrays.asList(
"acclamation", "account", "accusation", "acknowledgment", "address", "addressing",
"admission", "advertisement", "advice", "advisory", "affidavit", "affirmation", "alert",
"allegation", "analysis", "anecdote", "annotation", "announcement", "answer", "antiphon",
"apology", "applause", "appreciation", "argument", "arraignment", "article", "articulation",
"aside", "assertion", "asseveration", "assurance", "attestation", "attitude",
"averment", "avouchment", "avowal", "axiom", "backcap", "band-aid", "basic", "belief", "bestowal",
"bill", "blame", "blow-by-blow", "bomb", "book", "bow", "break", "breakdown", "brief", "briefing",
"broadcast", "broadcasting", "bulletin", "buzz", "cable", "calendar", "call", "canard", "canon",
"card", "cause", "censure", "certification", "characterization", "charge", "chat", "chatter",
"chitchat", "chronicle", "chronology", "citation", "claim", "clarification", "close", "cognizance",
"comeback", "comment", "commentary", "communication", "communique", "composition", "concept",
"concession", "conference", "confession", "confirmation", "conjecture", "connotation", "construal",
"construction", "consultation", "contention", "contract", "convention", "conversation", "converse",
"conviction", "counterclaim", "credenda", "creed", "critique",
"cry", "declaration", "defense", "definition", "delineation", "delivery", "demonstration",
"denial", "denotation", "depiction", "deposition", "description", "detail", "details", "detention",
"dialogue", "diction", "dictum", "digest", "directive", "disclosure", "discourse", "discovery",
"discussion", "dispatch", "display", "disquisition", "dissemination", "dissertation", "divulgence",
"dogma", "editorial", "ejaculation", "emphasis", "enlightenment",
"enunciation", "essay", "evidence", "examination", "example", "excerpt", "exclamation",
"excuse", "execution", "exegesis", "explanation", "explication", "exposing", "exposition", "expounding",
"expression", "eye-opener", "feedback", "fiction", "findings", "fingerprint", "flash", "formulation",
"fundamental", "gift", "gloss", "goods", "gospel", "gossip", "gratitude", "greeting",
"guarantee", "hail", "hailing", "handout", "hash", "headlines", "hearing", "hearsay",
"ideas", "idiom", "illustration", "impeachment", "implantation", "implication", "imputation",
"incrimination", "indication", "indoctrination", "inference", "info", "information",
"innuendo", "insinuation", "insistence", "instruction", "intelligence", "interpretation", "interview",
"intimation", "intonation", "issue", "item", "itemization", "justification", "key", "knowledge",
"leak", "letter", "locution", "manifesto",
"meaning", "meeting", "mention", "message", "missive", "mitigation", "monograph", "motive", "murmur",
"narration", "narrative", "news", "nod", "note", "notice", "notification", "oath", "observation",
"okay", "opinion", "oral", "outline", "paper", "parley", "particularization", "phrase", "phraseology",
"phrasing", "picture", "piece", "pipeline", "pitch", "plea", "plot", "portraiture", "portrayal",
"position", "potboiler", "prating", "precept", "prediction", "presentation", "presentment", "principle",
"proclamation", "profession", "program", "promulgation", "pronouncement", "pronunciation", "propaganda",
"prophecy", "proposal", "proposition", "prosecution", "protestation", "publication", "publicity",
"publishing", "quotation", "ratification", "reaction", "reason", "rebuttal", "receipt", "recital",
"recitation", "recognition", "record", "recount", "recountal", "refutation", "regulation", "rehearsal",
"rejoinder", "relation", "release", "remark", "rendition", "repartee", "reply", "report", "reporting",
"representation", "resolution", "response", "result", "retort", "return", "revelation", "review",
"rule", "rumble", "rumor", "rundown", "saying", "scandal", "scoop",
"scuttlebutt", "sense", "showing", "sign", "signature", "significance", "sketch", "skinny", "solution",
"speaking", "specification", "speech", "statement", "story", "study", "style", "suggestion",
"summarization", "summary", "summons", "tale", "talk", "talking", "tattle", "telecast",
"telegram", "telling", "tenet", "term", "testimonial", "testimony", "text", "theme", "thesis",
"tract", "tractate", "tradition", "translation", "treatise", "utterance", "vent", "ventilation",
"verbalization", "version", "vignette", "vindication", "warning",
"warrant", "whispering", "wire", "word", "work", "writ", "write-up", "writeup", "writing",
"acceptance", "complaint", "concern", "disappointment", "disclose", "estimate", "laugh", "pleasure", "regret",
"resentment", "view"));
public static final Set<String> nonWordsEn = Generics.newHashSet(Arrays.asList("mm", "hmm", "ahem", "um"));
public static final Set<String> copulasEn = Generics.newHashSet(Arrays.asList("is","are","were", "was","be", "been","become","became","becomes","seem","seemed","seems","remain","remains","remained"));
public static final Set<String> quantifiersEn = Generics.newHashSet(Arrays.asList("not","every","any","none","everything","anything","nothing","all","enough"));
public static final Set<String> partsEn = Generics.newHashSet(Arrays.asList("half","one","two","three","four","five","six","seven","eight","nine","ten","hundred","thousand","million","billion","tens","dozens","hundreds","thousands","millions","billions","group","groups","bunch","number","numbers","pinch","amount","amount","total","all","mile","miles","pounds"));
public static final Set<String> temporalsEn = Generics.newHashSet(Arrays.asList(
"second", "minute", "hour", "day", "week", "month", "year", "decade", "century", "millennium",
"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", "now",
"yesterday", "tomorrow", "age", "time", "era", "epoch", "morning", "evening", "day", "night", "noon", "afternoon",
"semester", "trimester", "quarter", "term", "winter", "spring", "summer", "fall", "autumn", "season",
"january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"));
public static final Set<String> femalePronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "her", "hers", "herself", "she" }));
public static final Set<String> malePronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "he", "him", "himself", "his" }));
public static final Set<String> neutralPronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "it", "its", "itself", "where", "here", "there", "which" }));
public static final Set<String> possessivePronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "my", "your", "his", "her", "its","our","their","whose" }));
public static final Set<String> otherPronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "who", "whom", "whose", "where", "when","which" }));
public static final Set<String> thirdPersonPronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "he", "him", "himself", "his", "she", "her", "herself", "hers", "her", "it", "itself", "its", "one", "oneself", "one's", "they", "them", "themself", "themselves", "theirs", "their", "they", "them", "'em", "themselves" }));
public static final Set<String> secondPersonPronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "you", "yourself", "yours", "your", "yourselves" }));
public static final Set<String> firstPersonPronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "i", "me", "myself", "mine", "my", "we", "us", "ourself", "ourselves", "ours", "our" }));
public static final Set<String> moneyPercentNumberPronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "it", "its" }));
public static final Set<String> dateTimePronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "when" }));
public static final Set<String> organizationPronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "it", "its", "they", "their", "them", "which"}));
public static final Set<String> locationPronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "it", "its", "where", "here", "there" }));
public static final Set<String> inanimatePronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "it", "itself", "its", "where", "when" }));
public static final Set<String> animatePronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "i", "me", "myself", "mine", "my", "we", "us", "ourself", "ourselves", "ours", "our", "you", "yourself", "yours", "your", "yourselves", "he", "him", "himself", "his", "she", "her", "herself", "hers", "her", "one", "oneself", "one's", "they", "them", "themself", "themselves", "theirs", "their", "they", "them", "'em", "themselves", "who", "whom", "whose" }));
public static final Set<String> indefinitePronounsEn = Generics.newHashSet(Arrays.asList(new String[]{"another", "anybody", "anyone", "anything", "each", "either", "enough", "everybody", "everyone", "everything", "less", "little", "much", "neither", "no one", "nobody", "nothing", "one", "other", "plenty", "somebody", "someone", "something", "both", "few", "fewer", "many", "others", "several", "all", "any", "more", "most", "none", "some", "such"}));
public static final Set<String> relativePronounsEn = Generics.newHashSet(Arrays.asList(new String[]{"that","who","which","whom","where","whose"}));
public static final Set<String> GPEPronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "it", "itself", "its", "they","where" }));
public static final Set<String> pluralPronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "we", "us", "ourself", "ourselves", "ours", "our", "yourself", "yourselves", "they", "them", "themself", "themselves", "theirs", "their" }));
public static final Set<String> singularPronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "i", "me", "myself", "mine", "my", "yourself", "he", "him", "himself", "his", "she", "her", "herself", "hers", "her", "it", "itself", "its", "one", "oneself", "one's" }));
public static final Set<String> facilityVehicleWeaponPronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "it", "itself", "its", "they", "where" }));
public static final Set<String> miscPronounsEn = Generics.newHashSet(Arrays.asList(new String[]{"it", "itself", "its", "they", "where" }));
public static final Set<String> reflexivePronounsEn = Generics.newHashSet(Arrays.asList(new String[]{"myself", "yourself", "yourselves", "himself", "herself", "itself", "ourselves", "themselves", "oneself"}));
public static final Set<String> transparentNounsEn = Generics.newHashSet(Arrays.asList(new String[]{"bunch", "group",
"breed", "class", "ilk", "kind", "half", "segment", "top", "bottom", "glass", "bottle",
"box", "cup", "gem", "idiot", "unit", "part", "stage", "name", "division", "label", "group", "figure",
"series", "member", "members", "first", "version", "site", "side", "role", "largest", "title", "fourth",
"third", "second", "number", "place", "trio", "two", "one", "longest", "highest", "shortest",
"head", "resident", "collection", "result", "last"
}));
public static final Set<String> stopWordsEn = Generics.newHashSet(Arrays.asList(new String[]{"a", "an", "the", "of", "at",
"on", "upon", "in", "to", "from", "out", "as", "so", "such", "or", "and", "those", "this", "these", "that",
"for", ",", "is", "was", "am", "are", "'s", "been", "were"}));
public static final Set<String> notOrganizationPRPEn = Generics.newHashSet(Arrays.asList(new String[]{"i", "me", "myself",
"mine", "my", "yourself", "he", "him", "himself", "his", "she", "her", "herself", "hers", "here"}));
public static final Set<String> quantifiers2En = Generics.newHashSet(Arrays.asList("all", "both", "neither", "either"));
public static final Set<String> determinersEn = Generics.newHashSet(Arrays.asList("the", "this", "that", "these", "those", "his", "her", "my", "your", "their", "our"));
public static final Set<String> negationsEn = Generics.newHashSet(Arrays.asList("n't","not", "nor", "neither", "never", "no", "non", "any", "none", "nobody", "nothing", "nowhere", "nearly","almost",
"if", "false", "fallacy", "unsuccessfully", "unlikely", "impossible", "improbable", "uncertain", "unsure", "impossibility", "improbability", "cancellation", "breakup", "lack",
"long-stalled", "end", "rejection", "failure", "avoid", "bar", "block", "break", "cancel", "cease", "cut", "decline", "deny", "deprive", "destroy", "excuse",
"fail", "forbid", "forestall", "forget", "halt", "lose", "nullify", "prevent", "refrain", "reject", "rebut", "remain", "refuse", "stop", "suspend", "ward"));
public static final Set<String> neg_relationsEn = Generics.newHashSet(Arrays.asList("prep_without", "prepc_without", "prep_except", "prepc_except", "prep_excluding", "prepx_excluding",
"prep_if", "prepc_if", "prep_whether", "prepc_whether", "prep_away_from", "prepc_away_from", "prep_instead_of", "prepc_instead_of"));
public static final Set<String> modalsEn = Generics.newHashSet(Arrays.asList("can", "could", "may", "might", "must", "should", "would", "seem",
"able", "apparently", "necessarily", "presumably", "probably", "possibly", "reportedly", "supposedly",
"inconceivable", "chance", "impossibility", "improbability", "encouragement", "improbable", "impossible",
"likely", "necessary", "probable", "possible", "uncertain", "unlikely", "unsure", "likelihood", "probability",
"possibility", "eventual", "hypothetical" , "presumed", "supposed", "reported", "apparent"));
//
// WordLists for Chinese
//
public static final Set<String> reportVerbZh = Generics.newHashSet(Arrays.asList(
"说", "讲", "问", "曰", "劝", "唱", "告诉", "报告", "回答", "承认", "描述", "忠告", "解释", "表示", "保证", "感觉", "预测", "预计", "忘记", "希望",
"想象", "暗示", "指示", "证明", "提示", "说服", "提倡", "拒绝", "否认", "欢迎", "怀疑", "总结", "演讲", "争论"));
public static final Set<String> reportNounZh = Generics.newHashSet(Arrays.asList(
"报告", "回答", "描述", "忠告", "解释", "表示", "保证", "感觉", "预测", "预计", "希望", "想象", "暗示", "指示", "证明", "提示", "提倡", "欢迎",
"怀疑", "总结", "演讲", "争论", "意识", "论文", "看法"));
public static final Set<String> nonWordsZh = Generics.newHashSet(Arrays.asList("啊", "嗯", "哦"));
public static final Set<String> copulasZh = Generics.newHashSet(Arrays.asList(new String[]{}));
public static final Set<String> quantifiersZh = Generics.newHashSet(Arrays.asList("所有", "没有", "一些", "有些", "都"));
public static final Set<String> partsZh = Generics.newHashSet(Arrays.asList("半", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "都"));
public static final Set<String> temporalsZh = Generics.newHashSet(Arrays.asList(
"秒", "分钟", "刻", "小时", "钟头", "天", "星期", "礼拜", "月", "年", "年代", "世纪",
"星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日", "星期天", "现在",
"昨天", "明天", "时代", "时间", "时候", "早上", "中午", "下午", "晚上", "天", "夜",
"学期", "冬天", "春天", "夏天", "秋天", "季节",
"一月份", "二月份", "三月份", "四月份", "五月份", "六月份", "七月份", "八月份", "九月份", "十月份", "十一月份", "十二月份"));
public static final Set<String> femalePronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "她", "她们" }));
public static final Set<String> malePronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "他", "他们" }));
public static final Set<String> neutralPronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "它", "它们", "谁", "什么", "那", "那儿", "那个", "那里", "哪", "哪个", "哪儿", "哪里", "这","这儿", "这个", "这里" }));
public static final Set<String> possessivePronounsZh = Generics.newHashSet(Arrays.asList(new String[]{}));
public static final Set<String> otherPronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "谁", "哪里", "哪个", "哪些", "哪儿" }));
public static final Set<String> thirdPersonPronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "她", "她们", "他", "他们" }));
public static final Set<String> secondPersonPronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "你", "你们", "您" }));
public static final Set<String> firstPersonPronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "我", "我们", "咱们", "咱"}));
public static final Set<String> moneyPercentNumberPronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "它" }));
public static final Set<String> dateTimePronounsZh = Generics.newHashSet(Arrays.asList(new String[]{}));
public static final Set<String> organizationPronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "它", "他们", "谁", "什么", "那", "那个", "那里", "哪", "哪个", "哪里", "这", "这个", "这里" }));
public static final Set<String> locationPronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "它", "哪里", "哪个", "这里", "这儿", "那里", "那儿" }));
public static final Set<String> inanimatePronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "它", "它们", "那", "那儿", "那个", "那里", "哪", "哪个", "哪儿", "哪里", "这","这儿", "这个", "这里" }));
public static final Set<String> animatePronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "我", "我们", "你", "你们", "她", "她们", "他", "他们", "谁" }));
public static final Set<String> indefinitePronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "谁", "另外", "任何", "每", "所有", "许多", "一些" }));
public static final Set<String> relativePronounsZh = Generics.newHashSet(); // Chinese doesn't have relative pronouns
public static final Set<String> interrogativePronounsZh = Generics.newHashSet(Arrays.asList(new String[]{"什", "什么时候", "哪边", "怎", "甚么", "谁们", "啥", "干什么", "为何", "哪里", "哪个", "么", "哪", "哪些", "什么样", "多少", "怎样", "怎么样", "为什么", "谁", "怎么", "几", "什么"})); // Need to filter these
public static final Set<String> GPEPronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "它", "它们", "他们", "那", "那儿", "那个", "那里", "哪", "哪个", "哪儿", "哪里", "这","这儿", "这个", "这里" }));
public static final Set<String> pluralPronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "我们", "你们", "她们", "他们", "它们", "咱们" }));
public static final Set<String> singularPronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "我", "你", "您", "她", "他" }));
public static final Set<String> facilityVehicleWeaponPronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "它", "他们", "哪里", "哪儿" }));
public static final Set<String> miscPronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "它", "他们", "哪里", "哪儿" }));
public static final Set<String> reflexivePronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "自己" }));
public static final Set<String> transparentNounsZh = Generics.newHashSet(Arrays.asList(new String[]{}));
public static final Set<String> stopWordsZh = Generics.newHashSet(Arrays.asList(new String[]{ "是", "和", "在" }));
public static final Set<String> notOrganizationPRPZh = Generics.newHashSet(Arrays.asList(new String[]{ "我", "我们", "你", "你们", "她", "她们", "他", "他们" }));
public static final Set<String> quantifiers2Zh = Generics.newHashSet(Arrays.asList( "每", "所有" ));
public static final Set<String> determinersZh = Generics.newHashSet(Arrays.asList( "这", "这个", "这些", "那", "那个", "那些" ));
public static final Set<String> negationsZh = Generics.newHashSet(Arrays.asList( "不", "没", "否", "如果", "可能", "输", "失败", "否认" ));
public static final Set<String> neg_relationsZh = Generics.newHashSet();
public static final Set<String> modalsZh = Generics.newHashSet(Arrays.asList( "能", "可能", "可以", "应该", "必须" ));
public static final Set<String> titleWordsZh = Generics.newHashSet(Arrays.asList(
"总统", "总理", "顾问", "部长", "市长", "省长", "先生", "外长", "教授", "副总理", "副总统",
"大使", "同志", "王妃", "国王", "主席", "王后", "王子", "首相", "经理", "秘书", "女士",
"总经理"));
public static final Set<String> removeWordsZh = Generics.newHashSet(Arrays.asList(
"_", // [cdm] Don't know the source of this one; doesn't seem to be in devset (with gold mentions)
"quot", //"quot" is a formatting error in CoNLL data
// "人", // a little dangerous 14 real cases though many not.
"时候", // okay but rare
// "问题", // dangerous - real case 1/3 of the time
// "情况", // dangerous - real case 1/3 of the time
"未来", // ok
// "战争", // a little dangerous
"可能", // ok
"新华社", // Xinhua news agency -- kind of a cheat, but....
"第一", "第二", "第三", "第四", "第五", "第六", "第七", "第八", "第九", // ordinals - should have regex or NER; there are also some with arabic numerals
"美军", "中央台", "时间" // cdm added these ones
));
public static final Set<String> removeCharsZh = Generics.newHashSet(Arrays.asList(
// "什么的", // in one spurious mention, but caught by general de rule!
// "哪", // slightly dangerous
"什么", // "what" -- good one, this interrogative isn't in mentions
"谁", // "Who" -- good interrogative to have
"啥", // "What"
"哪儿", // "where" -- rare but okay
// "哪里", // "where" but some are mentions
// "人们", // "people" -- dangerous
// "年", // year -- dangerous
"原因", // "reason" -- okay
// "啥时", // doesn't seem to appear in devset; ends in de
// "quot",
"多少" // "How many" [cdm added used to be t ested separately]
));
/** KBP pronominal mentions are at present only 3rd person, non-neuter, non-reflexive pronouns.
* At present we just mix English and Chinese ones, since it does no harm.
*/
private static final Set<String> kbpPronominalMentions = Generics.newHashSet(Arrays.asList(
"he", "him", "his", "she", "her", "hers",
"他", "她", "他们", "她们", "她的", "他的"
));
/**
* Returns whether the given token counts as a valid pronominal mention for KBP.
* This method (at present) works for either Chinese or English.
*
* @param word The token to classify.
* @return true if this token is a pronoun that KBP should recognize (3rd person, non-neuter, non reflexive).
*/
public static boolean isKbpPronominalMention(String word) {
return kbpPronominalMentions.contains(word.toLowerCase());
}
}
| stanfordnlp/CoreNLP | src/edu/stanford/nlp/coref/data/WordLists.java |
2,720 | // This file is part of OpenTSDB.
// Copyright (C) 2010-2014 The OpenTSDB Authors.
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 2.1 of the License, or (at your
// option) any later version. This program is distributed in the hope that it
// will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
// General Public License for more details. You should have received a copy
// of the GNU Lesser General Public License along with this program. If not,
// see <http://www.gnu.org/licenses/>.
package net.opentsdb.tsd;
import java.io.IOException;
import com.stumbleupon.async.Deferred;
import net.opentsdb.core.TSDB;
import net.opentsdb.stats.StatsCollector;
/**
* A plugin that runs along side TSD's built-in HTTP endpoints (like the
* <code>/api</code> endpoints). There can be multiple implementations of
* such plugins per TSD. These plugins run on the same Netty server as
* built-in HTTP endpoints and thus are available on the same port as those
* endpoints. However, these plugins are mounted beneath a special base
* path called <code>/plugin</code>.
*
* <p>Notes on multi-threaded behavior:
* <ul>
* <li>Plugins are created and initialized <strong>once</strong> per instance
* of the TSD. Therefore, these plugins are effectively singletons.
* <li>Plugins will be executed from multiple threads so the {@link #execute}
* and {@link collectStats} methods <strong>must be thread safe</strong>
* with respect to the plugin's internal state and external resources.
* </ul>
* @since 2.2
*/
public abstract class HttpRpcPlugin {
/**
* Called by TSDB to initialize the plugin. This is called <strong>once</strong>
* (and from a single thread) at the time the plugin in loaded.
*
* <p><b>Note:</b> Implementations should throw exceptions if they can't start
* up properly. The TSD will then shutdown so the operator can fix the
* problem. Please use IllegalArgumentException for configuration issues.
*
* @param tsdb The parent TSDB object
* @throws IllegalArgumentException if required configuration parameters are
* missing
* @throws RuntimeException
*/
public abstract void initialize(TSDB tsdb);
/**
* Called to gracefully shutdown the plugin. This is called <strong>once</strong>
* (and from a single thread) at the time the owning TSD is shutting down.
*
* @return A deferred object that indicates the completion of the request.
* The {@link Object} has not special meaning and can be {@code null}
* (think of it as {@code Deferred<Void>}).
*/
public abstract Deferred<Object> shutdown();
/**
* Should return the version of this plugin in the format:
* MAJOR.MINOR.MAINT, e.g. "2.0.1". The MAJOR version should match the major
* version of OpenTSDB the plugin is meant to work with.
* @return A version string used to log the loaded version
*/
public abstract String version();
/**
* Called by the TSD when a request for statistics collection has come in. The
* implementation may provide one or more statistics. If no statistics are
* available for the implementation, simply stub the method.
*
* <p><strong>Note:</strong> Must be thread-safe.
*
* @param collector The collector used for emitting statistics
*/
public abstract void collectStats(StatsCollector collector);
/**
* The (web) path this plugin should be available at. This value
* <strong>should</strong> start with a <code>/</code>. However, it
* <strong>must not</strong> contain the system's plugin base path or the
* plugin will fail to load.
*
* <p>Here are some examples where
* <code>path --(is available at)--> server path</code>
* <ul>
* <li><code>/myAwesomePlugin --> /plugin/myAwesomePlugin</code>
* <li><code>/myOtherPlugin/operation --> /plugin/myOtherPlugin/operation</code>
* </ul>
*
* @return a slash separated path
*/
public abstract String getPath();
/**
* Executes the plugin for the given query received on the path derived from
* {@link #getPath()}. This method will be called by multiple threads
* simultaneously and <b>must be</b> thread-safe.
*
* @param tsdb the owning TSDB instance.
* @param query the parsed query
* @throws IOException
*/
public abstract void execute(TSDB tsdb, HttpRpcPluginQuery query) throws IOException;
}
| OpenTSDB/opentsdb | src/tsd/HttpRpcPlugin.java |
2,721 | /* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2005-09 Ben Fry and Casey Reas
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package processing.app;
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;
import javax.swing.*;
/**
* Helper class for full-screen presentation mode.
*/
public class PresentMode {
static GraphicsDevice devices[];
/**
* Index of the default display device, probably the one that p5 was
* started from.
*/
static int defaultIndex;
/**
* Menu object for preferences window
*/
//JMenu preferencesMenu;
static JComboBox selector;
/**
* Index of the currently selected display to be used for present mode.
*/
static GraphicsDevice device;
static {
GraphicsEnvironment environment =
GraphicsEnvironment.getLocalGraphicsEnvironment();
devices = environment.getScreenDevices();
GraphicsDevice defaultDevice = environment.getDefaultScreenDevice();
Vector<String> names = new Vector<>();
for (int i = 0; i < devices.length; i++) {
String name = String.valueOf(i + 1);
if (devices[i] == defaultDevice) {
defaultIndex = i;
name += " (default)";
}
names.add(name);
}
selector = new JComboBox(names);
selector.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int index = selector.getSelectedIndex();
//device = devices[index];
PreferencesData.setInteger("run.present.display", index + 1);
}
});
}
static public JComboBox getSelector() {
int deviceIndex = PreferencesData.getInteger("run.present.display") - 1;
selector.setSelectedIndex(deviceIndex);
return selector;
}
/*
static public JFrame create() {
int deviceIndex = PrePreferences.getInteger("run.present.display") - 1;
if ((deviceIndex < 0) || (deviceIndex >= devices.length)) {
Base.showWarning("Display doesn't exist",
"Present Mode is set to use display " +
(deviceIndex+1) +
" but that doesn't seem to exist. \n" +
"This preference will be reset to " +
"use the default display.", null);
deviceIndex = defaultIndex;
}
//GraphicsDevice device = devices[
//JFrame frame = new JFrame(devices[deviceIndex]);
PresentFrame frame = new PresentFrame(devices[deviceIndex]);
}
public void show() {
setUndecorated(true);
setResizable(false);
device.setFullScreenWindow(this);
}
public Window getWindow() {
return device.getFullScreenWindow(); // isn't this just me?
}
public void dispose() {
Window window = device.getFullScreenWindow();
if (window != null) {
window.dispose();
}
device.setFullScreenWindow(null);
}
*/
}
| roboard/86Duino | app/src/processing/app/PresentMode.java |
2,722 | /*
* Copyright The OpenZipkin Authors
* SPDX-License-Identifier: Apache-2.0
*/
package zipkin2.internal;
import static zipkin2.internal.HexCodec.HEX_DIGITS;
/**
* Writes are unsafe as they do no bounds checks. This means you should take care to allocate or
* wrap an array at least as big as you need prior to writing. As it is possible to calculate size
* prior to writing, overrunning a buffer is a programming error.
*/
public final class WriteBuffer {
public interface Writer<T> {
int sizeInBytes(T value);
void write(T value, WriteBuffer buffer);
}
public static WriteBuffer wrap(byte[] bytes) {
return wrap(bytes, 0);
}
public static WriteBuffer wrap(byte[] bytes, int pos) {
return new WriteBuffer(bytes, pos);
}
final byte[] buf;
int pos;
WriteBuffer(byte[] buf, int pos) {
this.buf = buf;
this.pos = pos;
}
public void writeByte(int v) {
buf[pos++] = (byte) (v & 0xff);
}
public void write(byte[] v) {
System.arraycopy(v, 0, buf, pos, v.length);
pos += v.length;
}
void writeBackwards(long v) {
int lastPos = pos + asciiSizeInBytes(v); // We write backwards from right to left.
pos = lastPos;
while (v != 0) {
int digit = (int) (v % 10);
buf[--lastPos] = (byte) HEX_DIGITS[digit];
v /= 10;
}
}
/** Inspired by {@code okio.Buffer.writeLong} */
public void writeLongHex(long v) {
int pos = this.pos;
writeHexByte(buf, pos + 0, (byte) ((v >>> 56L) & 0xff));
writeHexByte(buf, pos + 2, (byte) ((v >>> 48L) & 0xff));
writeHexByte(buf, pos + 4, (byte) ((v >>> 40L) & 0xff));
writeHexByte(buf, pos + 6, (byte) ((v >>> 32L) & 0xff));
writeHexByte(buf, pos + 8, (byte) ((v >>> 24L) & 0xff));
writeHexByte(buf, pos + 10, (byte) ((v >>> 16L) & 0xff));
writeHexByte(buf, pos + 12, (byte) ((v >>> 8L) & 0xff));
writeHexByte(buf, pos + 14, (byte) (v & 0xff));
this.pos = pos + 16;
}
static void writeHexByte(byte[] data, int pos, byte b) {
data[pos + 0] = (byte) HEX_DIGITS[(b >> 4) & 0xf];
data[pos + 1] = (byte) HEX_DIGITS[b & 0xf];
}
int pos() {
return pos;
}
public void writeAscii(String v) {
for (int i = 0, length = v.length(); i < length; i++) {
writeByte(v.charAt(i) & 0xff);
}
}
/**
* This transcodes a UTF-16 Java String to UTF-8 bytes.
*
* <p>This looks most similar to {@code io.netty.buffer.ByteBufUtil.writeUtf8(AbstractByteBuf,
* int, CharSequence, int)} v4.1, modified including features to address ASCII runs of text.
*/
public void writeUtf8(CharSequence string) {
for (int i = 0, len = string.length(); i < len; i++) {
char ch = string.charAt(i);
if (ch < 0x80) { // 7-bit ASCII character
writeByte(ch);
// This could be an ASCII run, or possibly entirely ASCII
while (i < len - 1) {
ch = string.charAt(i + 1);
if (ch >= 0x80) break;
i++;
writeByte(ch); // another 7-bit ASCII character
}
} else if (ch < 0x800) { // 11-bit character
writeByte(0xc0 | (ch >> 6));
writeByte(0x80 | (ch & 0x3f));
} else if (ch < 0xd800 || ch > 0xdfff) { // 16-bit character
writeByte(0xe0 | (ch >> 12));
writeByte(0x80 | ((ch >> 6) & 0x3f));
writeByte(0x80 | (ch & 0x3f));
} else { // Possibly a 21-bit character
if (!Character.isHighSurrogate(ch)) { // Malformed or not UTF-8
writeByte('?');
continue;
}
if (i == len - 1) { // Truncated or not UTF-8
writeByte('?');
break;
}
char low = string.charAt(++i);
if (!Character.isLowSurrogate(low)) { // Malformed or not UTF-8
writeByte('?');
writeByte(Character.isHighSurrogate(low) ? '?' : low);
continue;
}
// Write the 21-bit character using 4 bytes
// See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G2630
int codePoint = Character.toCodePoint(ch, low);
writeByte(0xf0 | (codePoint >> 18));
writeByte(0x80 | ((codePoint >> 12) & 0x3f));
writeByte(0x80 | ((codePoint >> 6) & 0x3f));
writeByte(0x80 | (codePoint & 0x3f));
}
}
}
// Adapted from okio.Buffer.writeDecimalLong
public void writeAscii(long v) {
if (v == 0) {
writeByte('0');
return;
}
if (v == Long.MIN_VALUE) {
writeAscii("-9223372036854775808");
return;
}
if (v < 0) {
writeByte('-');
v = -v; // needs to be positive so we can use this for an array index
}
writeBackwards(v);
}
// com.squareup.wire.ProtoWriter.writeVarint v2.3.0
void writeVarint(int v) {
while ((v & ~0x7f) != 0) {
writeByte((byte) ((v & 0x7f) | 0x80));
v >>>= 7;
}
writeByte((byte) v);
}
// com.squareup.wire.ProtoWriter.writeVarint v2.3.0
void writeVarint(long v) {
while ((v & ~0x7fL) != 0) {
writeByte((byte) ((v & 0x7f) | 0x80));
v >>>= 7;
}
writeByte((byte) v);
}
void writeLongLe(long v) {
writeByte((byte) (v & 0xff));
writeByte((byte) ((v >> 8) & 0xff));
writeByte((byte) ((v >> 16) & 0xff));
writeByte((byte) ((v >> 24) & 0xff));
writeByte((byte) ((v >> 32) & 0xff));
writeByte((byte) ((v >> 40) & 0xff));
writeByte((byte) ((v >> 48) & 0xff));
writeByte((byte) ((v >> 56) & 0xff));
}
/**
* This returns the bytes needed to transcode a UTF-16 Java String to UTF-8 bytes.
*
* <p>Originally based on
* http://stackoverflow.com/questions/8511490/calculating-length-in-utf-8-of-java-string-without-actually-encoding-it
*
* <p>Later, ASCII run and malformed surrogate logic borrowed from okio.Utf8
*/
// TODO: benchmark vs https://github.com/protocolbuffers/protobuf/blob/master/java/core/src/main/java/com/google/protobuf/Utf8.java#L240
// there seem to be less branches for for strings without surrogates
public static int utf8SizeInBytes(CharSequence string) {
int sizeInBytes = 0;
for (int i = 0, len = string.length(); i < len; i++) {
char ch = string.charAt(i);
if (ch < 0x80) {
sizeInBytes++; // 7-bit ASCII character
// This could be an ASCII run, or possibly entirely ASCII
while (i < len - 1) {
ch = string.charAt(i + 1);
if (ch >= 0x80) break;
i++;
sizeInBytes++; // another 7-bit ASCII character
}
} else if (ch < 0x800) {
sizeInBytes += 2; // 11-bit character
} else if (ch < 0xd800 || ch > 0xdfff) {
sizeInBytes += 3; // 16-bit character
} else {
int low = i + 1 < len ? string.charAt(i + 1) : 0;
if (ch > 0xdbff || low < 0xdc00 || low > 0xdfff) {
sizeInBytes++; // A malformed surrogate, which yields '?'.
} else {
// A 21-bit character
sizeInBytes += 4;
i++;
}
}
}
return sizeInBytes;
}
/**
* Binary search for character width which favors matching lower numbers.
*
* <p>Adapted from okio.Buffer
*/
public static int asciiSizeInBytes(long v) {
if (v == 0) return 1;
if (v == Long.MIN_VALUE) return 20;
boolean negative = false;
if (v < 0) {
v = -v; // making this positive allows us to compare using less-than
negative = true;
}
int width =
v < 100000000L
? v < 10000L
? v < 100L ? v < 10L ? 1 : 2 : v < 1000L ? 3 : 4
: v < 1000000L ? v < 100000L ? 5 : 6 : v < 10000000L ? 7 : 8
: v < 1000000000000L
? v < 10000000000L ? v < 1000000000L ? 9 : 10 : v < 100000000000L ? 11 : 12
: v < 1000000000000000L
? v < 10000000000000L ? 13 : v < 100000000000000L ? 14 : 15
: v < 100000000000000000L
? v < 10000000000000000L ? 16 : 17
: v < 1000000000000000000L ? 18 : 19;
return negative ? width + 1 : width; // conditionally add room for negative sign
}
/**
* A base 128 varint encodes 7 bits at a time, this checks how many bytes are needed to represent
* the value.
*
* <p>See https://developers.google.com/protocol-buffers/docs/encoding#varints
*
* <p>This logic is the same as {@code com.squareup.wire.ProtoWriter.varint32Size} v2.3.0 which
* benchmarked faster than loop variants of the frequently copy/pasted VarInt.varIntSize
*/
public static int varintSizeInBytes(int value) {
if ((value & (0xffffffff << 7)) == 0) return 1;
if ((value & (0xffffffff << 14)) == 0) return 2;
if ((value & (0xffffffff << 21)) == 0) return 3;
if ((value & (0xffffffff << 28)) == 0) return 4;
return 5;
}
/** Like {@link #varintSizeInBytes(int)}, except for uint64. */
// TODO: benchmark vs https://github.com/protocolbuffers/protobuf/blob/master/java/core/src/main/java/com/google/protobuf/CodedOutputStream.java#L770
// Since trace IDs are random, I guess they cover the entire spectrum of varint sizes and probably would especially benefit from this.
public static int varintSizeInBytes(long v) {
if ((v & (0xffffffffffffffffL << 7)) == 0) return 1;
if ((v & (0xffffffffffffffffL << 14)) == 0) return 2;
if ((v & (0xffffffffffffffffL << 21)) == 0) return 3;
if ((v & (0xffffffffffffffffL << 28)) == 0) return 4;
if ((v & (0xffffffffffffffffL << 35)) == 0) return 5;
if ((v & (0xffffffffffffffffL << 42)) == 0) return 6;
if ((v & (0xffffffffffffffffL << 49)) == 0) return 7;
if ((v & (0xffffffffffffffffL << 56)) == 0) return 8;
if ((v & (0xffffffffffffffffL << 63)) == 0) return 9;
return 10;
}
}
| openzipkin/zipkin | zipkin/src/main/java/zipkin2/internal/WriteBuffer.java |
2,723 | package com.winterbe.java8.samples.time;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.ChronoUnit;
import java.util.Locale;
/**
* @author Benjamin Winterberg
*/
public class LocalDate1 {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalDate tomorrow = today.plus(1, ChronoUnit.DAYS);
LocalDate yesterday = tomorrow.minusDays(2);
System.out.println(today);
System.out.println(tomorrow);
System.out.println(yesterday);
LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4);
DayOfWeek dayOfWeek = independenceDay.getDayOfWeek();
System.out.println(dayOfWeek); // FRIDAY
DateTimeFormatter germanFormatter =
DateTimeFormatter
.ofLocalizedDate(FormatStyle.MEDIUM)
.withLocale(Locale.GERMAN);
LocalDate xmas = LocalDate.parse("24.12.2014", germanFormatter);
System.out.println(xmas); // 2014-12-24
}
} | winterbe/java8-tutorial | src/com/winterbe/java8/samples/time/LocalDate1.java |
2,724 | /*
* Copyright (c) 2013, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software;Designed and Developed mainly by many Chinese
* opensource volunteers. you can redistribute it and/or modify it under the
* terms of the GNU General Public License version 2 only, as published by the
* Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Any questions about this component can be directed to it's project Web address
* https://code.google.com/p/opencloudb/.
*
*/
package io.mycat.config.model;
import java.util.Set;
/**
* @author mycat
*/
public class UserConfig {
private String name;
private String password; //明文
private String encryptPassword; //密文
private int benchmark = 0; // 负载限制, 默认0表示不限制
private UserPrivilegesConfig privilegesConfig; //SQL表级的增删改查权限控制
/**
* 是否无密码登陆的默认账户
*/
private boolean defaultAccount = false;
private boolean readOnly = false;
public boolean isReadOnly() {
return readOnly;
}
public void setReadOnly(boolean readOnly) {
this.readOnly = readOnly;
}
private Set<String> schemas;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getBenchmark() {
return benchmark;
}
public void setBenchmark(int benchmark) {
this.benchmark = benchmark;
}
public Set<String> getSchemas() {
return schemas;
}
public String getEncryptPassword() {
return this.encryptPassword;
}
public void setEncryptPassword(String encryptPassword) {
this.encryptPassword = encryptPassword;
}
public void setSchemas(Set<String> schemas) {
this.schemas = schemas;
}
public UserPrivilegesConfig getPrivilegesConfig() {
return privilegesConfig;
}
public void setPrivilegesConfig(UserPrivilegesConfig privilegesConfig) {
this.privilegesConfig = privilegesConfig;
}
public boolean isDefaultAccount() {
return defaultAccount;
}
public void setDefaultAccount(boolean defaultAccount) {
this.defaultAccount = defaultAccount;
}
@Override
public String toString() {
return "UserConfig [name=" + name + ", password=" + password + ", encryptPassword=" + encryptPassword
+ ", benchmark=" + benchmark + ", privilegesConfig=" + privilegesConfig + ", defaultAccount="
+ defaultAccount + ", readOnly=" + readOnly + ", schemas=" + schemas + "]";
}
} | jim0409/Mycat-Server | src/main/java/io/mycat/config/model/UserConfig.java |
2,725 | /* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2012-16 The Processing Foundation
Copyright (c) 2004-12 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package processing.app;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Non-GUI handling of System.out and System.err redirection.
* <p />
* Be careful when debugging this class, because if it's throwing exceptions,
* don't take over System.err, and debug while watching just System.out
* or just call println() or whatever directly to systemOut or systemErr.
* <p />
* Also note that encodings will not work properly when run from Eclipse. This
* means that if you use non-ASCII characters in a println() or some such,
* the characters won't print properly in the Processing and/or Eclipse console.
* It seems that Eclipse's console-grabbing and that of Processing don't
* get along with one another. Use 'ant run' to work on encoding-related issues.
*/
public class Console {
// Single static instance shared because there's only one real System.out.
// Within the input handlers, the currentConsole variable will be used to
// echo things to the correct location.
/** The original System.out */
static PrintStream systemOut;
/** The original System.err */
static PrintStream systemErr;
/** Our replacement System.out */
static PrintStream consoleOut;
/** Our replacement System.err */
static PrintStream consoleErr;
/** All stdout also written to a file */
static OutputStream stdoutFile;
/** All stderr also written to a file */
static OutputStream stderrFile;
/** stdout listener for the currently active Editor */
static OutputStream editorOut;
/** stderr listener for the currently active Editor */
static OutputStream editorErr;
static public void startup() {
if (systemOut != null) {
// TODO fix this dreadful style choice in how the Console is initialized
// (This is not good code.. startup() should gracefully deal with this.
// It's just a low priority relative to the likelihood of trouble.)
new Exception("startup() called more than once").printStackTrace(systemErr);
return;
}
systemOut = System.out;
systemErr = System.err;
// placing everything inside a try block because this can be a dangerous
// time for the lights to blink out and crash for and obscure reason.
try {
SimpleDateFormat formatter = new SimpleDateFormat("yyMMdd_HHmmss");
// Moving away from a random string in 0256 (and adding hms) because
// the random digits looked like times anyway, causing confusion.
//String randy = String.format("%04d", (int) (1000 * Math.random()));
//final String stamp = formatter.format(new Date()) + "_" + randy;
final String stamp = formatter.format(new Date());
File consoleDir = Base.getSettingsFile("console");
if (consoleDir.exists()) {
// clear old debug files
File[] stdFiles = consoleDir.listFiles(new FileFilter() {
final String todayPrefix = stamp.substring(0, 4);
public boolean accept(File file) {
if (!file.isDirectory()) {
String name = file.getName();
if (name.endsWith(".err") || name.endsWith(".out")) {
// don't delete any of today's debug messages
return !name.startsWith(todayPrefix);
}
}
return false;
}
});
// Remove any files that aren't from today
for (File file : stdFiles) {
file.delete();
}
} else {
consoleDir.mkdirs();
consoleDir.setWritable(true, false);
}
File outFile = new File(consoleDir, stamp + ".out");
outFile.setWritable(true, false);
stdoutFile = new FileOutputStream(outFile);
File errFile = new File(consoleDir, stamp + ".err");
errFile.setWritable(true, false);
stderrFile = new FileOutputStream(errFile);
consoleOut = new PrintStream(new ConsoleStream(false));
consoleErr = new PrintStream(new ConsoleStream(true));
System.setOut(consoleOut);
System.setErr(consoleErr);
} catch (Exception e) {
stdoutFile = null;
stderrFile = null;
consoleOut = null;
consoleErr = null;
System.setOut(systemOut);
System.setErr(systemErr);
e.printStackTrace();
}
}
static public void setEditor(OutputStream out, OutputStream err) {
editorOut = out;
editorErr = err;
}
static public void systemOut(String what) {
systemOut.println(what);
}
static public void systemErr(String what) {
systemErr.println(what);
}
/**
* Close the streams so that the temporary files can be deleted.
* <p/>
* File.deleteOnExit() cannot be used because the stdout and stderr
* files are inside a folder, and have to be deleted before the
* folder itself is deleted, which can't be guaranteed when using
* the deleteOnExit() method.
*/
static public void shutdown() {
// replace original streams to remove references to console's streams
System.setOut(systemOut);
System.setErr(systemErr);
cleanup(consoleOut);
cleanup(consoleErr);
// also have to close the original FileOutputStream
// otherwise it won't be shut down completely
cleanup(stdoutFile);
cleanup(stderrFile);
}
static private void cleanup(OutputStream output) {
try {
if (output != null) {
output.flush();
output.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static class ConsoleStream extends OutputStream {
boolean err; // whether stderr or stdout
byte single[] = new byte[1];
public ConsoleStream(boolean err) {
this.err = err;
}
public void close() { }
public void flush() { }
public void write(byte b[]) { // appears never to be used
write(b, 0, b.length);
}
public void write(byte b[], int offset, int length) {
// First write to the original stdout/stderr
if (err) {
systemErr.write(b, offset, length);
} else {
systemOut.write(b, offset, length);
}
// Write to the files that are storing this information
writeFile(b, offset, length);
// Write to the console of the current Editor, if any
try {
if (err) {
if (editorErr != null) {
editorErr.write(b, offset, length);
}
} else {
if (editorOut != null) {
editorOut.write(b, offset, length);
}
}
} catch (IOException e) {
// Avoid this function being called in a recursive, infinite loop
e.printStackTrace(systemErr);
}
}
public void writeFile(byte b[], int offset, int length) {
final OutputStream echo = err ? stderrFile : stdoutFile;
if (echo != null) {
try {
echo.write(b, offset, length);
echo.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void write(int b) {
single[0] = (byte) b;
write(single, 0, 1);
}
}
} | processing/processing | app/src/processing/app/Console.java |
2,726 | /*
* Copyright (C) 2007 The Guava Authors
*
* 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 com.google.common.io;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Charsets;
import com.google.common.base.MoreObjects;
import com.google.common.collect.Lists;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.List;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Provides utility methods for working with resources in the classpath. Note that even though these
* methods use {@link URL} parameters, they are usually not appropriate for HTTP or other
* non-classpath resources.
*
* @author Chris Nokleberg
* @author Ben Yu
* @author Colin Decker
* @since 1.0
*/
@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class Resources {
private Resources() {}
/**
* Returns a {@link ByteSource} that reads from the given URL.
*
* @since 14.0
*/
public static ByteSource asByteSource(URL url) {
return new UrlByteSource(url);
}
/** A byte source that reads from a URL using {@link URL#openStream()}. */
private static final class UrlByteSource extends ByteSource {
private final URL url;
private UrlByteSource(URL url) {
this.url = checkNotNull(url);
}
@Override
public InputStream openStream() throws IOException {
return url.openStream();
}
@Override
public String toString() {
return "Resources.asByteSource(" + url + ")";
}
}
/**
* Returns a {@link CharSource} that reads from the given URL using the given character set.
*
* @since 14.0
*/
public static CharSource asCharSource(URL url, Charset charset) {
return asByteSource(url).asCharSource(charset);
}
/**
* Reads all bytes from a URL into a byte array.
*
* @param url the URL to read from
* @return a byte array containing all the bytes from the URL
* @throws IOException if an I/O error occurs
*/
public static byte[] toByteArray(URL url) throws IOException {
return asByteSource(url).read();
}
/**
* Reads all characters from a URL into a {@link String}, using the given character set.
*
* @param url the URL to read from
* @param charset the charset used to decode the input stream; see {@link Charsets} for helpful
* predefined constants
* @return a string containing all the characters from the URL
* @throws IOException if an I/O error occurs.
*/
public static String toString(URL url, Charset charset) throws IOException {
return asCharSource(url, charset).read();
}
/**
* Streams lines from a URL, stopping when our callback returns false, or we have read all of the
* lines.
*
* @param url the URL to read from
* @param charset the charset used to decode the input stream; see {@link Charsets} for helpful
* predefined constants
* @param callback the LineProcessor to use to handle the lines
* @return the output of processing the lines
* @throws IOException if an I/O error occurs
*/
@CanIgnoreReturnValue // some processors won't return a useful result
@ParametricNullness
public static <T extends @Nullable Object> T readLines(
URL url, Charset charset, LineProcessor<T> callback) throws IOException {
return asCharSource(url, charset).readLines(callback);
}
/**
* Reads all of the lines from a URL. The lines do not include line-termination characters, but do
* include other leading and trailing whitespace.
*
* <p>This method returns a mutable {@code List}. For an {@code ImmutableList}, use {@code
* Resources.asCharSource(url, charset).readLines()}.
*
* @param url the URL to read from
* @param charset the charset used to decode the input stream; see {@link Charsets} for helpful
* predefined constants
* @return a mutable {@link List} containing all the lines
* @throws IOException if an I/O error occurs
*/
public static List<String> readLines(URL url, Charset charset) throws IOException {
// don't use asCharSource(url, charset).readLines() because that returns
// an immutable list, which would change the behavior of this method
return readLines(
url,
charset,
new LineProcessor<List<String>>() {
final List<String> result = Lists.newArrayList();
@Override
public boolean processLine(String line) {
result.add(line);
return true;
}
@Override
public List<String> getResult() {
return result;
}
});
}
/**
* Copies all bytes from a URL to an output stream.
*
* @param from the URL to read from
* @param to the output stream
* @throws IOException if an I/O error occurs
*/
public static void copy(URL from, OutputStream to) throws IOException {
asByteSource(from).copyTo(to);
}
/**
* Returns a {@code URL} pointing to {@code resourceName} if the resource is found using the
* {@linkplain Thread#getContextClassLoader() context class loader}. In simple environments, the
* context class loader will find resources from the class path. In environments where different
* threads can have different class loaders, for example app servers, the context class loader
* will typically have been set to an appropriate loader for the current thread.
*
* <p>In the unusual case where the context class loader is null, the class loader that loaded
* this class ({@code Resources}) will be used instead.
*
* @throws IllegalArgumentException if the resource is not found
*/
@CanIgnoreReturnValue // being used to check if a resource exists
// TODO(cgdecker): maybe add a better way to check if a resource exists
// e.g. Optional<URL> tryGetResource or boolean resourceExists
public static URL getResource(String resourceName) {
ClassLoader loader =
MoreObjects.firstNonNull(
Thread.currentThread().getContextClassLoader(), Resources.class.getClassLoader());
URL url = loader.getResource(resourceName);
checkArgument(url != null, "resource %s not found.", resourceName);
return url;
}
/**
* Given a {@code resourceName} that is relative to {@code contextClass}, returns a {@code URL}
* pointing to the named resource.
*
* @throws IllegalArgumentException if the resource is not found
*/
@CanIgnoreReturnValue // being used to check if a resource exists
public static URL getResource(Class<?> contextClass, String resourceName) {
URL url = contextClass.getResource(resourceName);
checkArgument(
url != null, "resource %s relative to %s not found.", resourceName, contextClass.getName());
return url;
}
}
| google/guava | guava/src/com/google/common/io/Resources.java |
2,727 | package com.winterbe.java8.samples.misc;
import java.util.HashMap;
import java.util.Map;
/**
* @author Benjamin Winterberg
*/
public class Maps1 {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
for (int i = 0; i < 10; i++) {
map.putIfAbsent(i, "val" + i);
}
map.forEach((id, val) -> System.out.println(val));
map.computeIfPresent(3, (num, val) -> val + num);
System.out.println(map.get(3)); // val33
map.computeIfPresent(9, (num, val) -> null);
System.out.println(map.containsKey(9)); // false
map.computeIfAbsent(23, num -> "val" + num);
System.out.println(map.containsKey(23)); // true
map.computeIfAbsent(3, num -> "bam");
System.out.println(map.get(3)); // val33
System.out.println(map.getOrDefault(42, "not found")); // not found
map.remove(3, "val3");
System.out.println(map.get(3)); // val33
map.remove(3, "val33");
System.out.println(map.get(3)); // null
map.merge(9, "val9", (value, newValue) -> value.concat(newValue));
System.out.println(map.get(9)); // val9
map.merge(9, "concat", (value, newValue) -> value.concat(newValue));
System.out.println(map.get(9)); // val9concat
}
} | winterbe/java8-tutorial | src/com/winterbe/java8/samples/misc/Maps1.java |
2,728 | package com.winterbe.java8.samples.lambda;
/**
* @author Benjamin Winterberg
*/
public class Person {
public String firstName;
public String lastName;
public Person() {}
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
} | winterbe/java8-tutorial | src/com/winterbe/java8/samples/lambda/Person.java |
2,729 | package com.winterbe.java8.samples.stream;
import java.util.OptionalInt;
import java.util.stream.IntStream;
/**
* @author Benjamin Winterberg
*/
public class Streams4 {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i % 2 == 1) {
System.out.println(i);
}
}
IntStream.range(0, 10)
.forEach(i -> {
if (i % 2 == 1) System.out.println(i);
});
IntStream.range(0, 10)
.filter(i -> i % 2 == 1)
.forEach(System.out::println);
OptionalInt reduced1 =
IntStream.range(0, 10)
.reduce((a, b) -> a + b);
System.out.println(reduced1.getAsInt());
int reduced2 =
IntStream.range(0, 10)
.reduce(7, (a, b) -> a + b);
System.out.println(reduced2);
}
}
| winterbe/java8-tutorial | src/com/winterbe/java8/samples/stream/Streams4.java |
2,730 | package com.winterbe.java8.samples.concurrent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* @author Benjamin Winterberg
*/
public class Executors1 {
public static void main(String[] args) {
test1(3);
// test1(7);
}
private static void test1(long seconds) {
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
try {
TimeUnit.SECONDS.sleep(seconds);
String name = Thread.currentThread().getName();
System.out.println("task finished: " + name);
}
catch (InterruptedException e) {
System.err.println("task interrupted");
}
});
stop(executor);
}
static void stop(ExecutorService executor) {
try {
System.out.println("attempt to shutdown executor");
executor.shutdown();
executor.awaitTermination(5, TimeUnit.SECONDS);
}
catch (InterruptedException e) {
System.err.println("termination interrupted");
}
finally {
if (!executor.isTerminated()) {
System.err.println("killing non-finished tasks");
}
executor.shutdownNow();
System.out.println("shutdown finished");
}
}
}
| winterbe/java8-tutorial | src/com/winterbe/java8/samples/concurrent/Executors1.java |
2,731 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.uimanager;
import androidx.annotation.Nullable;
import com.facebook.yoga.YogaAlign;
import com.facebook.yoga.YogaBaselineFunction;
import com.facebook.yoga.YogaDirection;
import com.facebook.yoga.YogaDisplay;
import com.facebook.yoga.YogaFlexDirection;
import com.facebook.yoga.YogaJustify;
import com.facebook.yoga.YogaMeasureFunction;
import com.facebook.yoga.YogaNode;
import com.facebook.yoga.YogaOverflow;
import com.facebook.yoga.YogaPositionType;
import com.facebook.yoga.YogaValue;
import com.facebook.yoga.YogaWrap;
/**
* Base node class for representing virtual tree of React nodes. Shadow nodes are used primarily for
* layouting therefore it extends {@link YogaNode} to allow that. They also help with handling
* Common base subclass of {@link YogaNode} for all layout nodes for react-based view. It extends
* {@link YogaNode} by adding additional capabilities.
*
* <p>Instances of this class receive property updates from JS via @{link UIManagerModule}.
* Subclasses may use {@link #updateShadowNode} to persist some of the updated fields in the node
* instance that corresponds to a particular view type.
*
* <p>Subclasses of {@link ReactShadowNode} should be created only from {@link ViewManager} that
* corresponds to a certain type of native view. They will be updated and accessed only from JS
* thread. Subclasses of {@link ViewManager} may choose to use base class {@link ReactShadowNode} or
* custom subclass of it if necessary.
*
* <p>The primary use-case for {@link ReactShadowNode} nodes is to calculate layouting. Although
* this might be extended. For some examples please refer to ARTGroupYogaNode or ReactTextYogaNode.
*
* <p>This class allows for the native view hierarchy to not be an exact copy of the hierarchy
* received from JS by keeping track of both JS children (e.g. {@link #getChildCount()} and
* separately native children (e.g. {@link #getNativeChildCount()}). See {@link
* NativeViewHierarchyOptimizer} for more information.
*/
public interface ReactShadowNode<T extends ReactShadowNode> {
/**
* Nodes that return {@code true} will be treated as "virtual" nodes. That is, nodes that are not
* mapped into native views or Yoga nodes (e.g. nested text node). By default this method returns
* {@code false}.
*/
boolean isVirtual();
/**
* Nodes that return {@code true} will be treated as a root view for the virtual nodes tree. It
* means that all of its descendants will be "virtual" nodes. Good example is {@code InputText}
* view that may have children {@code Text} nodes but this whole hierarchy will be mapped to a
* single android {@link EditText} view.
*/
boolean isVirtualAnchor();
/**
* Nodes that return {@code true} will not manage (and and remove) child Yoga nodes. For example
* {@link ReactTextInputShadowNode} or {@link ReactTextShadowNode} have child nodes, which do not
* want Yoga to lay out, so in the eyes of Yoga it is a leaf node. Override this method in
* subclass to enforce this requirement.
*/
boolean isYogaLeafNode();
/**
* When constructing the native tree, nodes that return {@code true} will be treated as leaves.
* Instead of adding this view's native children as subviews of it, they will be added as subviews
* of an ancestor. In other words, this view wants to support native children but it cannot host
* them itself (e.g. it isn't a ViewGroup).
*/
boolean hoistNativeChildren();
String getViewClass();
boolean hasUpdates();
void markUpdateSeen();
void markUpdated();
boolean hasUnseenUpdates();
void dirty();
boolean isDirty();
void addChildAt(T child, int i);
T removeChildAt(int i);
int getChildCount();
T getChildAt(int i);
int indexOf(T child);
void removeAndDisposeAllChildren();
/**
* This method will be called by {@link UIManagerModule} once per batch, before calculating
* layout. Will be only called for nodes that are marked as updated with {@link #markUpdated()} or
* require layouting (marked with {@link #dirty()}).
*/
void onBeforeLayout(NativeViewHierarchyOptimizer nativeViewHierarchyOptimizer);
void updateProperties(ReactStylesDiffMap props);
void onAfterUpdateTransaction();
/**
* Called after layout step at the end of the UI batch from {@link UIManagerModule}. May be used
* to enqueue additional ui operations for the native view. Will only be called on nodes marked as
* updated either with {@link #dirty()} or {@link #markUpdated()}.
*
* @param uiViewOperationQueue interface for enqueueing UI operations
*/
void onCollectExtraUpdates(UIViewOperationQueue uiViewOperationQueue);
/* package */ boolean dispatchUpdatesWillChangeLayout(float absoluteX, float absoluteY);
/* package */ void dispatchUpdates(
float absoluteX,
float absoluteY,
UIViewOperationQueue uiViewOperationQueue,
NativeViewHierarchyOptimizer nativeViewHierarchyOptimizer);
int getReactTag();
void setReactTag(int reactTag);
int getRootTag();
void setRootTag(int rootTag);
void setViewClassName(String viewClassName);
@Nullable
T getParent();
// Returns the node that is responsible for laying out this node.
@Nullable
T getLayoutParent();
void setLayoutParent(@Nullable T layoutParent);
/**
* Get the {@link ThemedReactContext} associated with this {@link ReactShadowNode}. This will
* never change during the lifetime of a {@link ReactShadowNode} instance, but different instances
* can have different contexts; don't cache any calculations based on theme values globally.
*/
ThemedReactContext getThemedContext();
void setThemedContext(ThemedReactContext themedContext);
boolean shouldNotifyOnLayout();
void calculateLayout();
void calculateLayout(float width, float height);
boolean hasNewLayout();
void markLayoutSeen();
/**
* Adds a child that the native view hierarchy will have at this index in the native view
* corresponding to this node.
*/
void addNativeChildAt(T child, int nativeIndex);
T removeNativeChildAt(int i);
void removeAllNativeChildren();
int getNativeChildCount();
int indexOfNativeChild(T nativeChild);
@Nullable
T getNativeParent();
/**
* Sets whether this node only contributes to the layout of its children without doing any drawing
* or functionality itself.
*/
void setIsLayoutOnly(boolean isLayoutOnly);
boolean isLayoutOnly();
NativeKind getNativeKind();
int getTotalNativeChildren();
boolean isDescendantOf(T ancestorNode);
/**
* @return a {@link String} representation of the Yoga hierarchy of this {@link ReactShadowNode}
*/
String getHierarchyInfo();
/*
* In some cases we need a way to specify some environmental data to shadow node
* to improve layout (or do something similar), so {@code localData} serves these needs.
* For example, any stateful embedded native views may benefit from this.
* Have in mind that this data is not supposed to interfere with the state of
* the shadow node.
* Please respect one-directional data flow of React.
* Use {@link UIManagerModule#setViewLocalData} to set this property
* (to provide local/environmental data for a shadow node) from the main thread.
*/
void setLocalData(Object data);
/**
* Returns the offset within the native children owned by all layout-only nodes in the subtree
* rooted at this node for the given child. Put another way, this returns the number of native
* nodes (nodes not optimized out of the native tree) that are a) to the left (visited before by a
* DFS) of the given child in the subtree rooted at this node and b) do not have a native parent
* in this subtree (which means that the given child will be a sibling of theirs in the final
* native hierarchy since they'll get attached to the same native parent).
*
* <p>Basically, a view might have children that have been optimized away by {@link
* NativeViewHierarchyOptimizer}. Since those children will then add their native children to this
* view, we now have ranges of native children that correspond to single unoptimized children. The
* purpose of this method is to return the index within the native children that corresponds to
* the **start** of the native children that belong to the given child. Also, note that all of the
* children of a view might be optimized away, so this could return the same value for multiple
* different children.
*
* <p>Example. Native children are represented by (N) where N is the no-opt child they came from.
* If no children are optimized away it'd look like this: (0) (1) (2) (3) ... (n)
*
* <p>In case some children are optimized away, it might look like this: (0) (1) (1) (1) (3) (3)
* (4)
*
* <p>In that case: getNativeOffsetForChild(Node 0) => 0 getNativeOffsetForChild(Node 1) => 1
* getNativeOffsetForChild(Node 2) => 4 getNativeOffsetForChild(Node 3) => 4
*
* <p>getNativeOffsetForChild(Node 4) => 6
*/
int getNativeOffsetForChild(T child);
float getLayoutX();
float getLayoutY();
float getLayoutWidth();
float getLayoutHeight();
/**
* @return the x position of the corresponding view on the screen, rounded to pixels
*/
int getScreenX();
/**
* @return the y position of the corresponding view on the screen, rounded to pixels
*/
int getScreenY();
/**
* @return width corrected for rounding to pixels.
*/
int getScreenWidth();
/**
* @return height corrected for rounding to pixels.
*/
int getScreenHeight();
YogaDirection getLayoutDirection();
void setLayoutDirection(YogaDirection direction);
YogaValue getStyleWidth();
void setStyleWidth(float widthPx);
void setStyleWidthPercent(float percent);
void setStyleWidthAuto();
void setStyleMinWidth(float widthPx);
void setStyleMinWidthPercent(float percent);
void setStyleMaxWidth(float widthPx);
void setStyleMaxWidthPercent(float percent);
YogaValue getStyleHeight();
float getFlex();
void setStyleHeight(float heightPx);
void setStyleHeightPercent(float percent);
void setStyleHeightAuto();
void setStyleMinHeight(float widthPx);
void setStyleMinHeightPercent(float percent);
void setStyleMaxHeight(float widthPx);
void setStyleMaxHeightPercent(float percent);
void setFlex(float flex);
void setFlexGrow(float flexGrow);
void setRowGap(float rowGap);
void setRowGapPercent(float percent);
void setColumnGap(float columnGap);
void setColumnGapPercent(float percent);
void setGap(float gap);
void setGapPercent(float percent);
void setFlexShrink(float flexShrink);
void setFlexBasis(float flexBasis);
void setFlexBasisAuto();
void setFlexBasisPercent(float percent);
void setStyleAspectRatio(float aspectRatio);
void setFlexDirection(YogaFlexDirection flexDirection);
void setFlexWrap(YogaWrap wrap);
void setAlignSelf(YogaAlign alignSelf);
void setAlignItems(YogaAlign alignItems);
void setAlignContent(YogaAlign alignContent);
void setJustifyContent(YogaJustify justifyContent);
void setOverflow(YogaOverflow overflow);
void setDisplay(YogaDisplay display);
void setMargin(int spacingType, float margin);
void setMarginPercent(int spacingType, float percent);
void setMarginAuto(int spacingType);
float getPadding(int spacingType);
YogaValue getStylePadding(int spacingType);
void setDefaultPadding(int spacingType, float padding);
void setPadding(int spacingType, float padding);
void setPaddingPercent(int spacingType, float percent);
void setBorder(int spacingType, float borderWidth);
void setPosition(int spacingType, float position);
void setPositionPercent(int spacingType, float percent);
void setPositionType(YogaPositionType positionType);
void setShouldNotifyOnLayout(boolean shouldNotifyOnLayout);
void setBaselineFunction(YogaBaselineFunction baselineFunction);
void setMeasureFunction(YogaMeasureFunction measureFunction);
boolean isMeasureDefined();
void dispose();
void setMeasureSpecs(int widthMeasureSpec, int heightMeasureSpec);
Integer getWidthMeasureSpec();
Integer getHeightMeasureSpec();
Iterable<? extends ReactShadowNode> calculateLayoutOnChildren();
}
| facebook/react-native | packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactShadowNode.java |
2,732 | /*
* Copyright 2022 The Netty Project
*
* The Netty Project licenses this file to you 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:
*
* https://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 io.netty.util;
import io.netty.microbench.util.AbstractMicrobenchmark;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.annotations.Warmup;
import java.util.concurrent.TimeUnit;
@Threads(1)
@Warmup(iterations = 3)
@Measurement(iterations = 3)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public class GetIpV6ByNameBenchmark extends AbstractMicrobenchmark {
@Param({
"::",
"::1234:2345",
"1234:2345::3456:7890",
"fe80::bdad:7a67:6fcd:fa89",
"fe80:bdad:7a67:6fcd::fa89",
"1234:2345:3456:4567:5678:6789:0:7890"
})
private String ip;
@Benchmark
public byte[] getIPv6ByName() {
return NetUtil.getIPv6ByName(ip, true);
}
}
| netty/netty | microbench/src/main/java/io/netty/util/GetIpV6ByNameBenchmark.java |
2,733 | /*
* Scala (https://www.scala-lang.org)
*
* Copyright EPFL and Lightbend, Inc.
*
* Licensed under Apache License 2.0
* (http://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/
package scala.runtime;
import java.lang.invoke.*;
public final class Static {
private Static() {
}
public static CallSite bootstrap(MethodHandles.Lookup lookup, String invokedName, MethodType invokedType, MethodHandle handle, Object... args) throws Throwable {
Object value = handle.invokeWithArguments(args);
return new ConstantCallSite(MethodHandles.constant(invokedType.returnType(), value));
}
}
| scala/scala | src/library/scala/runtime/Static.java |
2,734 | /*
* Scala (https://www.scala-lang.org)
*
* Copyright EPFL and Lightbend, Inc.
*
* Licensed under Apache License 2.0
* (http://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/
package scala.runtime;
public final class CharRef implements java.io.Serializable {
private static final long serialVersionUID = 6537214938268005702L;
public char elem;
public CharRef(char elem) { this.elem = elem; }
public String toString() { return java.lang.Character.toString(elem); }
public static CharRef create(char e) { return new CharRef(e); }
public static CharRef zero() { return new CharRef((char)0); }
}
| scala/scala | src/library/scala/runtime/CharRef.java |
2,735 | package com.googleresearch.bustle;
/** Categories for benchmarks. A benchmark may have any number of tags. */
public enum BenchmarkTag {
// The task involves constant strings extracted from the examples.
CONSTANT,
// The task involves a conditional.
CONDITIONAL,
// The task involves a regex.
REGEX,
// The task involves an array, either a literal {a, b, ...} or created from a function like SPLIT
// or SEQUENCE, or uses an ArrayFormula.
ARRAY,
// The task involves formatting using TEXT(number, format).
TEXT_FORMATTING,
// This task may be excluded from experiments because the simplest known solution is still
// unreasonably difficult.
TOO_DIFFICULT,
// The task is intended to be unsolvable.
SHOULD_FAIL,
}
| google-research/google-research | bustle/com/googleresearch/bustle/BenchmarkTag.java |
2,736 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.uimanager;
import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_UI_MANAGER_MODULE_CONSTANTS_END;
import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_UI_MANAGER_MODULE_CONSTANTS_START;
import static com.facebook.react.uimanager.common.UIManagerType.DEFAULT;
import static com.facebook.react.uimanager.common.UIManagerType.FABRIC;
import android.content.ComponentCallbacks2;
import android.content.res.Configuration;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.facebook.common.logging.FLog;
import com.facebook.debug.holder.PrinterHolder;
import com.facebook.debug.tags.ReactDebugOverlayTags;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.Dynamic;
import com.facebook.react.bridge.GuardedRunnable;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.OnBatchCompleteListener;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMarker;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableType;
import com.facebook.react.bridge.UIManager;
import com.facebook.react.bridge.UIManagerListener;
import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.common.MapBuilder;
import com.facebook.react.common.ReactConstants;
import com.facebook.react.module.annotations.ReactModule;
import com.facebook.react.uimanager.common.ViewUtil;
import com.facebook.react.uimanager.debug.NotThreadSafeViewHierarchyUpdateDebugListener;
import com.facebook.react.uimanager.events.EventDispatcher;
import com.facebook.react.uimanager.events.EventDispatcherImpl;
import com.facebook.react.uimanager.events.RCTEventEmitter;
import com.facebook.systrace.Systrace;
import com.facebook.systrace.SystraceMessage;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Native module to allow JS to create and update native Views.
*
* <p>
*
* <h2>== Transactional Requirement ==</h2>
*
* A requirement of this class is to make sure that transactional UI updates occur all at once,
* meaning that no intermediate state is ever rendered to the screen. For example, if a JS
* application update changes the background of View A to blue and the width of View B to 100, both
* need to appear at once. Practically, this means that all UI update code related to a single
* transaction must be executed as a single code block on the UI thread. Executing as multiple code
* blocks could allow the platform UI system to interrupt and render a partial UI state.
*
* <p>To facilitate this, this module enqueues operations that are then applied to native view
* hierarchy through {@link NativeViewHierarchyManager} at the end of each transaction.
*
* <p>
*
* <h2>== CSSNodes ==</h2>
*
* In order to allow layout and measurement to occur on a non-UI thread, this module also operates
* on intermediate CSSNodeDEPRECATED objects that correspond to a native view. These
* CSSNodeDEPRECATED are able to calculate layout according to their styling rules, and then the
* resulting x/y/width/height of that layout is scheduled as an operation that will be applied to
* native view hierarchy at the end of current batch. TODO(5241856): Investigate memory usage of
* creating many small objects in UIManageModule and consider implementing a pool TODO(5483063):
* Don't dispatch the view hierarchy at the end of a batch if no UI changes occurred
*/
@ReactModule(name = UIManagerModule.NAME)
public class UIManagerModule extends ReactContextBaseJavaModule
implements OnBatchCompleteListener, LifecycleEventListener, UIManager {
public static final String TAG = UIManagerModule.class.getSimpleName();
/** Resolves a name coming from native side to a name of the event that is exposed to JS. */
public interface CustomEventNamesResolver {
/** Returns custom event name by the provided event name. */
@Nullable
String resolveCustomEventName(String eventName);
}
public static final String NAME = "UIManager";
private static final boolean DEBUG =
PrinterHolder.getPrinter().shouldDisplayLogMessage(ReactDebugOverlayTags.UI_MANAGER);
private final EventDispatcher mEventDispatcher;
private final Map<String, Object> mModuleConstants;
private final Map<String, Object> mCustomDirectEvents;
private final ViewManagerRegistry mViewManagerRegistry;
private final UIImplementation mUIImplementation;
private final MemoryTrimCallback mMemoryTrimCallback = new MemoryTrimCallback();
private final List<UIManagerModuleListener> mListeners = new ArrayList<>();
private final CopyOnWriteArrayList<UIManagerListener> mUIManagerListeners =
new CopyOnWriteArrayList<>();
private int mBatchId = 0;
public UIManagerModule(
ReactApplicationContext reactContext,
ViewManagerResolver viewManagerResolver,
int minTimeLeftInFrameForNonBatchedOperationMs) {
super(reactContext);
DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(reactContext);
mEventDispatcher = new EventDispatcherImpl(reactContext);
mModuleConstants = createConstants(viewManagerResolver);
mCustomDirectEvents = UIManagerModuleConstants.getDirectEventTypeConstants();
mViewManagerRegistry = new ViewManagerRegistry(viewManagerResolver);
mUIImplementation =
new UIImplementation(
reactContext,
mViewManagerRegistry,
mEventDispatcher,
minTimeLeftInFrameForNonBatchedOperationMs);
reactContext.addLifecycleEventListener(this);
}
public UIManagerModule(
ReactApplicationContext reactContext,
List<ViewManager> viewManagersList,
int minTimeLeftInFrameForNonBatchedOperationMs) {
super(reactContext);
DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(reactContext);
mEventDispatcher = new EventDispatcherImpl(reactContext);
mCustomDirectEvents = MapBuilder.newHashMap();
mModuleConstants = createConstants(viewManagersList, null, mCustomDirectEvents);
mViewManagerRegistry = new ViewManagerRegistry(viewManagersList);
mUIImplementation =
new UIImplementation(
reactContext,
mViewManagerRegistry,
mEventDispatcher,
minTimeLeftInFrameForNonBatchedOperationMs);
reactContext.addLifecycleEventListener(this);
}
/**
* This method gives an access to the {@link UIImplementation} object that can be used to execute
* operations on the view hierarchy.
*
* @deprecated This method will not be supported by the new architecture of react native.
*/
@Deprecated
public UIImplementation getUIImplementation() {
return mUIImplementation;
}
@Override
public @NonNull String getName() {
return NAME;
}
@Override
public Map<String, Object> getConstants() {
return mModuleConstants;
}
@Override
public void initialize() {
getReactApplicationContext().registerComponentCallbacks(mMemoryTrimCallback);
getReactApplicationContext().registerComponentCallbacks(mViewManagerRegistry);
mEventDispatcher.registerEventEmitter(
DEFAULT, getReactApplicationContext().getJSModule(RCTEventEmitter.class));
}
@Override
public void onHostResume() {
mUIImplementation.onHostResume();
}
@Override
public void onHostPause() {
mUIImplementation.onHostPause();
}
@Override
public void onHostDestroy() {
mUIImplementation.onHostDestroy();
}
@Override
public void invalidate() {
super.invalidate();
mEventDispatcher.onCatalystInstanceDestroyed();
mUIImplementation.onCatalystInstanceDestroyed();
ReactApplicationContext reactApplicationContext = getReactApplicationContext();
reactApplicationContext.unregisterComponentCallbacks(mMemoryTrimCallback);
reactApplicationContext.unregisterComponentCallbacks(mViewManagerRegistry);
YogaNodePool.get().clear();
ViewManagerPropertyUpdater.clear();
}
/**
* This method is intended to reuse the {@link ViewManagerRegistry} with FabricUIManager. Do not
* use this method as this will be removed in the near future.
*/
@Deprecated
public ViewManagerRegistry getViewManagerRegistry_DO_NOT_USE() {
return mViewManagerRegistry;
}
private static Map<String, Object> createConstants(ViewManagerResolver viewManagerResolver) {
ReactMarker.logMarker(CREATE_UI_MANAGER_MODULE_CONSTANTS_START);
SystraceMessage.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "CreateUIManagerConstants")
.arg("Lazy", true)
.flush();
try {
return UIManagerModuleConstantsHelper.createConstants(viewManagerResolver);
} finally {
Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
ReactMarker.logMarker(CREATE_UI_MANAGER_MODULE_CONSTANTS_END);
}
}
public static Map<String, Object> createConstants(
List<ViewManager> viewManagers,
@Nullable Map<String, Object> customBubblingEvents,
@Nullable Map<String, Object> customDirectEvents) {
ReactMarker.logMarker(CREATE_UI_MANAGER_MODULE_CONSTANTS_START);
SystraceMessage.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "CreateUIManagerConstants")
.arg("Lazy", false)
.flush();
try {
return UIManagerModuleConstantsHelper.createConstants(
viewManagers, customBubblingEvents, customDirectEvents);
} finally {
Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
ReactMarker.logMarker(CREATE_UI_MANAGER_MODULE_CONSTANTS_END);
}
}
@ReactMethod(isBlockingSynchronousMethod = true)
public @Nullable WritableMap getConstantsForViewManager(String viewManagerName) {
ViewManager targetView = mUIImplementation.resolveViewManager(viewManagerName);
if (targetView == null) {
return null;
}
return getConstantsForViewManager(targetView, mCustomDirectEvents);
}
public static @Nullable WritableMap getConstantsForViewManager(
ViewManager viewManager, Map<String, Object> customDirectEvents) {
SystraceMessage.beginSection(
Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "UIManagerModule.getConstantsForViewManager")
.arg("ViewManager", viewManager.getName())
.arg("Lazy", true)
.flush();
try {
Map<String, Object> viewManagerConstants =
UIManagerModuleConstantsHelper.createConstantsForViewManager(
viewManager, null, null, null, customDirectEvents);
if (viewManagerConstants != null) {
return Arguments.makeNativeMap(viewManagerConstants);
}
return null;
} finally {
SystraceMessage.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE).flush();
}
}
@ReactMethod(isBlockingSynchronousMethod = true)
public WritableMap getDefaultEventTypes() {
return Arguments.makeNativeMap(UIManagerModuleConstantsHelper.getDefaultExportableEventTypes());
}
/** Resolves Direct Event name exposed to JS from the one known to the Native side. */
@Deprecated
public CustomEventNamesResolver getDirectEventNamesResolver() {
return new CustomEventNamesResolver() {
@Override
public @Nullable String resolveCustomEventName(@Nullable String eventName) {
return resolveCustomDirectEventName(eventName);
}
};
}
@Override
@Deprecated
@Nullable
public String resolveCustomDirectEventName(@Nullable String eventName) {
if (eventName != null) {
Map<String, String> customEventType =
(Map<String, String>) mCustomDirectEvents.get(eventName);
if (customEventType != null) {
return customEventType.get("registrationName");
}
}
return eventName;
}
@Override
public void profileNextBatch() {
mUIImplementation.profileNextBatch();
}
@Override
public Map<String, Long> getPerformanceCounters() {
return mUIImplementation.getProfiledBatchPerfCounters();
}
public <T extends View> int addRootView(final T rootView) {
return addRootView(rootView, null);
}
/**
* Used by native animated module to bypass the process of updating the values through the shadow
* view hierarchy. This method will directly update native views, which means that updates for
* layout-related propertied won't be handled properly. Make sure you know what you're doing
* before calling this method :)
*/
@Override
public void synchronouslyUpdateViewOnUIThread(int tag, ReadableMap props) {
mUIImplementation.synchronouslyUpdateViewOnUIThread(tag, new ReactStylesDiffMap(props));
}
/**
* Registers a new root view. JS can use the returned tag with manageChildren to add/remove
* children to this view.
*
* <p>Calling addRootView through UIManagerModule calls addRootView in the non-Fabric renderer,
* always. This is deprecated in favor of calling startSurface in Fabric, which must be done
* directly through the FabricUIManager.
*
* <p>Note that this must be called after getWidth()/getHeight() actually return something. See
* CatalystApplicationFragment as an example.
*
* <p>TODO(6242243): Make addRootView thread safe NB: this method is horribly not-thread-safe.
*/
@Override
public <T extends View> int addRootView(final T rootView, WritableMap initialProps) {
Systrace.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "UIManagerModule.addRootView");
final int tag = ReactRootViewTagGenerator.getNextRootViewTag();
final ReactApplicationContext reactApplicationContext = getReactApplicationContext();
// We pass in a surfaceId of -1 here - it is used only in Fabric.
final ThemedReactContext themedRootContext =
new ThemedReactContext(
reactApplicationContext,
rootView.getContext(),
((ReactRoot) rootView).getSurfaceID(),
-1);
mUIImplementation.registerRootView(rootView, tag, themedRootContext);
Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
return tag;
}
@Override
public <T extends View> int startSurface(
final T rootView,
final String moduleName,
final WritableMap initialProps,
int widthMeasureSpec,
int heightMeasureSpec) {
throw new UnsupportedOperationException();
}
@Override
public void stopSurface(final int surfaceId) {
throw new UnsupportedOperationException();
}
/** Unregisters a new root view. */
@ReactMethod
public void removeRootView(int rootViewTag) {
mUIImplementation.removeRootView(rootViewTag);
}
public void updateNodeSize(int nodeViewTag, int newWidth, int newHeight) {
getReactApplicationContext().assertOnNativeModulesQueueThread();
mUIImplementation.updateNodeSize(nodeViewTag, newWidth, newHeight);
}
/**
* Sets local data for a shadow node corresponded with given tag. In some cases we need a way to
* specify some environmental data to shadow node to improve layout (or do something similar), so
* {@code localData} serves these needs. For example, any stateful embedded native views may
* benefit from this. Have in mind that this data is not supposed to interfere with the state of
* the shadow view. Please respect one-directional data flow of React.
*/
public void setViewLocalData(final int tag, final Object data) {
final ReactApplicationContext reactApplicationContext = getReactApplicationContext();
reactApplicationContext.assertOnUiQueueThread();
reactApplicationContext.runOnNativeModulesQueueThread(
new GuardedRunnable(reactApplicationContext) {
@Override
public void runGuarded() {
mUIImplementation.setViewLocalData(tag, data);
}
});
}
@ReactMethod
public void createView(int tag, String className, int rootViewTag, ReadableMap props) {
if (DEBUG) {
String message =
"(UIManager.createView) tag: " + tag + ", class: " + className + ", props: " + props;
FLog.d(ReactConstants.TAG, message);
PrinterHolder.getPrinter().logMessage(ReactDebugOverlayTags.UI_MANAGER, message);
}
mUIImplementation.createView(tag, className, rootViewTag, props);
}
@ReactMethod
public void updateView(final int tag, final String className, final ReadableMap props) {
if (DEBUG) {
String message =
"(UIManager.updateView) tag: " + tag + ", class: " + className + ", props: " + props;
FLog.d(ReactConstants.TAG, message);
PrinterHolder.getPrinter().logMessage(ReactDebugOverlayTags.UI_MANAGER, message);
}
mUIImplementation.updateView(tag, className, props);
}
/**
* Interface for adding/removing/moving views within a parent view from JS.
*
* @param viewTag the view tag of the parent view
* @param moveFrom a list of indices in the parent view to move views from
* @param moveTo parallel to moveFrom, a list of indices in the parent view to move views to
* @param addChildTags a list of tags of views to add to the parent
* @param addAtIndices parallel to addChildTags, a list of indices to insert those children at
* @param removeFrom a list of indices of views to permanently remove. The memory for the
* corresponding views and data structures should be reclaimed.
*/
@ReactMethod
public void manageChildren(
int viewTag,
@Nullable ReadableArray moveFrom,
@Nullable ReadableArray moveTo,
@Nullable ReadableArray addChildTags,
@Nullable ReadableArray addAtIndices,
@Nullable ReadableArray removeFrom) {
if (DEBUG) {
String message =
"(UIManager.manageChildren) tag: "
+ viewTag
+ ", moveFrom: "
+ moveFrom
+ ", moveTo: "
+ moveTo
+ ", addTags: "
+ addChildTags
+ ", atIndices: "
+ addAtIndices
+ ", removeFrom: "
+ removeFrom;
FLog.d(ReactConstants.TAG, message);
PrinterHolder.getPrinter().logMessage(ReactDebugOverlayTags.UI_MANAGER, message);
}
mUIImplementation.manageChildren(
viewTag, moveFrom, moveTo, addChildTags, addAtIndices, removeFrom);
}
/**
* Interface for fast tracking the initial adding of views. Children view tags are assumed to be
* in order
*
* @param viewTag the view tag of the parent view
* @param childrenTags An array of tags to add to the parent in order
*/
@ReactMethod
public void setChildren(int viewTag, ReadableArray childrenTags) {
if (DEBUG) {
String message = "(UIManager.setChildren) tag: " + viewTag + ", children: " + childrenTags;
FLog.d(ReactConstants.TAG, message);
PrinterHolder.getPrinter().logMessage(ReactDebugOverlayTags.UI_MANAGER, message);
}
mUIImplementation.setChildren(viewTag, childrenTags);
}
/**
* Determines the location on screen, width, and height of the given view and returns the values
* via an async callback.
*/
@ReactMethod
public void measure(int reactTag, Callback callback) {
mUIImplementation.measure(reactTag, callback);
}
/**
* Determines the location on screen, width, and height of the given view relative to the device
* screen and returns the values via an async callback. This is the absolute position including
* things like the status bar
*/
@ReactMethod
public void measureInWindow(int reactTag, Callback callback) {
mUIImplementation.measureInWindow(reactTag, callback);
}
/**
* Measures the view specified by tag relative to the given ancestorTag. This means that the
* returned x, y are relative to the origin x, y of the ancestor view. Results are stored in the
* given outputBuffer. We allow ancestor view and measured view to be the same, in which case the
* position always will be (0, 0) and method will only measure the view dimensions.
*
* <p>NB: Unlike {@link #measure}, this will measure relative to the view layout, not the visible
* window which can cause unexpected results when measuring relative to things like ScrollViews
* that can have offset content on the screen.
*/
@ReactMethod
public void measureLayout(
int tag, int ancestorTag, Callback errorCallback, Callback successCallback) {
mUIImplementation.measureLayout(tag, ancestorTag, errorCallback, successCallback);
}
/**
* Find the touch target child native view in the supplied root view hierarchy, given a react
* target location.
*
* <p>This method is currently used only by Element Inspector DevTool.
*
* @param reactTag the tag of the root view to traverse
* @param point an array containing both X and Y target location
* @param callback will be called if with the identified child view react ID, and measurement
* info. If no view was found, callback will be invoked with no data.
*/
@ReactMethod
public void findSubviewIn(
final int reactTag, final ReadableArray point, final Callback callback) {
mUIImplementation.findSubviewIn(
reactTag,
Math.round(PixelUtil.toPixelFromDIP(point.getDouble(0))),
Math.round(PixelUtil.toPixelFromDIP(point.getDouble(1))),
callback);
}
/**
* Check if the first shadow node is the descendant of the second shadow node
*
* @deprecated this method will not be available in FabricUIManager class.
*/
@ReactMethod
@Deprecated
public void viewIsDescendantOf(
final int reactTag, final int ancestorReactTag, final Callback callback) {
mUIImplementation.viewIsDescendantOf(reactTag, ancestorReactTag, callback);
}
@ReactMethod
public void setJSResponder(int reactTag, boolean blockNativeResponder) {
mUIImplementation.setJSResponder(reactTag, blockNativeResponder);
}
@ReactMethod
public void clearJSResponder() {
mUIImplementation.clearJSResponder();
}
@ReactMethod
public void dispatchViewManagerCommand(
int reactTag, Dynamic commandId, @Nullable ReadableArray commandArgs) {
// Fabric dispatchCommands should go through the JSI API - this will crash in Fabric.
@Nullable
UIManager uiManager =
UIManagerHelper.getUIManager(
getReactApplicationContext(), ViewUtil.getUIManagerType(reactTag));
if (uiManager == null) {
return;
}
if (commandId.getType() == ReadableType.Number) {
uiManager.dispatchCommand(reactTag, commandId.asInt(), commandArgs);
} else if (commandId.getType() == ReadableType.String) {
uiManager.dispatchCommand(reactTag, commandId.asString(), commandArgs);
}
}
/** Deprecated, use {@link #dispatchCommand(int, String, ReadableArray)} instead. */
@Deprecated
@Override
public void dispatchCommand(int reactTag, int commandId, @Nullable ReadableArray commandArgs) {
mUIImplementation.dispatchViewManagerCommand(reactTag, commandId, commandArgs);
}
@Override
public void dispatchCommand(int reactTag, String commandId, @Nullable ReadableArray commandArgs) {
mUIImplementation.dispatchViewManagerCommand(reactTag, commandId, commandArgs);
}
/**
* LayoutAnimation API on Android is currently experimental. Therefore, it needs to be enabled
* explicitly in order to avoid regression in existing application written for iOS using this API.
*
* <p>Warning : This method will be removed in future version of React Native, and layout
* animation will be enabled by default, so always check for its existence before invoking it.
*
* <p>TODO(9139831) : remove this method once layout animation is fully stable.
*
* @param enabled whether layout animation is enabled or not
*/
@ReactMethod
public void setLayoutAnimationEnabledExperimental(boolean enabled) {
mUIImplementation.setLayoutAnimationEnabledExperimental(enabled);
}
/**
* Configure an animation to be used for the native layout changes, and native views creation. The
* animation will only apply during the current batch operations.
*
* <p>TODO(7728153) : animating view deletion is currently not supported.
*
* @param config the configuration of the animation for view addition/removal/update.
* @param success will be called when the animation completes, or when the animation get
* interrupted. In this case, callback parameter will be false.
* @param error will be called if there was an error processing the animation
*/
@ReactMethod
public void configureNextLayoutAnimation(ReadableMap config, Callback success, Callback error) {
mUIImplementation.configureNextLayoutAnimation(config, success);
}
/**
* To implement the transactional requirement mentioned in the class javadoc, we only commit UI
* changes to the actual view hierarchy once a batch of JS->Java calls have been completed. We
* know this is safe because all JS->Java calls that are triggered by a Java->JS call (e.g. the
* delivery of a touch event or execution of 'renderApplication') end up in a single JS->Java
* transaction.
*
* <p>A better way to do this would be to have JS explicitly signal to this module when a UI
* transaction is done. Right now, though, this is how iOS does it, and we should probably update
* the JS and native code and make this change at the same time.
*
* <p>TODO(5279396): Make JS UI library explicitly notify the native UI module of the end of a UI
* transaction using a standard native call
*/
@Override
public void onBatchComplete() {
int batchId = mBatchId;
mBatchId++;
SystraceMessage.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "onBatchCompleteUI")
.arg("BatchId", batchId)
.flush();
for (UIManagerModuleListener listener : mListeners) {
listener.willDispatchViewUpdates(this);
}
for (UIManagerListener listener : mUIManagerListeners) {
listener.willDispatchViewUpdates(this);
}
try {
// If there are no RootViews registered, there will be no View updates to dispatch.
// This is a hack to prevent this from being called when Fabric is used everywhere.
// This should no longer be necessary in Bridgeless Mode.
if (mUIImplementation.getRootViewNum() > 0) {
mUIImplementation.dispatchViewUpdates(batchId);
}
} finally {
Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
}
}
public void setViewHierarchyUpdateDebugListener(
@Nullable NotThreadSafeViewHierarchyUpdateDebugListener listener) {
mUIImplementation.setViewHierarchyUpdateDebugListener(listener);
}
@Override
public EventDispatcher getEventDispatcher() {
return mEventDispatcher;
}
@ReactMethod
public void sendAccessibilityEvent(int tag, int eventType) {
int uiManagerType = ViewUtil.getUIManagerType(tag);
if (uiManagerType == FABRIC) {
// TODO: T65793557 Refactor sendAccessibilityEvent to use ViewCommands
UIManager fabricUIManager =
UIManagerHelper.getUIManager(getReactApplicationContext(), uiManagerType);
if (fabricUIManager != null) {
fabricUIManager.sendAccessibilityEvent(tag, eventType);
}
} else {
mUIImplementation.sendAccessibilityEvent(tag, eventType);
}
}
/**
* Schedule a block to be executed on the UI thread. Useful if you need to execute view logic
* after all currently queued view updates have completed.
*
* @param block that contains UI logic you want to execute.
* <p>Usage Example:
* <p>UIManagerModule uiManager = reactContext.getNativeModule(UIManagerModule.class);
* uiManager.addUIBlock(new UIBlock() { public void execute (NativeViewHierarchyManager nvhm)
* { View view = nvhm.resolveView(tag); // ...execute your code on View (e.g. snapshot the
* view) } });
*/
public void addUIBlock(UIBlock block) {
mUIImplementation.addUIBlock(block);
}
/**
* Schedule a block to be executed on the UI thread. Useful if you need to execute view logic
* before all currently queued view updates have completed.
*
* @param block that contains UI logic you want to execute.
*/
public void prependUIBlock(UIBlock block) {
mUIImplementation.prependUIBlock(block);
}
@Deprecated
public void addUIManagerListener(UIManagerModuleListener listener) {
mListeners.add(listener);
}
@Deprecated
public void removeUIManagerListener(UIManagerModuleListener listener) {
mListeners.remove(listener);
}
public void addUIManagerEventListener(UIManagerListener listener) {
mUIManagerListeners.add(listener);
}
public void removeUIManagerEventListener(UIManagerListener listener) {
mUIManagerListeners.remove(listener);
}
/**
* Given a reactTag from a component, find its root node tag, if possible. Otherwise, this will
* return 0. If the reactTag belongs to a root node, this will return the same reactTag.
*
* @deprecated this method is not going to be supported in the near future, use {@link
* ViewUtil#isRootTag(int)} to verify if a react Tag is a root or not
* <p>TODO: T63569137 Delete the method UIManagerModule.resolveRootTagFromReactTag
* @param reactTag the component tag
* @return the rootTag
*/
@Deprecated
public int resolveRootTagFromReactTag(int reactTag) {
return ViewUtil.isRootTag(reactTag)
? reactTag
: mUIImplementation.resolveRootTagFromReactTag(reactTag);
}
/** Dirties the node associated with the given react tag */
public void invalidateNodeLayout(int tag) {
ReactShadowNode node = mUIImplementation.resolveShadowNode(tag);
if (node == null) {
FLog.w(
ReactConstants.TAG,
"Warning : attempted to dirty a non-existent react shadow node. reactTag=" + tag);
return;
}
node.dirty();
mUIImplementation.dispatchViewUpdates(-1);
}
/**
* Updates the styles of the {@link ReactShadowNode} based on the Measure specs received by
* parameters. offsetX and offsetY aren't used in non-Fabric, so they're ignored here.
*/
public void updateRootLayoutSpecs(
final int rootViewTag,
final int widthMeasureSpec,
final int heightMeasureSpec,
int offsetX,
int offsetY) {
ReactApplicationContext reactApplicationContext = getReactApplicationContext();
reactApplicationContext.runOnNativeModulesQueueThread(
new GuardedRunnable(reactApplicationContext) {
@Override
public void runGuarded() {
mUIImplementation.updateRootView(rootViewTag, widthMeasureSpec, heightMeasureSpec);
mUIImplementation.dispatchViewUpdates(-1);
}
});
}
/** Listener that drops the CSSNode pool on low memory when the app is backgrounded. */
private static class MemoryTrimCallback implements ComponentCallbacks2 {
@Override
public void onTrimMemory(int level) {
if (level >= TRIM_MEMORY_MODERATE) {
YogaNodePool.get().clear();
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {}
@Override
public void onLowMemory() {}
}
@Override
public View resolveView(int tag) {
UiThreadUtil.assertOnUiThread();
return mUIImplementation
.getUIViewOperationQueue()
.getNativeViewHierarchyManager()
.resolveView(tag);
}
@Override
public void receiveEvent(int reactTag, String eventName, @Nullable WritableMap event) {
receiveEvent(-1, reactTag, eventName, event);
}
@Override
public void receiveEvent(
int surfaceId, int reactTag, String eventName, @Nullable WritableMap event) {
assert ViewUtil.getUIManagerType(reactTag) == DEFAULT;
getReactApplicationContext()
.getJSModule(RCTEventEmitter.class)
.receiveEvent(reactTag, eventName, event);
}
}
| facebook/react-native | packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModule.java |
2,737 | /* ###
* IP: GHIDRA
*
* 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 docking.util.image;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.geom.RectangularShape;
import java.awt.image.BufferedImage;
import java.awt.image.VolatileImage;
import generic.theme.GThemeDefaults.Colors.Palette;
import generic.util.image.ImageUtils;
public class Callout {
private static final Color CALLOUT_SHAPE_COLOR = Palette.getColor("palegreen");
private static final int CALLOUT_BORDER_PADDING = 20;
public Image createCallout(CalloutComponentInfo calloutInfo) {
double distanceFactor = 1.15;
//
// Callout Size
//
Dimension cSize = calloutInfo.getSize();
int newHeight = cSize.height * 4;
int calloutHeight = newHeight;
int calloutWidth = calloutHeight; // square
//
// Callout Distance (from original component)
//
double xDistance = calloutWidth * distanceFactor * .80;
double yDistance = calloutHeight * distanceFactor * distanceFactor;
// only pad if the callout leaves the bounds of the parent image
int padding = 0;
Rectangle cBounds = calloutInfo.getBounds();
Point cLoc = cBounds.getLocation();
if (yDistance > cLoc.y) {
// need some padding!
padding = (int) Math.round(calloutHeight * distanceFactor);
cLoc.y += padding;
cBounds.setLocation(cLoc.x, cLoc.y); // move y down by the padding
}
boolean goLeft = false;
// TODO for now, always go right
// Rectangle pBounds = parentComponent.getBounds();
// double center = pBounds.getCenterX();
// if (cLoc.x > center) {
// goLeft = true; // callout is on the right of center--go to the left
// }
//
// Callout Bounds
//
int calloutX = (int) (cLoc.x + (goLeft ? -(xDistance + calloutWidth) : xDistance));
int calloutY = (int) (cLoc.y + -yDistance);
int backgroundWidth = calloutWidth;
int backgroundHeight = backgroundWidth; // square
Rectangle calloutBounds =
new Rectangle(calloutX, calloutY, backgroundWidth, backgroundHeight);
//
// Full Callout Shape Bounds
//
Rectangle fullBounds = cBounds.union(calloutBounds);
BufferedImage calloutImage =
createCalloutImage(calloutInfo, cLoc, calloutBounds, fullBounds);
// DropShadow dropShadow = new DropShadow();
// Image shadow = dropShadow.createDrowShadow(calloutImage, 40);
//
// Create our final image and draw into it the callout image and its shadow
//
return calloutImage;
// int width = Math.max(shadow.getWidth(null), calloutImage.getWidth());
// int height = Math.max(shadow.getHeight(null), calloutImage.getHeight());
//
// BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
//
// Graphics g = image.getGraphics();
// Graphics2D g2d = (Graphics2D) g;
// g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//
// Point imageLoc = calloutInfo.convertPointToParent(fullBounds.getLocation());
// g2d.drawImage(shadow, imageLoc.x, imageLoc.y, null);
// g2d.drawImage(calloutImage, imageLoc.x, imageLoc.y, null);
//
//
//
//
// Debug
//
// g2d.setColor(Palette.RED);
// g2d.draw(fullBounds);
//
// g2d.setColor(Palette.CYAN);
// g2d.draw(calloutBounds);
//
// g2d.setColor(Palette.BLUE);
// g2d.draw(cBounds);
// return image;
}
public Image createCalloutOnImage(Image image, CalloutComponentInfo calloutInfo) {
//
// This code creates a 'call out' image, which is a round, zoomed image of an area
// in the given image, as chosen by the client. Further, a cone shape will extend
// from the client's chosen location to the callout image we create here.
//
//
// Callout Size
//
Dimension cSize = calloutInfo.getSize();
int newHeight = cSize.height * 6;
int calloutHeight = newHeight;
int calloutWidth = calloutHeight; // square
//
// Callout Distance (from original component). This is the location (relative to
// the original component) of the callout image (not the full shape). So, if the
// x distance was 10, then the callout image would start 10 pixels to the right of
// the component.
//
double distanceX = calloutWidth * 1.5;
double distanceY = calloutHeight * 2;
// only pad if the callout leaves the bounds of the parent image
int topPadding = 0;
Rectangle componentBounds = calloutInfo.getBounds();
Point componentLocation = componentBounds.getLocation();
Point imageComponentLocation = calloutInfo.convertPointToParent(componentLocation);
int calloutImageY = imageComponentLocation.y - ((int) distanceY);
if (calloutImageY < 0) {
// the callout would be drawn off the top of the image; pad the image
topPadding = Math.abs(calloutImageY) + CALLOUT_BORDER_PADDING;
// Also, since we have made the image bigger, we have to the component bounds, as
// the callout image uses these bounds to know where to draw the callout. If we
// don't move them, then the padding will cause the callout to be drawn higher
// by the amount of the padding.
componentLocation.y += topPadding;
componentBounds.setLocation(componentLocation.x, componentLocation.y);
}
//
// Callout Bounds
//
// angle the callout
double theta = Math.toRadians(45);
int calloutX = (int) (componentLocation.x + (Math.cos(theta) * distanceX));
int calloutY = (int) (componentLocation.y - (Math.sin(theta) * distanceY));
int backgroundWidth = calloutWidth;
int backgroundHeight = backgroundWidth; // square
Rectangle calloutBounds =
new Rectangle(calloutX, calloutY, backgroundWidth, backgroundHeight);
//
// Full Callout Shape Bounds (this does not include the drop-shadow)
//
Rectangle calloutDrawingArea = componentBounds.union(calloutBounds);
BufferedImage calloutImage =
createCalloutImage(calloutInfo, componentLocation, calloutBounds, calloutDrawingArea);
DropShadow dropShadow = new DropShadow();
Image shadow = dropShadow.createDropShadow(calloutImage, 40);
//
// Create our final image and draw into it the callout image and its shadow
//
Point calloutImageLoc = calloutInfo.convertPointToParent(calloutDrawingArea.getLocation());
calloutDrawingArea.setLocation(calloutImageLoc);
Rectangle dropShadowBounds = new Rectangle(calloutImageLoc.x, calloutImageLoc.y,
shadow.getWidth(null), shadow.getHeight(null));
Rectangle completeBounds = calloutDrawingArea.union(dropShadowBounds);
int fullBoundsXEndpoint = calloutImageLoc.x + completeBounds.width;
int overlap = fullBoundsXEndpoint - image.getWidth(null);
int rightPadding = 0;
if (overlap > 0) {
rightPadding = overlap + CALLOUT_BORDER_PADDING;
}
int fullBoundsYEndpoint = calloutImageLoc.y + completeBounds.height;
int bottomPadding = 0;
overlap = fullBoundsYEndpoint - image.getHeight(null);
if (overlap > 0) {
bottomPadding = overlap;
}
image =
ImageUtils.padImage(image, Palette.WHITE, topPadding, 0, rightPadding, bottomPadding);
Graphics g = image.getGraphics();
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.drawImage(shadow, calloutImageLoc.x, calloutImageLoc.y, null);
g2d.drawImage(calloutImage, calloutImageLoc.x, calloutImageLoc.y, null);
//
//
//
//
// Debug
//
// g2d.setColor(Palette.RED);
// g2d.draw(fullBounds);
//
// g2d.setColor(Palette.CYAN);
// g2d.draw(calloutBounds);
//
// g2d.setColor(Palette.BLUE);
// g2d.draw(componentBounds);
//
// g2d.setColor(Palette.MAGENTA);
// g2d.draw(completeBounds);
//
// g2d.setColor(Palette.GRAY);
// g2d.draw(dropShadowBounds);
//
// Point cLocation = componentBounds.getLocation();
// Point convertedCLocation = calloutInfo.convertPointToParent(cLocation);
// g2d.setColor(Palette.PINK);
// componentBounds.setLocation(convertedCLocation);
// g2d.draw(componentBounds);
//
// Point convertedFBLocation = calloutInfo.convertPointToParent(fullBounds.getLocation());
// fullBounds.setLocation(convertedFBLocation);
// g2d.setColor(Palette.ORANGE);
// g2d.draw(fullBounds);
return image;
}
private BufferedImage createCalloutImage(CalloutComponentInfo calloutInfo, Point cLoc,
Rectangle calloutBounds, Rectangle fullBounds) {
BufferedImage calloutImage =
new BufferedImage(fullBounds.width, fullBounds.height, BufferedImage.TYPE_INT_ARGB);
Graphics2D cg = (Graphics2D) calloutImage.getGraphics();
cg.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//
// Make relative our two shapes--the component shape and the callout shape
//
Point calloutOrigin = fullBounds.getLocation(); // the shape is relative to the full bounds
int sx = calloutBounds.x - calloutOrigin.x;
int sy = calloutBounds.y - calloutOrigin.y;
Ellipse2D calloutShape =
new Ellipse2D.Double(sx, sy, calloutBounds.width, calloutBounds.height);
int cx = cLoc.x - calloutOrigin.x;
int cy = cLoc.y - calloutOrigin.y;
Dimension cSize = calloutInfo.getSize();
// TODO this shows how to correctly account for scaling in the Function Graph
// Dimension cSize2 = new Dimension(cSize);
// double scale = .5d;
// cSize2.width *= scale;
// cSize2.height *= scale;
Rectangle componentShape = new Rectangle(new Point(cx, cy), cSize);
paintCalloutArrow(cg, componentShape, calloutShape);
paintCalloutCircularImage(cg, calloutInfo, calloutShape);
cg.dispose();
return calloutImage;
}
private void paintCalloutCircularImage(Graphics2D g, CalloutComponentInfo calloutInfo,
RectangularShape shape) {
//
// First draw the background circle that will sit beneath the image, to create a
// ring around the image
//
g.setColor(CALLOUT_SHAPE_COLOR);
g.fill(shape);
//
// Now, make the image a bit smaller, so that the background is a ring around the image
//
int offset = 3;
Rectangle sr = shape.getBounds(); // shape rectangle
Rectangle ir = new Rectangle(); // image rectangle
ir.x = sr.x + offset;
ir.y = sr.y + offset;
ir.width = sr.width - (2 * offset);
ir.height = sr.height - (2 * offset);
shape.setFrame(ir); // change the size for the image
Dimension imageSize = ir.getSize();
Image foregroundImage =
createMagnifiedImage(g.getDeviceConfiguration(), imageSize, calloutInfo, shape);
shape.setFrame(sr); // restore
g.drawImage(foregroundImage, ir.x, ir.y, null);
}
private void paintCalloutArrow(Graphics2D g2d, RectangularShape componentShape,
RectangularShape calloutShape) {
Rectangle cr = componentShape.getBounds();
Rectangle sr = calloutShape.getBounds();
Point p1 = new Point((int) cr.getCenterX(), (int) cr.getCenterY());
Point p2 = new Point(sr.x + (sr.width / 2), sr.y + (sr.height / 2));
//
// Calculate the tangents to the callout circle
//
int radius = sr.width / 2;
int dx = p2.x - p1.x;
int dy = p2.y - p1.y;
double distance = Math.sqrt(dx * dx + dy * dy);
double alpha = Math.asin(radius / distance);
double beta = Math.atan2(dy, dx);
double theta = beta - alpha;
double x = radius * Math.sin(theta) + p2.x;
double y = radius * -Math.cos(theta) + p2.y;
Point tangentA = new Point((int) Math.round(x), (int) Math.round(y));
theta = beta + alpha;
x = radius * -Math.sin(theta) + p2.x;
y = radius * Math.cos(theta) + p2.y;
Point tangentB = new Point((int) Math.round(x), (int) Math.round(y));
g2d.setColor(CALLOUT_SHAPE_COLOR);
Polygon p = new Polygon();
p.addPoint(p1.x, p1.y);
p.addPoint(tangentA.x, tangentA.y);
p.addPoint(tangentB.x, tangentB.y);
g2d.fillPolygon(p);
}
private Image createMagnifiedImage(GraphicsConfiguration gc, Dimension imageSize,
CalloutComponentInfo calloutInfo, RectangularShape imageShape) {
Dimension componentSize = calloutInfo.getSize();
Point componentScreenLocation = calloutInfo.getLocationOnScreen();
Rectangle r = new Rectangle(componentScreenLocation, componentSize);
int offset = 100;
r.x -= offset;
r.y -= offset;
r.width += 2 * offset;
r.height += 2 * offset;
Image compImage = null;
try {
Robot robot = new Robot();
compImage = robot.createScreenCapture(r);
}
catch (AWTException e) {
throw new RuntimeException("boom", e);
}
double magnification = calloutInfo.getMagnification();
int newWidth = (int) (compImage.getWidth(null) * magnification);
int newHeight = (int) (compImage.getHeight(null) * magnification);
compImage = ImageUtils.createScaledImage(compImage, newWidth, newHeight, 0);
Rectangle bounds = imageShape.getBounds();
VolatileImage image =
gc.createCompatibleVolatileImage(bounds.width, bounds.height, Transparency.TRANSLUCENT);
Graphics2D g = (Graphics2D) image.getGraphics();
// update all pixels to have 0 alpha
g.setComposite(AlphaComposite.Clear);
// update the shape to be relative to the new image's origin
Rectangle relativeFrame = new Rectangle(new Point(0, 0), bounds.getSize());
imageShape.setFrame(relativeFrame);
g.fill(relativeFrame);
// render the clip shape into the image
g.setComposite(AlphaComposite.Src);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(Palette.WHITE);
g.fill(imageShape);
imageShape.setFrame(bounds); // restore
// Using ScrAtop uses the alpha value as a coverage for each pixel stored in
// the destination. For the areas outside the clip shape, the destination alpha will
// be zero, so nothing is rendered in those areas.
g.setComposite(AlphaComposite.SrcAtop);
int cw = compImage.getWidth(null);
int ch = compImage.getHeight(null);
int x = -((cw / 2) - (bounds.width / 2));
int y = -((ch / 2) - (bounds.height / 2));
g.drawImage(compImage, x, y, cw, ch, null);
g.dispose();
return image;
}
}
| NationalSecurityAgency/ghidra | Ghidra/Framework/Docking/src/main/java/docking/util/image/Callout.java |
2,738 | /*
* Scala (https://www.scala-lang.org)
*
* Copyright EPFL and Lightbend, Inc.
*
* Licensed under Apache License 2.0
* (http://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/
package scala.runtime;
public final class BoxedUnit implements java.io.Serializable {
private static final long serialVersionUID = 8405543498931817370L;
public final static BoxedUnit UNIT = new BoxedUnit();
public final static Class<Void> TYPE = java.lang.Void.TYPE;
private Object readResolve() { return UNIT; }
private BoxedUnit() { }
public boolean equals(java.lang.Object other) {
return this == other;
}
public int hashCode() {
return 0;
}
public String toString() {
return "()";
}
}
| scala/scala | src/library/scala/runtime/BoxedUnit.java |
2,739 | /* ###
* IP: Apache License 2.0 with LLVM Exceptions
*/
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (https://www.swig.org).
* Version 4.1.1
*
* Do not make changes to this file unless you know what you are doing - modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package SWIG;
public class SBEnvironment {
private transient long swigCPtr;
protected transient boolean swigCMemOwn;
protected SBEnvironment(long cPtr, boolean cMemoryOwn) {
swigCMemOwn = cMemoryOwn;
swigCPtr = cPtr;
}
protected static long getCPtr(SBEnvironment obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
protected static long swigRelease(SBEnvironment obj) {
long ptr = 0;
if (obj != null) {
if (!obj.swigCMemOwn)
throw new RuntimeException("Cannot release ownership as memory is not owned");
ptr = obj.swigCPtr;
obj.swigCMemOwn = false;
obj.delete();
}
return ptr;
}
@SuppressWarnings("deprecation")
protected void finalize() {
delete();
}
public synchronized void delete() {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
lldbJNI.delete_SBEnvironment(swigCPtr);
}
swigCPtr = 0;
}
}
public SBEnvironment() {
this(lldbJNI.new_SBEnvironment__SWIG_0(), true);
}
public SBEnvironment(SBEnvironment rhs) {
this(lldbJNI.new_SBEnvironment__SWIG_1(SBEnvironment.getCPtr(rhs), rhs), true);
}
public String Get(String name) {
return lldbJNI.SBEnvironment_Get(swigCPtr, this, name);
}
public long GetNumValues() {
return lldbJNI.SBEnvironment_GetNumValues(swigCPtr, this);
}
public String GetNameAtIndex(long index) {
return lldbJNI.SBEnvironment_GetNameAtIndex(swigCPtr, this, index);
}
public String GetValueAtIndex(long index) {
return lldbJNI.SBEnvironment_GetValueAtIndex(swigCPtr, this, index);
}
public SBStringList GetEntries() {
return new SBStringList(lldbJNI.SBEnvironment_GetEntries(swigCPtr, this), true);
}
public void PutEntry(String name_and_value) {
lldbJNI.SBEnvironment_PutEntry(swigCPtr, this, name_and_value);
}
public void SetEntries(SBStringList entries, boolean append) {
lldbJNI.SBEnvironment_SetEntries(swigCPtr, this, SBStringList.getCPtr(entries), entries, append);
}
public boolean Set(String name, String value, boolean overwrite) {
return lldbJNI.SBEnvironment_Set(swigCPtr, this, name, value, overwrite);
}
public boolean Unset(String name) {
return lldbJNI.SBEnvironment_Unset(swigCPtr, this, name);
}
public void Clear() {
lldbJNI.SBEnvironment_Clear(swigCPtr, this);
}
}
| NationalSecurityAgency/ghidra | Ghidra/Debug/Debugger-swig-lldb/src/main/java/SWIG/SBEnvironment.java |
2,740 | /*
* Copyright 2020 The Netty Project
*
* The Netty Project licenses this file to you 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:
*
* https://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 io.netty.microbench.search;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.buffer.search.AbstractMultiSearchProcessorFactory;
import io.netty.buffer.search.AbstractSearchProcessorFactory;
import io.netty.buffer.search.SearchProcessorFactory;
import io.netty.microbench.util.AbstractMicrobenchmark;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.CompilerControl;
import org.openjdk.jmh.annotations.CompilerControl.Mode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.TearDown;
import org.openjdk.jmh.annotations.Warmup;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Warmup(iterations = 5)
@Measurement(iterations = 5)
@Fork(1)
public class SearchBenchmark extends AbstractMicrobenchmark {
private static final long SEED = 123;
public enum Input {
RANDOM_256B {
@Override
byte[] getNeedle(Random rnd) {
return new byte[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' };
}
@Override
byte[] getHaystack(Random rnd) {
return randomBytes(rnd, 256, ' ', 127);
}
},
RANDOM_2KB {
@Override
byte[] getNeedle(Random rnd) {
return new byte[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' };
}
@Override
byte[] getHaystack(Random rnd) {
return randomBytes(rnd, 2048, ' ', 127);
}
},
PREDICTABLE {
@Override
byte[] getNeedle(Random rnd) {
// all 0s
return new byte[64];
}
@Override
byte[] getHaystack(Random rnd) {
// no 0s except in the very end
byte[] bytes = randomBytes(rnd, 2048, 1, 255);
Arrays.fill(bytes, bytes.length - 64, bytes.length, (byte) 0);
return bytes;
}
},
UNPREDICTABLE {
@Override
byte[] getNeedle(Random rnd) {
return randomBytes(rnd, 64, 0, 1);
}
@Override
byte[] getHaystack(Random rnd) {
return randomBytes(rnd, 2048, 0, 1);
}
},
WORST_CASE { // Bitap will fail on it because the needle is >64 bytes long
@Override
byte[] getNeedle(Random rnd) {
// aa(...)aab
byte[] needle = new byte[1024];
Arrays.fill(needle, (byte) 'a');
needle[needle.length - 1] = 'b';
return needle;
}
@Override
byte[] getHaystack(Random rnd) {
// aa(...)aaa
byte[] haystack = new byte[2048];
Arrays.fill(haystack, (byte) 'a');
return haystack;
}
};
abstract byte[] getNeedle(Random rnd);
abstract byte[] getHaystack(Random rnd);
}
@Param
public Input input;
@Param
public ByteBufType bufferType;
private Random rnd;
private ByteBuf needle, haystack;
private byte[] needleBytes, haystackBytes;
private SearchProcessorFactory kmpFactory, bitapFactory, ahoCorasicFactory;
@Setup
public void setup() {
rnd = new Random(SEED);
needleBytes = input.getNeedle(rnd);
haystackBytes = input.getHaystack(rnd);
needle = Unpooled.wrappedBuffer(needleBytes);
haystack = bufferType.newBuffer(haystackBytes);
kmpFactory = AbstractSearchProcessorFactory.newKmpSearchProcessorFactory(needleBytes);
ahoCorasicFactory = AbstractMultiSearchProcessorFactory.newAhoCorasicSearchProcessorFactory(needleBytes);
if (needleBytes.length <= 64) {
bitapFactory = AbstractSearchProcessorFactory.newBitapSearchProcessorFactory(needleBytes);
}
}
@TearDown
public void teardown() {
needle.release();
haystack.release();
}
@Benchmark
@CompilerControl(Mode.DONT_INLINE)
public int indexOf() {
return ByteBufUtil.indexOf(needle, haystack);
}
@Benchmark
@CompilerControl(Mode.DONT_INLINE)
public int kmp() {
return haystack.forEachByte(kmpFactory.newSearchProcessor());
}
@Benchmark
@CompilerControl(Mode.DONT_INLINE)
public int bitap() {
return haystack.forEachByte(bitapFactory.newSearchProcessor());
}
@Benchmark
@CompilerControl(Mode.DONT_INLINE)
public int ahoCorasic() {
return haystack.forEachByte(ahoCorasicFactory.newSearchProcessor());
}
private static byte[] randomBytes(Random rnd, int size, int from, int to) {
byte[] bytes = new byte[size];
for (int i = 0; i < size; i++) {
bytes[i] = (byte) (from + rnd.nextInt(to - from + 1));
}
return bytes;
}
}
| netty/netty | microbench/src/main/java/io/netty/microbench/search/SearchBenchmark.java |
2,741 | package com.winterbe.java8.samples.stream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
/**
* @author Benjamin Winterberg
*/
public class Streams7 {
static class Foo {
String name;
List<Bar> bars = new ArrayList<>();
Foo(String name) {
this.name = name;
}
}
static class Bar {
String name;
Bar(String name) {
this.name = name;
}
}
public static void main(String[] args) {
// test1();
test2();
}
static void test2() {
IntStream.range(1, 4)
.mapToObj(num -> new Foo("Foo" + num))
.peek(f -> IntStream.range(1, 4)
.mapToObj(num -> new Bar("Bar" + num + " <- " + f.name))
.forEach(f.bars::add))
.flatMap(f -> f.bars.stream())
.forEach(b -> System.out.println(b.name));
}
static void test1() {
List<Foo> foos = new ArrayList<>();
IntStream
.range(1, 4)
.forEach(num -> foos.add(new Foo("Foo" + num)));
foos.forEach(f ->
IntStream
.range(1, 4)
.forEach(num -> f.bars.add(new Bar("Bar" + num + " <- " + f.name))));
foos.stream()
.flatMap(f -> f.bars.stream())
.forEach(b -> System.out.println(b.name));
}
} | winterbe/java8-tutorial | src/com/winterbe/java8/samples/stream/Streams7.java |
2,742 | package com.winterbe.java8.samples.concurrent;
import java.util.concurrent.TimeUnit;
/**
* @author Benjamin Winterberg
*/
public class Threads1 {
public static void main(String[] args) {
test1();
// test2();
// test3();
}
private static void test3() {
Runnable runnable = () -> {
try {
System.out.println("Foo " + Thread.currentThread().getName());
TimeUnit.SECONDS.sleep(1);
System.out.println("Bar " + Thread.currentThread().getName());
}
catch (InterruptedException e) {
e.printStackTrace();
}
};
Thread thread = new Thread(runnable);
thread.start();
}
private static void test2() {
Runnable runnable = () -> {
try {
System.out.println("Foo " + Thread.currentThread().getName());
Thread.sleep(1000);
System.out.println("Bar " + Thread.currentThread().getName());
}
catch (InterruptedException e) {
e.printStackTrace();
}
};
Thread thread = new Thread(runnable);
thread.start();
}
private static void test1() {
Runnable runnable = () -> {
String threadName = Thread.currentThread().getName();
System.out.println("Hello " + threadName);
};
runnable.run();
Thread thread = new Thread(runnable);
thread.start();
System.out.println("Done!");
}
}
| winterbe/java8-tutorial | src/com/winterbe/java8/samples/concurrent/Threads1.java |
2,744 | package com.winterbe.java8.samples.concurrent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.IntStream;
/**
* @author Benjamin Winterberg
*/
public class Lock1 {
private static final int NUM_INCREMENTS = 10000;
private static ReentrantLock lock = new ReentrantLock();
private static int count = 0;
private static void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
testLock();
}
private static void testLock() {
count = 0;
ExecutorService executor = Executors.newFixedThreadPool(2);
IntStream.range(0, NUM_INCREMENTS)
.forEach(i -> executor.submit(Lock1::increment));
ConcurrentUtils.stop(executor);
System.out.println(count);
}
}
| winterbe/java8-tutorial | src/com/winterbe/java8/samples/concurrent/Lock1.java |
2,746 | /*
* Scala (https://www.scala-lang.org)
*
* Copyright EPFL and Lightbend, Inc.
*
* Licensed under Apache License 2.0
* (http://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/
package scala.runtime;
public final class VolatileByteRef implements java.io.Serializable {
private static final long serialVersionUID = -100666928446877072L;
volatile public byte elem;
public VolatileByteRef(byte elem) { this.elem = elem; }
public String toString() { return java.lang.Byte.toString(elem); }
public static VolatileByteRef create(byte e) { return new VolatileByteRef(e); }
public static VolatileByteRef zero() { return new VolatileByteRef((byte)0); }
}
| scala/scala | src/library/scala/runtime/VolatileByteRef.java |
2,747 | /*
* Scala (https://www.scala-lang.org)
*
* Copyright EPFL and Lightbend, Inc.
*
* Licensed under Apache License 2.0
* (http://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/
package scala.runtime;
public final class VolatileCharRef implements java.io.Serializable {
private static final long serialVersionUID = 6537214938268005702L;
volatile public char elem;
public VolatileCharRef(char elem) { this.elem = elem; }
public String toString() { return java.lang.Character.toString(elem); }
public static VolatileCharRef create(char e) { return new VolatileCharRef(e); }
public static VolatileCharRef zero() { return new VolatileCharRef((char)0); }
}
| scala/scala | src/library/scala/runtime/VolatileCharRef.java |
2,748 | /*
* Copyright 2020 The Netty Project
*
* The Netty Project licenses this file to you 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:
*
* https://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 io.netty.microbench.stomp;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.stomp.DefaultStompFrame;
import io.netty.handler.codec.stomp.StompFrame;
import io.netty.handler.codec.stomp.StompHeadersSubframe;
import io.netty.handler.codec.stomp.StompSubframeEncoder;
import io.netty.microbench.channel.EmbeddedChannelWriteReleaseHandlerContext;
import io.netty.microbench.util.AbstractMicrobenchmark;
import io.netty.util.internal.ThreadLocalRandom;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.profile.GCProfiler;
import org.openjdk.jmh.runner.options.ChainedOptionsBuilder;
@State(Scope.Benchmark)
@Fork(value = 2)
@Threads(1)
@Warmup(iterations = 5)
@Measurement(iterations = 10)
public class StompEncoderBenchmark extends AbstractMicrobenchmark {
private StompSubframeEncoder stompEncoder;
private ByteBuf content;
private StompFrame stompFrame;
private ChannelHandlerContext context;
@Param({ "true", "false" })
public boolean pooledAllocator;
@Param({ "true", "false" })
public boolean voidPromise;
@Param
public ExampleStompHeadersSubframe.HeadersType headersType;
@Param({ "0", "100", "1000" })
public int contentLength;
@Setup(Level.Trial)
public void setup() {
byte[] bytes = new byte[contentLength];
ThreadLocalRandom.current().nextBytes(bytes);
content = Unpooled.wrappedBuffer(bytes);
ByteBuf testContent = Unpooled.unreleasableBuffer(content.asReadOnly());
StompHeadersSubframe headersSubframe = ExampleStompHeadersSubframe.EXAMPLES.get(headersType);
stompFrame = new DefaultStompFrame(headersSubframe.command(), testContent);
stompFrame.headers().setAll(headersSubframe.headers());
stompEncoder = new StompSubframeEncoder();
context = new EmbeddedChannelWriteReleaseHandlerContext(
pooledAllocator? PooledByteBufAllocator.DEFAULT : UnpooledByteBufAllocator.DEFAULT, stompEncoder) {
@Override
protected void handleException(Throwable t) {
handleUnexpectedException(t);
}
};
}
@TearDown(Level.Trial)
public void teardown() {
content.release();
content = null;
}
@Benchmark
public void writeStompFrame() throws Exception {
stompEncoder.write(context, stompFrame.retain(), newPromise());
}
private ChannelPromise newPromise() {
return voidPromise? context.voidPromise() : context.newPromise();
}
@Override
protected ChainedOptionsBuilder newOptionsBuilder() throws Exception {
return super.newOptionsBuilder().addProfiler(GCProfiler.class);
}
}
| netty/netty | microbench/src/main/java/io/netty/microbench/stomp/StompEncoderBenchmark.java |
2,749 | /*
* Copyright 2016 The Netty Project
*
* The Netty Project licenses this file to you 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:
*
* https://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 io.netty.microbench.redis;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.redis.ArrayRedisMessage;
import io.netty.handler.codec.redis.FullBulkStringRedisMessage;
import io.netty.handler.codec.redis.RedisEncoder;
import io.netty.handler.codec.redis.RedisMessage;
import io.netty.microbench.channel.EmbeddedChannelWriteReleaseHandlerContext;
import io.netty.microbench.util.AbstractMicrobenchmark;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.annotations.Warmup;
import java.util.ArrayList;
import java.util.List;
@State(Scope.Benchmark)
@Fork(1)
@Threads(1)
@Warmup(iterations = 5)
@Measurement(iterations = 5)
public class RedisEncoderBenchmark extends AbstractMicrobenchmark {
private RedisEncoder encoder;
private ByteBuf content;
private ChannelHandlerContext context;
private ArrayRedisMessage redisArray;
@Param({ "true", "false" })
public boolean pooledAllocator;
@Param({ "true", "false" })
public boolean voidPromise;
@Param({ "50", "200", "1000" })
public int arraySize;
@Setup(Level.Trial)
public void setup() {
byte[] bytes = new byte[256];
content = Unpooled.buffer(bytes.length);
content.writeBytes(bytes);
ByteBuf testContent = Unpooled.unreleasableBuffer(content.asReadOnly());
List<RedisMessage> rList = new ArrayList<RedisMessage>(arraySize);
for (int i = 0; i < arraySize; ++i) {
rList.add(new FullBulkStringRedisMessage(testContent));
}
redisArray = new ArrayRedisMessage(rList);
encoder = new RedisEncoder();
context = new EmbeddedChannelWriteReleaseHandlerContext(pooledAllocator ? PooledByteBufAllocator.DEFAULT :
UnpooledByteBufAllocator.DEFAULT, encoder) {
@Override
protected void handleException(Throwable t) {
handleUnexpectedException(t);
}
};
}
@TearDown(Level.Trial)
public void teardown() {
content.release();
content = null;
}
@Benchmark
public void writeArray() throws Exception {
encoder.write(context, redisArray.retain(), newPromise());
}
private ChannelPromise newPromise() {
return voidPromise ? context.voidPromise() : context.newPromise();
}
}
| netty/netty | microbench/src/main/java/io/netty/microbench/redis/RedisEncoderBenchmark.java |
2,750 | /*
* Scala (https://www.scala-lang.org)
*
* Copyright EPFL and Lightbend, Inc.
*
* Licensed under Apache License 2.0
* (http://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/
package scala.runtime;
public final class VolatileFloatRef implements java.io.Serializable {
private static final long serialVersionUID = -5793980990371366933L;
volatile public float elem;
public VolatileFloatRef(float elem) { this.elem = elem; }
public String toString() { return java.lang.Float.toString(elem); }
public static VolatileFloatRef create(float e) { return new VolatileFloatRef(e); }
public static VolatileFloatRef zero() { return new VolatileFloatRef(0); }
}
| scala/scala | src/library/scala/runtime/VolatileFloatRef.java |
2,751 | /*
* Copyright 2020 The Netty Project
*
* The Netty Project licenses this file to you 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:
*
* https://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 io.netty.microbench.buffer;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.microbench.util.AbstractMicrobenchmark;
import io.netty.util.AsciiString;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.CompilerControl;
import org.openjdk.jmh.annotations.CompilerControl.Mode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Setup;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
@Fork(value = 2, jvmArgsAppend = "-XX:MaxInlineLevel=9")
public class Utf8EncodingBenchmark extends AbstractMicrobenchmark {
private static class AnotherCharSequence implements CharSequence {
private final char[] chars;
AnotherCharSequence(String chars) {
this.chars = new char[chars.length()];
chars.getChars(0, chars.length(), this.chars, 0);
}
@Override
public int length() {
return chars.length;
}
@Override
public char charAt(int i) {
return chars[i];
}
@Override
public CharSequence subSequence(int start, int end) {
throw new UnsupportedOperationException();
}
@Override
public String toString() {
throw new UnsupportedOperationException();
}
}
// experiment test input
private String[] strings;
private StringBuilder[] stringBuilders;
private AnotherCharSequence[] anotherCharSequences;
private AsciiString[] asciiStrings;
@Param({ "false", "true" })
private boolean direct;
private ByteBuf buffer;
@Param({ "false", "true" })
private boolean noUnsafe;
private int dataSetLength;
@Setup
public void init() {
System.setProperty("io.netty.noUnsafe", Boolean.valueOf(noUnsafe).toString());
InputStream testTextStream = null;
InputStreamReader inStreamReader = null;
BufferedReader buffReader = null;
int maxExpectedSize = 0;
List<String> strings = new ArrayList<String>();
List<StringBuilder> stringBuilders = new ArrayList<StringBuilder>();
List<AnotherCharSequence> anotherCharSequenceList = new ArrayList<AnotherCharSequence>();
List<AsciiString> asciiStrings = new ArrayList<AsciiString>();
try {
testTextStream = getClass().getResourceAsStream("/Utf8Samples.txt");
inStreamReader = new InputStreamReader(testTextStream, "UTF-8");
buffReader = new BufferedReader(inStreamReader);
String line;
while ((line = buffReader.readLine()) != null) {
strings.add(line);
stringBuilders.add(new StringBuilder(line));
anotherCharSequenceList.add(new AnotherCharSequence(line));
asciiStrings.add(new AsciiString(line));
maxExpectedSize = Math.max(maxExpectedSize, ByteBufUtil.utf8MaxBytes(line.length()));
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
closeStream(testTextStream);
closeReader(inStreamReader);
closeReader(buffReader);
}
buffer = direct? Unpooled.directBuffer(maxExpectedSize, maxExpectedSize) :
Unpooled.buffer(maxExpectedSize, maxExpectedSize);
buffer.setByte(maxExpectedSize - 1, 0);
this.strings = strings.toArray(new String[strings.size()]);
this.stringBuilders = stringBuilders.toArray(new StringBuilder[stringBuilders.size()]);
this.anotherCharSequences =
anotherCharSequenceList.toArray(new AnotherCharSequence[anotherCharSequenceList.size()]);
this.asciiStrings = asciiStrings.toArray(new AsciiString[asciiStrings.size()]);
this.dataSetLength = this.strings.length;
}
private static void closeStream(InputStream inStream) {
if (inStream != null) {
try {
inStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
private static void closeReader(Reader buffReader) {
if (buffReader != null) {
try {
buffReader.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@Benchmark
@CompilerControl(Mode.DONT_INLINE)
public int nestedByteBufUtilWriteUtf8String() {
int countBytes = 0;
for (String string : strings) {
countBytes += nestedByteBufUtilWriteUtf8String1(string);
}
return countBytes;
}
private int nestedByteBufUtilWriteUtf8String1(String string) {
return nestedByteBufUtilWriteUtf8String2(string);
}
private int nestedByteBufUtilWriteUtf8String2(String string) {
return nestedByteBufUtilWriteUtf8String3(string);
}
private int nestedByteBufUtilWriteUtf8String3(String string) {
return nestedByteBufUtilWriteUtf8String4(string);
}
private int nestedByteBufUtilWriteUtf8String4(String string) {
return nestedByteBufUtilWriteUtf8String5(string);
}
private int nestedByteBufUtilWriteUtf8String5(String string) {
return nestedByteBufUtilWriteUtf8String6(string);
}
private int nestedByteBufUtilWriteUtf8String6(String string) {
// this calls should be inlined but...what happen to the subsequent calls > MaxInlineLevel?
buffer.resetWriterIndex();
ByteBufUtil.writeUtf8(buffer, string, 0, string.length());
return buffer.writerIndex();
}
@Benchmark
@CompilerControl(Mode.DONT_INLINE)
public int byteBufUtilWriteUtf8String() {
int countBytes = 0;
for (String string : strings) {
buffer.resetWriterIndex();
ByteBufUtil.writeUtf8(buffer, string, 0, string.length());
countBytes += buffer.writerIndex();
}
return countBytes;
}
@Benchmark
@CompilerControl(Mode.DONT_INLINE)
public int byteBufUtilWriteUtf8Bimorphic() {
int countBytes = 0;
for (int i = 0, size = dataSetLength; i < size; i++) {
final StringBuilder stringBuilder = stringBuilders[i];
final String string = strings[i];
buffer.resetWriterIndex();
ByteBufUtil.writeUtf8(buffer, stringBuilder, 0, stringBuilder.length());
countBytes += buffer.writerIndex();
buffer.resetWriterIndex();
ByteBufUtil.writeUtf8(buffer, string, 0, string.length());
countBytes += buffer.writerIndex();
}
return countBytes;
}
@Benchmark
@CompilerControl(Mode.DONT_INLINE)
public int byteBufUtilWriteUtf8Megamorphic() {
int countBytes = 0;
for (int i = 0, size = dataSetLength; i < size; i++) {
final StringBuilder stringBuilder = stringBuilders[i];
final String string = strings[i];
final AnotherCharSequence anotherCharSequence = anotherCharSequences[i];
buffer.resetWriterIndex();
ByteBufUtil.writeUtf8(buffer, stringBuilder, 0, stringBuilder.length());
countBytes += buffer.writerIndex();
buffer.resetWriterIndex();
ByteBufUtil.writeUtf8(buffer, string, 0, string.length());
countBytes += buffer.writerIndex();
buffer.resetWriterIndex();
ByteBufUtil.writeUtf8(buffer, anotherCharSequence, 0, anotherCharSequence.length());
countBytes += buffer.writerIndex();
}
return countBytes;
}
@Benchmark
@CompilerControl(Mode.DONT_INLINE)
public int byteBufUtilWriteUtf8CommonCharSequences() {
int countBytes = 0;
for (int i = 0, size = dataSetLength; i < size; i++) {
final StringBuilder stringBuilder = stringBuilders[i];
final String string = strings[i];
final AsciiString asciiString = asciiStrings[i];
buffer.resetWriterIndex();
ByteBufUtil.writeUtf8(buffer, stringBuilder, 0, stringBuilder.length());
countBytes += buffer.writerIndex();
buffer.resetWriterIndex();
ByteBufUtil.writeUtf8(buffer, string, 0, string.length());
countBytes += buffer.writerIndex();
buffer.resetWriterIndex();
ByteBufUtil.writeUtf8(buffer, asciiString, 0, asciiString.length());
countBytes += buffer.writerIndex();
}
return countBytes;
}
@Benchmark
@CompilerControl(Mode.DONT_INLINE)
public int byteBufUtilWriteUtf8AsciiString() {
int countBytes = 0;
for (int i = 0, size = dataSetLength; i < size; i++) {
final AsciiString asciiString = asciiStrings[i];
buffer.resetWriterIndex();
ByteBufUtil.writeUtf8(buffer, asciiString, 0, asciiString.length());
countBytes += buffer.writerIndex();
}
return countBytes;
}
@Benchmark
@CompilerControl(Mode.DONT_INLINE)
public int writeGetBytes() throws UnsupportedEncodingException {
int countBytes = 0;
for (String string : strings) {
buffer.resetWriterIndex();
final byte[] bytes = string.getBytes("UTF-8");
buffer.writeBytes(bytes);
countBytes += buffer.writerIndex();
}
return countBytes;
}
}
| netty/netty | microbench/src/main/java/io/netty/microbench/buffer/Utf8EncodingBenchmark.java |
2,752 | /*
* Copyright 2024 The Netty Project
*
* The Netty Project licenses this file to you 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:
*
* https://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 io.netty.util;
import io.netty.util.internal.SuppressJava6Requirement;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.annotations.Warmup;
import java.util.SplittableRandom;
import java.util.concurrent.TimeUnit;
@Threads(1)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Fork(2)
@Warmup(iterations = 5, time = 1)
@Measurement(iterations = 8, time = 1)
@State(Scope.Benchmark)
public class AsciiStringCaseConversionBenchmark {
@Param({ "7", "16", "23", "32" })
int size;
@Param({ "4", "11" })
int logPermutations;
@Param({ "0" })
int seed;
int permutations;
AsciiString[] asciiStringData;
String[] stringData;
byte[] ret;
private int i;
@Param({ "true", "false" })
private boolean noUnsafe;
@Setup(Level.Trial)
@SuppressJava6Requirement(reason = "using SplittableRandom to reliably produce data")
public void init() {
System.setProperty("io.netty.noUnsafe", Boolean.valueOf(noUnsafe).toString());
final SplittableRandom random = new SplittableRandom(seed);
permutations = 1 << logPermutations;
ret = new byte[size];
asciiStringData = new AsciiString[permutations];
stringData = new String[permutations];
for (int i = 0; i < permutations; ++i) {
final int foundIndex = random.nextInt(Math.max(0, size - 8), size);
final byte[] byteArray = new byte[size];
int j = 0;
for (; j < size; j++) {
byte value = (byte) random.nextInt(0, (int) Byte.MAX_VALUE + 1);
// turn any found value into something different
if (j < foundIndex) {
if (AsciiStringUtil.isUpperCase(value)) {
value = AsciiStringUtil.toLowerCase(value);
}
}
if (j == foundIndex) {
value = 'N';
}
byteArray[j] = value;
}
asciiStringData[i] = new AsciiString(byteArray, false);
stringData[i] = asciiStringData[i].toString();
}
}
private AsciiString getData() {
return asciiStringData[i++ & permutations - 1];
}
private String getStringData() {
return stringData[i++ & permutations - 1];
}
@Benchmark
public AsciiString toLowerCase() {
return getData().toLowerCase();
}
@Benchmark
public AsciiString toUpperCase() {
return getData().toUpperCase();
}
@Benchmark
public String stringToLowerCase() {
return getStringData().toLowerCase();
}
@Benchmark
public String stringtoUpperCase() {
return getStringData().toUpperCase();
}
}
| netty/netty | microbench/src/main/java/io/netty/util/AsciiStringCaseConversionBenchmark.java |
2,753 | /* ###
* IP: GHIDRA
*
* 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 resources.icons;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.*;
import java.net.URL;
import java.util.Objects;
import javax.accessibility.AccessibleContext;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import generic.util.image.ImageUtils;
import ghidra.util.Msg;
import resources.ResourceManager;
/**
* <code>ImageIconWrapper</code> provides the ability to instantiate
* an ImageIcon with delayed loading. In addition to delayed loading
* it has the added benefit of allowing the use of static initialization
* of ImageIcons without starting the Swing thread which can cause
* problems when running headless.
*
* @deprecated This class has been replaced by a series of classes that extend
* {@link LazyImageIcon}: {@link UrlImageIcon}, {@link DerivedImageIcon}, {@link BytesImageIcon},
* {@link DisabledImageIcon}, and {@link ScaledImageIcon}. Pick the one that matches
* the constructor that was being used to create an ImageIconWrapper
*/
@Deprecated(forRemoval = true, since = "11")
public class ImageIconWrapper extends ImageIcon implements FileBasedIcon {
private boolean loaded;
private ImageIcon imageIcon;
private Image image;
private Image baseImage;
private Icon baseIcon;
private byte[] imageBytes;
private URL imageURL;
private String imageName; // lazy load
/**
* Construct wrapped ImageIcon based upon specified image byte array
* (see {@link Toolkit#createImage(byte[])})
* @param imageBytes image bytes
* @param imageName image reference name
*/
public ImageIconWrapper(byte[] imageBytes, String imageName) {
this.imageBytes = Objects.requireNonNull(imageBytes,
"Cannot create an ImageIconWrapper from a null bytes");
this.imageName = imageName;
if (imageBytes.length == 0) {
throw new IllegalArgumentException("Cannot create an image from 0 bytes");
}
}
/**
* Construct wrapped ImageIcon based upon specified image
* @param image icon image
* @param imageName image reference name
*/
public ImageIconWrapper(Image image, String imageName) {
Objects.requireNonNull(image, "Cannot create an ImageIconWrapper from a null image");
this.baseImage = image;
this.imageName = imageName;
}
/**
* Construct wrapped ImageIcon based upon specified icon
* which may require transformation into ImageIcon
* @param icon the icon
*/
public ImageIconWrapper(Icon icon) {
this.baseIcon =
Objects.requireNonNull(icon, "Cannot create an ImageIconWrapper from a null icon");
}
/**
* Construct wrapped ImageIcon based upon specified resource URL
* @param url icon image resource URL
*/
public ImageIconWrapper(URL url) {
Objects.requireNonNull(url, "Cannot create an ImageIconWrapper from a null URL");
imageURL = url;
imageName = imageURL.toExternalForm();
}
private synchronized void init() {
if (!loaded) {
loaded = true;
imageIcon = createImageIcon();
image = imageIcon.getImage();
super.setImage(image);
}
}
@Override
public String getFilename() {
return getImageName();
}
/**
* Get icon reference name
* @return icon name
*/
public String getImageName() {
if (imageName == null && baseIcon != null) {
imageName = ResourceManager.getIconName(baseIcon);
}
return imageName;
}
@Override
public Image getImage() {
init();
return image;
}
@Override
public AccessibleContext getAccessibleContext() {
init();
return imageIcon.getAccessibleContext();
}
@Override
public String getDescription() {
init();
return imageIcon.getDescription();
}
@Override
public int getIconHeight() {
init();
return imageIcon.getIconHeight();
}
@Override
public int getIconWidth() {
init();
return imageIcon.getIconWidth();
}
@Override
public int getImageLoadStatus() {
init();
return imageIcon.getImageLoadStatus();
}
@Override
public ImageObserver getImageObserver() {
init();
return imageIcon.getImageObserver();
}
@Override
public synchronized void paintIcon(Component c, Graphics g, int x, int y) {
init();
super.paintIcon(c, g, x, y);
}
@Override
public void setDescription(String description) {
init();
imageIcon.setDescription(description);
}
@Override
public void setImage(Image image) {
init();
this.image = image;
super.setImage(image);
}
@Override
public String toString() {
init();
return imageIcon.toString();
}
private byte[] loadBytesFromURL(URL url) {
try (InputStream is = url.openStream()) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
int length = 0;
byte[] buf = new byte[1024];
while ((length = is.read(buf)) > 0) {
os.write(buf, 0, length);
}
return os.toByteArray();
}
catch (IOException e) {
Msg.error(this, "Exception loading image bytes: " + url.toExternalForm(), e);
}
return null;
}
/**
* Get the base icon image to be transformed in ImageIcon
* @return the base icon image to be transformed in ImageIcon
*/
protected final Image createIconBaseImage() {
if (baseImage != null) {
return baseImage;
}
if (baseIcon != null) {
BufferedImage bufferedImage = new BufferedImage(baseIcon.getIconWidth(),
baseIcon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics graphics = bufferedImage.getGraphics();
baseIcon.paintIcon(null, graphics, 0, 0);
graphics.dispose();
return bufferedImage;
}
if (imageBytes == null || imageBytes.length == 0) {
imageBytes = loadBytesFromURL(imageURL);
if (imageBytes == null) {
return null;
}
}
return Toolkit.getDefaultToolkit().createImage(imageBytes);
}
protected ImageIcon createImageIcon() {
if (baseIcon instanceof ImageIcon) {
return (ImageIcon) baseIcon;
}
Image iconImage = createIconBaseImage();
if (iconImage == null) {
return getDefaultIcon();
}
String name = getImageName();
if (!ImageUtils.waitForImage(name, iconImage)) {
return getDefaultIcon(); // rather than returning null we will give a reasonable default
}
return new ImageIcon(iconImage, name);
}
private ImageIcon getDefaultIcon() {
ImageIcon defaultIcon = ResourceManager.getDefaultIcon();
if (this == defaultIcon) {
// this can happen under just the right conditions when loading the default
// icon's bytes fails (probably due to disk or network issues)
throw new IllegalStateException("Unexpected failure loading the default icon!");
}
return defaultIcon; // some sort of initialization has failed
}
}
| NationalSecurityAgency/ghidra | Ghidra/Framework/Gui/src/main/java/resources/icons/ImageIconWrapper.java |
2,754 | /* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2004-09 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package processing.app;
import static processing.app.I18n.tr;
import static processing.app.Theme.scale;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.print.PageFormat;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.TransferHandler;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import javax.swing.text.BadLocationException;
import org.fife.ui.rsyntaxtextarea.folding.FoldManager;
import com.jcraft.jsch.JSchException;
import cc.arduino.CompilerProgressListener;
import cc.arduino.packages.BoardPort;
import cc.arduino.packages.MonitorFactory;
import cc.arduino.packages.Uploader;
import cc.arduino.packages.uploaders.SerialUploader;
import cc.arduino.view.GoToLineNumber;
import cc.arduino.view.StubMenuListener;
import cc.arduino.view.findreplace.FindReplace;
import jssc.SerialPortException;
import processing.app.debug.RunnerException;
import processing.app.forms.PasswordAuthorizationDialog;
import processing.app.helpers.DocumentTextChangeListener;
import processing.app.helpers.Keys;
import processing.app.helpers.OSUtils;
import processing.app.helpers.PreferencesMapException;
import processing.app.helpers.StringReplacer;
import processing.app.legacy.PApplet;
import processing.app.syntax.PdeKeywords;
import processing.app.syntax.SketchTextArea;
import processing.app.tools.MenuScroller;
import processing.app.tools.Tool;
/**
* Main editor panel for the Processing Development Environment.
*/
@SuppressWarnings("serial")
public class Editor extends JFrame implements RunnerListener {
public static final int MAX_TIME_AWAITING_FOR_RESUMING_SERIAL_MONITOR = 10000;
final Platform platform;
private JMenu recentSketchesMenu;
private JMenu programmersMenu;
private final Box upper;
private ArrayList<EditorTab> tabs = new ArrayList<>();
private int currentTabIndex = -1;
private static class ShouldSaveIfModified
implements Predicate<SketchController> {
@Override
public boolean test(SketchController controller) {
return PreferencesData.getBoolean("editor.save_on_verify")
&& controller.getSketch().isModified()
&& !controller.isReadOnly();
}
}
private static class CanExportInSketchFolder
implements Predicate<SketchController> {
@Override
public boolean test(SketchController controller) {
if (controller.isReadOnly()) {
return false;
}
if (controller.getSketch().isModified()) {
return PreferencesData.getBoolean("editor.save_on_verify");
}
return true;
}
}
final Base base;
// otherwise, if the window is resized with the message label
// set to blank, it's preferredSize() will be fukered
private static final String EMPTY =
" " +
" " +
" ";
/** Command on Mac OS X, Ctrl on Windows and Linux */
private static final int SHORTCUT_KEY_MASK =
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
/** Command-W on Mac OS X, Ctrl-W on Windows and Linux */
static final KeyStroke WINDOW_CLOSE_KEYSTROKE =
KeyStroke.getKeyStroke('W', SHORTCUT_KEY_MASK);
/** Command-Option on Mac OS X, Ctrl-Alt on Windows and Linux */
static final int SHORTCUT_ALT_KEY_MASK = ActionEvent.ALT_MASK |
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
/**
* true if this file has not yet been given a name by the user
*/
boolean untitled;
private PageFormat pageFormat;
// file, sketch, and tools menus for re-inserting items
private JMenu fileMenu;
private JMenu toolsMenu;
private int numTools = 0;
static public boolean avoidMultipleOperations = false;
private final EditorToolbar toolbar;
// these menus are shared so that they needn't be rebuilt for all windows
// each time a sketch is created, renamed, or moved.
static JMenu toolbarMenu;
static JMenu sketchbookMenu;
static JMenu examplesMenu;
static JMenu importMenu;
private static JMenu portMenu;
static volatile AbstractMonitor serialMonitor;
static AbstractMonitor serialPlotter;
final EditorHeader header;
EditorStatus status;
EditorConsole console;
private JSplitPane splitPane;
// currently opened program
SketchController sketchController;
Sketch sketch;
EditorLineStatus lineStatus;
//JEditorPane editorPane;
/** Contains all EditorTabs, of which only one will be visible */
private JPanel codePanel;
//Runner runtime;
private JMenuItem saveMenuItem;
private JMenuItem saveAsMenuItem;
//boolean presenting;
static private boolean uploading;
// undo fellers
private JMenuItem undoItem;
private JMenuItem redoItem;
private FindReplace find;
Runnable runHandler;
Runnable presentHandler;
private Runnable runAndSaveHandler;
private Runnable presentAndSaveHandler;
private UploadHandler uploadHandler;
private UploadHandler uploadUsingProgrammerHandler;
private Runnable timeoutUploadHandler;
private Map<String, Tool> internalToolCache = new HashMap<String, Tool>();
public Editor(Base ibase, File file, int[] storedLocation, int[] defaultLocation, Platform platform) throws Exception {
super("Arduino");
this.base = ibase;
this.platform = platform;
Base.setIcon(this);
// Install default actions for Run, Present, etc.
resetHandlers();
// add listener to handle window close box hit event
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
base.handleClose(Editor.this);
}
});
// don't close the window when clicked, the app will take care
// of that via the handleQuitInternal() methods
// http://dev.processing.org/bugs/show_bug.cgi?id=440
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
// When bringing a window to front, let the Base know
addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent e) {
base.handleActivated(Editor.this);
}
// added for 1.0.5
// http://dev.processing.org/bugs/show_bug.cgi?id=1260
public void windowDeactivated(WindowEvent e) {
List<Component> toolsMenuItemsToRemove = new LinkedList<>();
for (Component menuItem : toolsMenu.getMenuComponents()) {
if (menuItem instanceof JComponent) {
Object removeOnWindowDeactivation = ((JComponent) menuItem).getClientProperty("removeOnWindowDeactivation");
if (removeOnWindowDeactivation != null && Boolean.valueOf(removeOnWindowDeactivation.toString())) {
toolsMenuItemsToRemove.add(menuItem);
}
}
}
for (Component menuItem : toolsMenuItemsToRemove) {
toolsMenu.remove(menuItem);
}
toolsMenu.remove(portMenu);
}
});
//PdeKeywords keywords = new PdeKeywords();
//sketchbook = new Sketchbook(this);
buildMenuBar();
// For rev 0120, placing things inside a JPanel
Container contentPain = getContentPane();
contentPain.setLayout(new BorderLayout());
JPanel pane = new JPanel();
pane.setLayout(new BorderLayout());
contentPain.add(pane, BorderLayout.CENTER);
Box box = Box.createVerticalBox();
upper = Box.createVerticalBox();
if (toolbarMenu == null) {
toolbarMenu = new JMenu();
base.rebuildToolbarMenu(toolbarMenu);
}
toolbar = new EditorToolbar(this, toolbarMenu);
upper.add(toolbar);
header = new EditorHeader(this);
upper.add(header);
// assemble console panel, consisting of status area and the console itself
JPanel consolePanel = new JPanel();
consolePanel.setLayout(new BorderLayout());
status = new EditorStatus(this);
consolePanel.add(status, BorderLayout.NORTH);
console = new EditorConsole(base);
console.setName("console");
// windows puts an ugly border on this guy
console.setBorder(null);
consolePanel.add(console, BorderLayout.CENTER);
lineStatus = new EditorLineStatus();
consolePanel.add(lineStatus, BorderLayout.SOUTH);
codePanel = new JPanel(new BorderLayout());
upper.add(codePanel);
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, upper, consolePanel);
// repaint child panes while resizing
splitPane.setContinuousLayout(true);
// if window increases in size, give all of increase to
// the textarea in the uppper pane
splitPane.setResizeWeight(1D);
// to fix ugliness.. normally macosx java 1.3 puts an
// ugly white border around this object, so turn it off.
splitPane.setBorder(null);
// By default, the split pane binds Ctrl-Tab and Ctrl-Shift-Tab for changing
// focus. Since we do not use that, but want to use these shortcuts for
// switching tabs, remove the bindings from the split pane. This allows the
// events to bubble up and be handled by the EditorHeader.
Keys.killBinding(splitPane, Keys.ctrl(KeyEvent.VK_TAB));
Keys.killBinding(splitPane, Keys.ctrlShift(KeyEvent.VK_TAB));
splitPane.setDividerSize(scale(splitPane.getDividerSize()));
// the following changed from 600, 400 for netbooks
// http://code.google.com/p/arduino/issues/detail?id=52
splitPane.setMinimumSize(scale(new Dimension(600, 100)));
box.add(splitPane);
// hopefully these are no longer needed w/ swing
// (har har har.. that was wishful thinking)
// listener = new EditorListener(this, textarea);
pane.add(box);
pane.setTransferHandler(new FileDropHandler());
// Set the minimum size for the editor window
setMinimumSize(scale(new Dimension(
PreferencesData.getInteger("editor.window.width.min"),
PreferencesData.getInteger("editor.window.height.min"))));
// Bring back the general options for the editor
applyPreferences();
// Finish preparing Editor (formerly found in Base)
pack();
// Set the window bounds and the divider location before setting it visible
setPlacement(storedLocation, defaultLocation);
// Open the document that was passed in
boolean loaded = handleOpenInternal(file);
if (!loaded) sketchController = null;
// default the console output to the last opened editor
EditorConsole.setCurrentEditorConsole(console);
}
/**
* Handles files dragged & dropped from the desktop and into the editor
* window. Dragging files into the editor window is the same as using
* "Sketch → Add File" for each file.
*/
private class FileDropHandler extends TransferHandler {
public boolean canImport(JComponent dest, DataFlavor[] flavors) {
return true;
}
@SuppressWarnings("unchecked")
public boolean importData(JComponent src, Transferable transferable) {
int successful = 0;
try {
DataFlavor uriListFlavor =
new DataFlavor("text/uri-list;class=java.lang.String");
if (transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
List<File> list = (List<File>)
transferable.getTransferData(DataFlavor.javaFileListFlavor);
for (File file : list) {
if (sketchController.addFile(file)) {
successful++;
}
}
} else if (transferable.isDataFlavorSupported(uriListFlavor)) {
// Some platforms (Mac OS X and Linux, when this began) preferred
// this method of moving files.
String data = (String)transferable.getTransferData(uriListFlavor);
String[] pieces = PApplet.splitTokens(data, "\r\n");
for (String piece : pieces) {
if (piece.startsWith("#")) continue;
String path = null;
if (piece.startsWith("file:///")) {
path = piece.substring(7);
} else if (piece.startsWith("file:/")) {
path = piece.substring(5);
}
if (sketchController.addFile(new File(path))) {
successful++;
}
}
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
if (successful == 0) {
statusError(tr("No files were added to the sketch."));
} else if (successful == 1) {
statusNotice(tr("One file added to the sketch."));
} else {
statusNotice(I18n.format(tr("{0} files added to the sketch."), successful));
}
return true;
}
}
private void setPlacement(int[] storedLocation, int[] defaultLocation) {
if (storedLocation.length > 5 && storedLocation[5] != 0) {
setExtendedState(storedLocation[5]);
setPlacement(defaultLocation);
} else {
setPlacement(storedLocation);
}
}
private void setPlacement(int[] location) {
setBounds(location[0], location[1], location[2], location[3]);
if (location[4] != 0) {
splitPane.setDividerLocation(location[4]);
}
}
protected int[] getPlacement() {
int[] location = new int[6];
// Get the dimensions of the Frame
Rectangle bounds = getBounds();
location[0] = bounds.x;
location[1] = bounds.y;
location[2] = bounds.width;
location[3] = bounds.height;
// Get the current placement of the divider
location[4] = splitPane.getDividerLocation();
location[5] = getExtendedState() & MAXIMIZED_BOTH;
return location;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/**
* Read and apply new values from the preferences, either because
* the app is just starting up, or the user just finished messing
* with things in the Preferences window.
*/
public void applyPreferences() {
boolean external = PreferencesData.getBoolean("editor.external");
saveMenuItem.setEnabled(!external);
saveAsMenuItem.setEnabled(!external);
for (EditorTab tab: tabs) {
tab.applyPreferences();
}
console.applyPreferences();
if (serialMonitor != null) {
serialMonitor.applyPreferences();
}
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
private void buildMenuBar() {
JMenuBar menubar = new JMenuBar();
final JMenu fileMenu = buildFileMenu();
fileMenu.addMenuListener(new StubMenuListener() {
@Override
public void menuSelected(MenuEvent e) {
List<Component> components = Arrays.asList(fileMenu.getMenuComponents());
if (!components.contains(sketchbookMenu)) {
fileMenu.insert(sketchbookMenu, 3);
}
if (!components.contains(examplesMenu)) {
fileMenu.insert(examplesMenu, 4);
}
fileMenu.revalidate();
validate();
}
});
menubar.add(fileMenu);
menubar.add(buildEditMenu());
final JMenu sketchMenu = new JMenu(tr("Sketch"));
sketchMenu.setMnemonic(KeyEvent.VK_S);
sketchMenu.addMenuListener(new StubMenuListener() {
@Override
public void menuSelected(MenuEvent e) {
buildSketchMenu(sketchMenu);
sketchMenu.revalidate();
validate();
}
});
buildSketchMenu(sketchMenu);
menubar.add(sketchMenu);
final JMenu toolsMenu = buildToolsMenu();
toolsMenu.addMenuListener(new StubMenuListener() {
@Override
public void menuSelected(MenuEvent e) {
List<Component> components = Arrays.asList(toolsMenu.getMenuComponents());
int offset = 0;
for (JMenu menu : base.getBoardsCustomMenus()) {
if (!components.contains(menu)) {
toolsMenu.insert(menu, numTools + offset);
offset++;
}
}
if (!components.contains(portMenu)) {
toolsMenu.insert(portMenu, numTools + offset);
}
programmersMenu.removeAll();
base.getProgrammerMenus().forEach(programmersMenu::add);
toolsMenu.revalidate();
validate();
}
});
menubar.add(toolsMenu);
menubar.add(buildHelpMenu());
setJMenuBar(menubar);
}
private JMenu buildFileMenu() {
JMenuItem item;
fileMenu = new JMenu(tr("File"));
fileMenu.setMnemonic(KeyEvent.VK_F);
item = newJMenuItem(tr("New"), 'N');
item.addActionListener(event -> {
try {
base.handleNew();
} catch (Exception e1) {
e1.printStackTrace();
}
});
fileMenu.add(item);
item = Editor.newJMenuItem(tr("Open..."), 'O');
item.addActionListener(event -> {
try {
base.handleOpenPrompt();
} catch (Exception e1) {
e1.printStackTrace();
}
});
fileMenu.add(item);
base.rebuildRecentSketchesMenuItems();
recentSketchesMenu = new JMenu(tr("Open Recent"));
SwingUtilities.invokeLater(() -> rebuildRecentSketchesMenu());
fileMenu.add(recentSketchesMenu);
if (sketchbookMenu == null) {
sketchbookMenu = new JMenu(tr("Sketchbook"));
MenuScroller.setScrollerFor(sketchbookMenu);
base.rebuildSketchbookMenu(sketchbookMenu);
}
fileMenu.add(sketchbookMenu);
if (examplesMenu == null) {
examplesMenu = new JMenu(tr("Examples"));
MenuScroller.setScrollerFor(examplesMenu);
base.rebuildExamplesMenu(examplesMenu);
}
fileMenu.add(examplesMenu);
item = Editor.newJMenuItem(tr("Close"), 'W');
item.addActionListener(event -> base.handleClose(Editor.this));
fileMenu.add(item);
saveMenuItem = newJMenuItem(tr("Save"), 'S');
saveMenuItem.addActionListener(event -> handleSave(false));
fileMenu.add(saveMenuItem);
saveAsMenuItem = newJMenuItemShift(tr("Save As..."), 'S');
saveAsMenuItem.addActionListener(event -> handleSaveAs());
fileMenu.add(saveAsMenuItem);
fileMenu.addSeparator();
item = newJMenuItemShift(tr("Page Setup"), 'P');
item.addActionListener(event -> handlePageSetup());
fileMenu.add(item);
item = newJMenuItem(tr("Print"), 'P');
item.addActionListener(event -> handlePrint());
fileMenu.add(item);
// macosx already has its own preferences and quit menu
if (!OSUtils.hasMacOSStyleMenus()) {
fileMenu.addSeparator();
item = newJMenuItem(tr("Preferences"), ',');
item.addActionListener(event -> base.handlePrefs());
fileMenu.add(item);
fileMenu.addSeparator();
item = newJMenuItem(tr("Quit"), 'Q');
item.addActionListener(event -> base.handleQuit());
fileMenu.add(item);
}
return fileMenu;
}
public void rebuildRecentSketchesMenu() {
recentSketchesMenu.removeAll();
for (JMenuItem recentSketchMenuItem : base.getRecentSketchesMenuItems()) {
recentSketchesMenu.add(recentSketchMenuItem);
}
}
private void buildSketchMenu(JMenu sketchMenu) {
sketchMenu.removeAll();
JMenuItem item = newJMenuItem(tr("Verify/Compile"), 'R');
item.addActionListener(event -> handleRun(false, presentHandler, runHandler));
sketchMenu.add(item);
item = newJMenuItem(tr("Upload"), 'U');
item.addActionListener(event -> handleExport(false));
sketchMenu.add(item);
item = newJMenuItemShift(tr("Upload Using Programmer"), 'U');
item.addActionListener(event -> handleExport(true));
sketchMenu.add(item);
item = newJMenuItemAlt(tr("Export compiled Binary"), 'S');
item.addActionListener(event -> {
if (!(new CanExportInSketchFolder().test(sketchController))) {
System.out.println(tr("Export canceled, changes must first be saved."));
return;
}
handleRun(false, new CanExportInSketchFolder(), presentAndSaveHandler, runAndSaveHandler);
});
sketchMenu.add(item);
// item = new JMenuItem("Stop");
// item.addActionListener(event -> handleStop());
// sketchMenu.add(item);
sketchMenu.addSeparator();
item = newJMenuItem(tr("Show Sketch Folder"), 'K');
item.addActionListener(event -> Base.openFolder(sketch.getFolder()));
sketchMenu.add(item);
item.setEnabled(Base.openFolderAvailable());
if (importMenu == null) {
importMenu = new JMenu(tr("Include Library"));
MenuScroller.setScrollerFor(importMenu);
base.rebuildImportMenu(importMenu);
}
sketchMenu.add(importMenu);
item = new JMenuItem(tr("Add File..."));
item.addActionListener(event -> sketchController.handleAddFile());
sketchMenu.add(item);
}
private JMenu buildToolsMenu() {
toolsMenu = new JMenu(tr("Tools"));
toolsMenu.setMnemonic(KeyEvent.VK_T);
addInternalTools(toolsMenu);
JMenuItem item = newJMenuItemShift(tr("Manage Libraries..."), 'I');
item.addActionListener(e -> base.openLibraryManager("", ""));
toolsMenu.add(item);
item = newJMenuItemShift(tr("Serial Monitor"), 'M');
item.addActionListener(e -> handleSerial());
toolsMenu.add(item);
item = newJMenuItemShift(tr("Serial Plotter"), 'L');
item.addActionListener(e -> handlePlotter());
toolsMenu.add(item);
addTools(toolsMenu, BaseNoGui.getToolsFolder());
File sketchbookTools = new File(BaseNoGui.getSketchbookFolder(), "tools");
addTools(toolsMenu, sketchbookTools);
toolsMenu.addSeparator();
numTools = toolsMenu.getItemCount();
// XXX: DAM: these should probably be implemented using the Tools plugin
// API, if possible (i.e. if it supports custom actions, etc.)
base.getBoardsCustomMenus().stream().forEach(toolsMenu::add);
if (portMenu == null)
portMenu = new JMenu(tr("Port"));
populatePortMenu();
toolsMenu.add(portMenu);
MenuScroller.setScrollerFor(portMenu);
item = new JMenuItem(tr("Get Board Info"));
item.addActionListener(e -> handleBoardInfo());
toolsMenu.add(item);
toolsMenu.addSeparator();
base.rebuildProgrammerMenu();
programmersMenu = new JMenu(tr("Programmer"));
MenuScroller.setScrollerFor(programmersMenu);
base.getProgrammerMenus().stream().forEach(programmersMenu::add);
toolsMenu.add(programmersMenu);
item = new JMenuItem(tr("Burn Bootloader"));
item.addActionListener(e -> handleBurnBootloader());
toolsMenu.add(item);
toolsMenu.addMenuListener(new StubMenuListener() {
public JMenuItem getSelectedItemRecursive(JMenu menu) {
int count = menu.getItemCount();
for (int i=0; i < count; i++) {
JMenuItem item = menu.getItem(i);
if ((item instanceof JMenu))
item = getSelectedItemRecursive((JMenu)item);
if (item != null && item.isSelected())
return item;
}
return null;
}
public void menuSelected(MenuEvent e) {
//System.out.println("Tools menu selected.");
populatePortMenu();
for (Component c : toolsMenu.getMenuComponents()) {
if ((c instanceof JMenu) && c.isVisible()) {
JMenu menu = (JMenu)c;
String name = menu.getText();
if (name == null) continue;
String basename = name;
int index = name.indexOf(':');
if (index > 0) basename = name.substring(0, index);
JMenuItem item = getSelectedItemRecursive(menu);
String sel = item != null ? item.getText() : null;
if (sel == null) {
if (!name.equals(basename)) menu.setText(basename);
} else {
if (sel.length() > 50) sel = sel.substring(0, 50) + "...";
String newname = basename + ": \"" + sel + "\"";
if (!name.equals(newname)) menu.setText(newname);
}
}
}
}
});
return toolsMenu;
}
private void addTools(JMenu menu, File sourceFolder) {
if (sourceFolder == null)
return;
Map<String, JMenuItem> toolItems = new HashMap<>();
File[] folders = sourceFolder.listFiles(new FileFilter() {
public boolean accept(File folder) {
if (folder.isDirectory()) {
//System.out.println("checking " + folder);
File subfolder = new File(folder, "tool");
return subfolder.exists();
}
return false;
}
});
if (folders == null || folders.length == 0) {
return;
}
for (File folder : folders) {
File toolDirectory = new File(folder, "tool");
try {
// add dir to classpath for .classes
//urlList.add(toolDirectory.toURL());
// add .jar files to classpath
File[] archives = toolDirectory.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return (name.toLowerCase().endsWith(".jar") ||
name.toLowerCase().endsWith(".zip"));
}
});
URL[] urlList = new URL[archives.length];
for (int j = 0; j < urlList.length; j++) {
urlList[j] = archives[j].toURI().toURL();
}
URLClassLoader loader = new URLClassLoader(urlList);
String className = null;
for (File archive : archives) {
className = findClassInZipFile(folder.getName(), archive);
if (className != null) break;
}
/*
// Alternatively, could use manifest files with special attributes:
// http://java.sun.com/j2se/1.3/docs/guide/jar/jar.html
// Example code for loading from a manifest file:
// http://forums.sun.com/thread.jspa?messageID=3791501
File infoFile = new File(toolDirectory, "tool.txt");
if (!infoFile.exists()) continue;
String[] info = PApplet.loadStrings(infoFile);
//Main-Class: org.poo.shoe.AwesomerTool
//String className = folders[i].getName();
String className = null;
for (int k = 0; k < info.length; k++) {
if (info[k].startsWith(";")) continue;
String[] pieces = PApplet.splitTokens(info[k], ": ");
if (pieces.length == 2) {
if (pieces[0].equals("Main-Class")) {
className = pieces[1];
}
}
}
*/
// If no class name found, just move on.
if (className == null) continue;
Class<?> toolClass = Class.forName(className, true, loader);
final Tool tool = (Tool) toolClass.newInstance();
tool.init(Editor.this);
String title = tool.getMenuTitle();
JMenuItem item = new JMenuItem(title);
item.addActionListener(event -> {
SwingUtilities.invokeLater(tool);
//new Thread(tool).start();
});
//menu.add(item);
toolItems.put(title, item);
} catch (Exception e) {
e.printStackTrace();
}
}
ArrayList<String> toolList = new ArrayList<>(toolItems.keySet());
if (toolList.size() == 0) return;
menu.addSeparator();
Collections.sort(toolList);
for (String title : toolList) {
menu.add(toolItems.get(title));
}
}
private String findClassInZipFile(String base, File file) {
// Class file to search for
String classFileName = "/" + base + ".class";
ZipFile zipFile = null;
try {
zipFile = new ZipFile(file);
Enumeration<?> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
if (!entry.isDirectory()) {
String name = entry.getName();
//System.out.println("entry: " + name);
if (name.endsWith(classFileName)) {
//int slash = name.lastIndexOf('/');
//String packageName = (slash == -1) ? "" : name.substring(0, slash);
// Remove .class and convert slashes to periods.
return name.substring(0, name.length() - 6).replace('/', '.');
}
}
}
} catch (IOException e) {
//System.err.println("Ignoring " + filename + " (" + e.getMessage() + ")");
e.printStackTrace();
} finally {
if (zipFile != null) {
try {
zipFile.close();
} catch (IOException e) {
// noop
}
}
}
return null;
}
public void updateKeywords(PdeKeywords keywords) {
for (EditorTab tab : tabs)
tab.updateKeywords(keywords);
}
JMenuItem createToolMenuItem(String className) {
try {
final Tool tool = getOrCreateToolInstance(className);
JMenuItem item = new JMenuItem(tool.getMenuTitle());
tool.init(Editor.this);
item.addActionListener(event -> SwingUtilities.invokeLater(tool));
return item;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private Tool getOrCreateToolInstance(String className) {
Tool internalTool = internalToolCache.get(className);
if (internalTool == null) {
try {
Class<?> toolClass = Class.forName(className);
internalTool = (Tool) toolClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
return null;
}
internalToolCache.put(className, internalTool);
}
return internalTool;
}
private void addInternalTools(JMenu menu) {
JMenuItem item;
item = createToolMenuItem("cc.arduino.packages.formatter.AStyle");
if (item == null) {
throw new NullPointerException("Tool cc.arduino.packages.formatter.AStyle unavailable");
}
item.setName("menuToolsAutoFormat");
int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
item.setAccelerator(KeyStroke.getKeyStroke('T', modifiers));
menu.add(item);
//menu.add(createToolMenuItem("processing.app.tools.CreateFont"));
//menu.add(createToolMenuItem("processing.app.tools.ColorSelector"));
menu.add(createToolMenuItem("processing.app.tools.Archiver"));
menu.add(createToolMenuItem("processing.app.tools.FixEncoding"));
}
private void selectSerialPort(String name) {
if(portMenu == null) {
System.out.println(tr("serialMenu is null"));
return;
}
if (name == null) {
System.out.println(tr("name is null"));
return;
}
JCheckBoxMenuItem selection = null;
for (int i = 0; i < portMenu.getItemCount(); i++) {
JMenuItem menuItem = portMenu.getItem(i);
if (!(menuItem instanceof JCheckBoxMenuItem)) {
continue;
}
JCheckBoxMenuItem checkBoxMenuItem = ((JCheckBoxMenuItem) menuItem);
checkBoxMenuItem.setState(false);
if (name.equals(checkBoxMenuItem.getText())) selection = checkBoxMenuItem;
}
if (selection != null) selection.setState(true);
//System.out.println(item.getLabel());
BaseNoGui.selectSerialPort(name);
try {
boolean reopenMonitor = ((serialMonitor != null && serialMonitor.isVisible()) ||
serialPlotter != null && serialPlotter.isVisible());
if (serialMonitor != null) {
serialMonitor.close();
}
if (serialPlotter != null) {
serialPlotter.close();
}
if (reopenMonitor) {
handleSerial();
}
} catch (Exception e) {
// ignore
}
onBoardOrPortChange();
base.onBoardOrPortChange();
//System.out.println("set to " + get("serial.port"));
}
class BoardPortJCheckBoxMenuItem extends JCheckBoxMenuItem {
private BoardPort port;
public BoardPortJCheckBoxMenuItem(BoardPort port) {
super();
this.port = port;
setText(toString());
addActionListener(e -> {
selectSerialPort(port.getAddress());
base.onBoardOrPortChange();
});
}
@Override
public String toString() {
// This is required for serialPrompt()
String label = port.getLabel();
if (port.getBoardName() != null && !port.getBoardName().isEmpty()) {
label += " (" + port.getBoardName() + ")";
}
return label;
}
}
private void populatePortMenu() {
final List<String> PROTOCOLS_ORDER = Arrays.asList("serial", "network");
final List<String> PROTOCOLS_LABELS = Arrays.asList(tr("Serial ports"), tr("Network ports"));
portMenu.removeAll();
String selectedPort = PreferencesData.get("serial.port");
List<BoardPort> ports = Base.getDiscoveryManager().discovery();
ports = platform.filterPorts(ports, PreferencesData.getBoolean("serial.ports.showall"));
ports.stream() //
.filter(port -> port.getProtocolLabel() == null || port.getProtocolLabel().isEmpty())
.forEach(port -> {
int labelIdx = PROTOCOLS_ORDER.indexOf(port.getProtocol());
if (labelIdx != -1) {
port.setProtocolLabel(PROTOCOLS_LABELS.get(labelIdx));
} else {
port.setProtocolLabel(port.getProtocol());
}
});
Collections.sort(ports, (port1, port2) -> {
String pr1 = port1.getProtocol();
String pr2 = port2.getProtocol();
int prIdx1 = PROTOCOLS_ORDER.contains(pr1) ? PROTOCOLS_ORDER.indexOf(pr1) : 999;
int prIdx2 = PROTOCOLS_ORDER.contains(pr2) ? PROTOCOLS_ORDER.indexOf(pr2) : 999;
int r = prIdx1 - prIdx2;
if (r != 0)
return r;
r = port1.getProtocolLabel().compareTo(port2.getProtocolLabel());
if (r != 0)
return r;
return port1.getAddress().compareTo(port2.getAddress());
});
String lastProtocol = "";
String lastProtocolLabel = "";
for (BoardPort port : ports) {
if (!port.getProtocol().equals(lastProtocol) || !port.getProtocolLabel().equals(lastProtocolLabel)) {
if (!lastProtocol.isEmpty()) {
portMenu.addSeparator();
}
lastProtocol = port.getProtocol();
lastProtocolLabel = port.getProtocolLabel();
JMenuItem item = new JMenuItem(tr(lastProtocolLabel));
item.setEnabled(false);
portMenu.add(item);
}
String address = port.getAddress();
BoardPortJCheckBoxMenuItem item = new BoardPortJCheckBoxMenuItem(port);
item.setSelected(address.equals(selectedPort));
portMenu.add(item);
}
portMenu.setEnabled(portMenu.getMenuComponentCount() > 0);
}
private JMenu buildHelpMenu() {
JMenu menu = new JMenu(tr("Help"));
menu.setMnemonic(KeyEvent.VK_H);
JMenuItem item = new JMenuItem(tr("Getting Started"));
item.addActionListener(event -> Base.openURL("https://www.arduino.cc/en/Guide"));
menu.add(item);
item = new JMenuItem(tr("Environment"));
item.addActionListener(event -> Base.openURL("https://www.arduino.cc/en/Guide/Environment"));
menu.add(item);
item = new JMenuItem(tr("Troubleshooting"));
item.addActionListener(event -> Base.openURL("https://support.arduino.cc/hc/en-us"));
menu.add(item);
item = new JMenuItem(tr("Reference"));
item.addActionListener(event -> Base.openURL("https://www.arduino.cc/reference/en/"));
menu.add(item);
menu.addSeparator();
item = newJMenuItemShift(tr("Find in Reference"), 'F');
item.addActionListener(event -> handleFindReference(getCurrentTab().getCurrentKeyword()));
menu.add(item);
item = new JMenuItem(tr("Frequently Asked Questions"));
item.addActionListener(event -> Base.openURL("https://support.arduino.cc/hc/en-us"));
menu.add(item);
item = new JMenuItem(tr("Visit Arduino.cc"));
item.addActionListener(event -> Base.openURL("https://www.arduino.cc/"));
menu.add(item);
// macosx already has its own about menu
if (!OSUtils.hasMacOSStyleMenus()) {
menu.addSeparator();
item = new JMenuItem(tr("About Arduino"));
item.addActionListener(event -> base.handleAbout());
menu.add(item);
}
return menu;
}
private JMenu buildEditMenu() {
JMenu menu = new JMenu(tr("Edit"));
menu.setName("menuEdit");
menu.setMnemonic(KeyEvent.VK_E);
undoItem = newJMenuItem(tr("Undo"), 'Z');
undoItem.setName("menuEditUndo");
undoItem.addActionListener(event -> getCurrentTab().handleUndo());
menu.add(undoItem);
if (!OSUtils.isMacOS()) {
redoItem = newJMenuItem(tr("Redo"), 'Y');
} else {
redoItem = newJMenuItemShift(tr("Redo"), 'Z');
}
redoItem.setName("menuEditRedo");
redoItem.addActionListener(event -> getCurrentTab().handleRedo());
menu.add(redoItem);
menu.addSeparator();
JMenuItem cutItem = newJMenuItem(tr("Cut"), 'X');
cutItem.addActionListener(event -> getCurrentTab().handleCut());
menu.add(cutItem);
JMenuItem copyItem = newJMenuItem(tr("Copy"), 'C');
copyItem.addActionListener(event -> getCurrentTab().getTextArea().copy());
menu.add(copyItem);
JMenuItem copyForumItem = newJMenuItemShift(tr("Copy for Forum"), 'C');
copyForumItem.addActionListener(event -> getCurrentTab().handleDiscourseCopy());
menu.add(copyForumItem);
JMenuItem copyHTMLItem = newJMenuItemAlt(tr("Copy as HTML"), 'C');
copyHTMLItem.addActionListener(event -> getCurrentTab().handleHTMLCopy());
menu.add(copyHTMLItem);
JMenuItem pasteItem = newJMenuItem(tr("Paste"), 'V');
pasteItem.addActionListener(event -> getCurrentTab().handlePaste());
menu.add(pasteItem);
JMenuItem selectAllItem = newJMenuItem(tr("Select All"), 'A');
selectAllItem.addActionListener(event -> getCurrentTab().handleSelectAll());
menu.add(selectAllItem);
JMenuItem gotoLine = newJMenuItem(tr("Go to line..."), 'L');
gotoLine.addActionListener(event -> {
GoToLineNumber goToLineNumber = new GoToLineNumber(Editor.this);
goToLineNumber.setLocationRelativeTo(Editor.this);
goToLineNumber.setVisible(true);
});
menu.add(gotoLine);
menu.addSeparator();
JMenuItem commentItem = newJMenuItem(tr("Comment/Uncomment"), PreferencesData.get("editor.keys.shortcut_comment", "/").charAt(0));
commentItem.addActionListener(event -> getCurrentTab().handleCommentUncomment());
menu.add(commentItem);
JMenuItem increaseIndentItem = new JMenuItem(tr("Increase Indent"));
increaseIndentItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0));
increaseIndentItem.addActionListener(event -> getCurrentTab().handleIndentOutdent(true));
menu.add(increaseIndentItem);
JMenuItem decreseIndentItem = new JMenuItem(tr("Decrease Indent"));
decreseIndentItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.SHIFT_MASK));
decreseIndentItem.setName("menuDecreaseIndent");
decreseIndentItem.addActionListener(event -> getCurrentTab().handleIndentOutdent(false));
menu.add(decreseIndentItem);
menu.addSeparator();
JMenuItem increaseFontSizeItem = newJMenuItem(tr("Increase Font Size"), KeyEvent.VK_PLUS);
increaseFontSizeItem.addActionListener(event -> base.handleFontSizeChange(1));
menu.add(increaseFontSizeItem);
// Many keyboards have '+' and '=' on the same key. Allowing "CTRL +",
// "CTRL SHIFT +" and "CTRL =" covers the generally expected behavior.
KeyStroke ctrlShiftEq = KeyStroke.getKeyStroke(KeyEvent.VK_EQUALS, SHORTCUT_KEY_MASK | ActionEvent.SHIFT_MASK);
menu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ctrlShiftEq, "IncreaseFontSize");
KeyStroke ctrlEq = KeyStroke.getKeyStroke(KeyEvent.VK_EQUALS, SHORTCUT_KEY_MASK);
menu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ctrlEq, "IncreaseFontSize");
menu.getActionMap().put("IncreaseFontSize", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
base.handleFontSizeChange(1);
}
});
JMenuItem decreaseFontSizeItem = newJMenuItem(tr("Decrease Font Size"), KeyEvent.VK_MINUS);
decreaseFontSizeItem.addActionListener(event -> base.handleFontSizeChange(-1));
menu.add(decreaseFontSizeItem);
menu.addSeparator();
JMenuItem findItem = newJMenuItem(tr("Find..."), 'F');
findItem.addActionListener(event -> {
if (find == null) {
find = new FindReplace(Editor.this, Base.FIND_DIALOG_STATE);
}
if (!OSUtils.isMacOS()) {
find.setFindText(getCurrentTab().getSelectedText());
}
find.setLocationRelativeTo(Editor.this);
find.setVisible(true);
});
menu.add(findItem);
JMenuItem findNextItem = newJMenuItem(tr("Find Next"), 'G');
findNextItem.addActionListener(event -> {
if (find != null) {
find.findNext();
}
});
menu.add(findNextItem);
JMenuItem findPreviousItem = newJMenuItemShift(tr("Find Previous"), 'G');
findPreviousItem.addActionListener(event -> {
if (find != null) {
find.findPrevious();
}
});
menu.add(findPreviousItem);
if (OSUtils.isMacOS()) {
JMenuItem useSelectionForFindItem = newJMenuItem(tr("Use Selection For Find"), 'E');
useSelectionForFindItem.addActionListener(event -> {
if (find == null) {
find = new FindReplace(Editor.this, Base.FIND_DIALOG_STATE);
}
find.setFindText(getCurrentTab().getSelectedText());
});
menu.add(useSelectionForFindItem);
}
menu.addMenuListener(new MenuListener() {
@Override
public void menuSelected(MenuEvent e) {
boolean enabled = getCurrentTab().getSelectedText() != null;
cutItem.setEnabled(enabled);
copyItem.setEnabled(enabled);
}
@Override
public void menuDeselected(MenuEvent e) {}
@Override
public void menuCanceled(MenuEvent e) {}
});
return menu;
}
/**
* A software engineer, somewhere, needs to have his abstraction
* taken away. In some countries they jail or beat people for writing
* the sort of API that would require a five line helper function
* just to set the command key for a menu item.
*/
static public JMenuItem newJMenuItem(String title, int what) {
JMenuItem menuItem = new JMenuItem(title);
menuItem.setAccelerator(KeyStroke.getKeyStroke(what, SHORTCUT_KEY_MASK));
return menuItem;
}
/**
* Like newJMenuItem() but adds shift as a modifier for the key command.
*/
// Control + Shift + K seems to not be working on linux (Xubuntu 17.04, 2017-08-19)
static public JMenuItem newJMenuItemShift(String title, int what) {
JMenuItem menuItem = new JMenuItem(title);
menuItem.setAccelerator(KeyStroke.getKeyStroke(what, SHORTCUT_KEY_MASK | ActionEvent.SHIFT_MASK));
return menuItem;
}
/**
* Same as newJMenuItem(), but adds the ALT (on Linux and Windows)
* or OPTION (on Mac OS X) key as a modifier.
*/
private static JMenuItem newJMenuItemAlt(String title, int what) {
JMenuItem menuItem = new JMenuItem(title);
menuItem.setAccelerator(KeyStroke.getKeyStroke(what, SHORTCUT_ALT_KEY_MASK));
return menuItem;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
protected void updateUndoRedoState() {
SketchTextArea textArea = getCurrentTab().getTextArea();
undoItem.setEnabled(textArea.canUndo());
redoItem.setEnabled(textArea.canRedo());
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
// these will be done in a more generic way soon, more like:
// setHandler("action name", Runnable);
// but for the time being, working out the kinks of how many things to
// abstract from the editor in this fashion.
private void resetHandlers() {
runHandler = new BuildHandler();
presentHandler = new BuildHandler(true);
runAndSaveHandler = new BuildHandler(false, true);
presentAndSaveHandler = new BuildHandler(true, true);
uploadHandler = new UploadHandler();
uploadHandler.setUsingProgrammer(false);
uploadUsingProgrammerHandler = new UploadHandler();
uploadUsingProgrammerHandler.setUsingProgrammer(true);
timeoutUploadHandler = new TimeoutUploadHandler();
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/**
* Gets the current sketch controller.
*/
public SketchController getSketchController() {
return sketchController;
}
/**
* Gets the current sketch.
*/
public Sketch getSketch() {
return sketch;
}
/**
* Gets the currently displaying tab.
*/
public EditorTab getCurrentTab() {
return tabs.get(currentTabIndex);
}
/**
* Gets the index of the currently displaying tab.
*/
public int getCurrentTabIndex() {
return currentTabIndex;
}
/**
* Returns an (unmodifiable) list of currently opened tabs.
*/
public List<EditorTab> getTabs() {
return Collections.unmodifiableList(tabs);
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/**
* Change the currently displayed tab.
* Note that the GUI might not update immediately, since this needs
* to run in the Event dispatch thread.
* @param index The index of the tab to select
*/
public void selectTab(final int index) {
currentTabIndex = index;
updateUndoRedoState();
updateTitle();
header.rebuild();
getCurrentTab().activated();
// This must be run in the GUI thread
SwingUtilities.invokeLater(() -> {
codePanel.removeAll();
EditorTab selectedTab = tabs.get(index);
codePanel.add(selectedTab, BorderLayout.CENTER);
selectedTab.applyPreferences();
selectedTab.requestFocusInWindow(); // get the caret blinking
// For some reason, these are needed. Revalidate says it should be
// automatically called when components are added or removed, but without
// it, the component switched to is not displayed. repaint() is needed to
// clear the entire text area of any previous text.
codePanel.revalidate();
codePanel.repaint();
});
}
public void selectNextTab() {
selectTab((currentTabIndex + 1) % tabs.size());
}
public void selectPrevTab() {
selectTab((currentTabIndex - 1 + tabs.size()) % tabs.size());
}
public EditorTab findTab(final SketchFile file) {
return tabs.get(findTabIndex(file));
}
/**
* Finds the index of the tab showing the given file. Matches the file against
* EditorTab.getSketchFile() using ==.
*
* @returns The index of the tab for the given file, or -1 if no such tab was
* found.
*/
public int findTabIndex(final SketchFile file) {
for (int i = 0; i < tabs.size(); ++i) {
if (tabs.get(i).getSketchFile() == file)
return i;
}
return -1;
}
/**
* Finds the index of the tab showing the given file. Matches the file against
* EditorTab.getSketchFile().getFile() using equals.
*
* @returns The index of the tab for the given file, or -1 if no such tab was
* found.
*/
public int findTabIndex(final File file) {
for (int i = 0; i < tabs.size(); ++i) {
if (tabs.get(i).getSketchFile().getFile().equals(file))
return i;
}
return -1;
}
/**
* Create tabs for each of the current sketch's files, removing any existing
* tabs.
*/
public void createTabs() {
tabs.clear();
currentTabIndex = -1;
tabs.ensureCapacity(sketch.getCodeCount());
for (SketchFile file : sketch.getFiles()) {
try {
addTab(file, null);
} catch(IOException e) {
// TODO: Improve / move error handling
System.err.println(e);
}
}
selectTab(0);
}
/**
* Reorders tabs as per current sketch's files order
*/
public void reorderTabs() {
Collections.sort(tabs, (x, y) -> Sketch.CODE_DOCS_COMPARATOR.compare(x.getSketchFile(), y.getSketchFile()));
}
/**
* Add a new tab.
*
* @param file
* The file to show in the tab.
* @param contents
* The contents to show in the tab, or null to load the contents from
* the given file.
* @throws IOException
*/
protected void addTab(SketchFile file, String contents) throws IOException {
EditorTab tab = new EditorTab(this, file, contents);
tab.getTextArea().getDocument()
.addDocumentListener(new DocumentTextChangeListener(
() -> updateUndoRedoState()));
tabs.add(tab);
reorderTabs();
}
protected void removeTab(SketchFile file) throws IOException {
int index = findTabIndex(file);
tabs.remove(index);
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
void handleFindReference(String text) {
String referenceFile = base.getPdeKeywords().getReference(text);
String q;
if (referenceFile == null) {
q = text;
} else if (referenceFile.startsWith("Serial_")) {
q = referenceFile.substring(7);
} else {
q = referenceFile;
}
try {
Base.openURL("https://www.arduino.cc/search?tab=&q="
+ URLEncoder.encode(q, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/**
* Implements Sketch → Run.
* @param verbose Set true to run with verbose output.
* @param verboseHandler
* @param nonVerboseHandler
*/
public void handleRun(final boolean verbose, Runnable verboseHandler, Runnable nonVerboseHandler) {
handleRun(verbose, new ShouldSaveIfModified(), verboseHandler, nonVerboseHandler);
}
private void handleRun(final boolean verbose, Predicate<SketchController> shouldSavePredicate, Runnable verboseHandler, Runnable nonVerboseHandler) {
if (shouldSavePredicate.test(sketchController)) {
handleSave(true);
}
toolbar.activateRun();
status.progress(tr("Compiling sketch..."));
// do this to advance/clear the terminal window / dos prompt / etc
for (int i = 0; i < 10; i++) System.out.println();
// clear the console on each run, unless the user doesn't want to
if (PreferencesData.getBoolean("console.auto_clear")) {
console.clear();
}
// Cannot use invokeLater() here, otherwise it gets
// placed on the event thread and causes a hang--bad idea all around.
new Thread(verbose ? verboseHandler : nonVerboseHandler).start();
}
class BuildHandler implements Runnable {
private final boolean verbose;
private final boolean saveHex;
public BuildHandler() {
this(false);
}
public BuildHandler(boolean verbose) {
this(verbose, false);
}
public BuildHandler(boolean verbose, boolean saveHex) {
this.verbose = verbose;
this.saveHex = saveHex;
}
@Override
public void run() {
try {
removeAllLineHighlights();
sketchController.build(verbose, saveHex);
statusNotice(tr("Done compiling."));
} catch (PreferencesMapException e) {
statusError(I18n.format(
tr("Error while compiling: missing '{0}' configuration parameter"),
e.getMessage()));
} catch (Exception e) {
status.unprogress();
statusError(e);
}
status.unprogress();
toolbar.deactivateRun();
avoidMultipleOperations = false;
}
}
public void removeAllLineHighlights() {
for (EditorTab tab : tabs)
tab.getTextArea().removeAllLineHighlights();
}
public void addLineHighlight(int line) throws BadLocationException {
SketchTextArea textArea = getCurrentTab().getTextArea();
FoldManager foldManager = textArea.getFoldManager();
if (foldManager.isLineHidden(line)) {
for (int i = 0; i < foldManager.getFoldCount(); i++) {
if (foldManager.getFold(i).containsLine(line)) {
foldManager.getFold(i).setCollapsed(false);
}
}
}
textArea.addLineHighlight(line, new Color(1, 0, 0, 0.2f));
textArea.setCaretPosition(textArea.getLineStartOffset(line));
}
/**
* Implements Sketch → Stop, or pressing Stop on the toolbar.
*/
private void handleStop() { // called by menu or buttons
// toolbar.activate(EditorToolbar.STOP);
toolbar.deactivateRun();
// toolbar.deactivate(EditorToolbar.STOP);
// focus the PDE again after quitting presentation mode [toxi 030903]
toFront();
}
/**
* Check if the sketch is modified and ask user to save changes.
* @return false if canceling the close/quit operation
*/
protected boolean checkModified() {
if (!sketch.isModified())
return true;
// As of Processing 1.0.10, this always happens immediately.
// http://dev.processing.org/bugs/show_bug.cgi?id=1456
toFront();
String prompt = I18n.format(tr("Save changes to \"{0}\"? "),
sketch.getName());
if (!OSUtils.hasMacOSStyleMenus()) {
int result =
JOptionPane.showConfirmDialog(this, prompt, tr("Close"),
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
switch (result) {
case JOptionPane.YES_OPTION:
return handleSave(true);
case JOptionPane.NO_OPTION:
return true; // ok to continue
case JOptionPane.CANCEL_OPTION:
case JOptionPane.CLOSED_OPTION: // Escape key pressed
return false;
default:
throw new IllegalStateException();
}
} else {
// This code is disabled unless Java 1.5 is being used on Mac OS X
// because of a Java bug that prevents the initial value of the
// dialog from being set properly (at least on my MacBook Pro).
// The bug causes the "Don't Save" option to be the highlighted,
// blinking, default. This sucks. But I'll tell you what doesn't
// suck--workarounds for the Mac and Apple's snobby attitude about it!
// I think it's nifty that they treat their developers like dirt.
JOptionPane pane =
new JOptionPane(tr("<html> " +
"<head> <style type=\"text/css\">"+
"b { font: 13pt \"Lucida Grande\" }"+
"p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+
"</style> </head>" +
"<b>Do you want to save changes to this sketch<BR>" +
" before closing?</b>" +
"<p>If you don't save, your changes will be lost."),
JOptionPane.QUESTION_MESSAGE);
String[] options = new String[] {
tr("Save"), tr("Cancel"), tr("Don't Save")
};
pane.setOptions(options);
// highlight the safest option ala apple hig
pane.setInitialValue(options[0]);
JDialog dialog = pane.createDialog(this, null);
dialog.setVisible(true);
Object result = pane.getValue();
if (result == options[0]) { // save (and close/quit)
return handleSave(true);
} else {
return result == options[2];
}
}
}
/**
* Second stage of open, occurs after having checked to see if the
* modifications (if any) to the previous sketch need to be saved.
*/
protected boolean handleOpenInternal(File sketchFile) {
// check to make sure that this .pde file is
// in a folder of the same name
String fileName = sketchFile.getName();
File file = Sketch.checkSketchFile(sketchFile);
if (file == null) {
if (!fileName.endsWith(".ino") && !fileName.endsWith(".pde")) {
Base.showWarning(tr("Bad file selected"), tr("Arduino can only open its own sketches\n" +
"and other files ending in .ino or .pde"), null);
return false;
} else {
String properParent = fileName.substring(0, fileName.length() - 4);
Object[] options = {tr("OK"), tr("Cancel")};
String prompt = I18n.format(tr("The file \"{0}\" needs to be inside\n" +
"a sketch folder named \"{1}\".\n" +
"Create this folder, move the file, and continue?"),
fileName,
properParent);
int result = JOptionPane.showOptionDialog(this, prompt, tr("Moving"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
if (result != JOptionPane.YES_OPTION) {
return false;
}
// create properly named folder
File properFolder = new File(sketchFile.getParent(), properParent);
if (properFolder.exists()) {
Base.showWarning(tr("Error"), I18n.format(tr("A folder named \"{0}\" already exists. " +
"Can't open sketch."), properParent), null);
return false;
}
if (!properFolder.mkdirs()) {
//throw new IOException("Couldn't create sketch folder");
Base.showWarning(tr("Error"), tr("Could not create the sketch folder."), null);
return false;
}
// copy the sketch inside
File properPdeFile = new File(properFolder, sketchFile.getName());
try {
Base.copyFile(sketchFile, properPdeFile);
} catch (IOException e) {
Base.showWarning(tr("Error"), tr("Could not copy to a proper location."), e);
return false;
}
// remove the original file, so user doesn't get confused
sketchFile.delete();
// update with the new path
file = properPdeFile;
}
}
try {
sketch = new Sketch(file);
} catch (IOException e) {
Base.showWarning(tr("Error"), tr("Could not create the sketch."), e);
return false;
}
sketchController = new SketchController(this, sketch);
createTabs();
// Disable untitled setting from previous document, if any
untitled = false;
// opening was successful
return true;
}
public void updateTitle() {
if (sketchController == null) {
return;
}
SketchFile current = getCurrentTab().getSketchFile();
String customFormat = PreferencesData.get("editor.custom_title_format");
if (customFormat != null && !customFormat.trim().isEmpty()) {
Map<String, String> titleMap = new HashMap<String, String>();
titleMap.put("file", current.getFileName());
String path = sketch.getFolder().getAbsolutePath();
titleMap.put("folder", path);
titleMap.put("path", path);
titleMap.put("project", sketch.getName());
titleMap.put("version", BaseNoGui.VERSION_NAME_LONG);
setTitle(StringReplacer.replaceFromMapping(customFormat, titleMap));
} else {
if (current.isPrimary()) {
setTitle(I18n.format(tr("{0} | Arduino {1}"), sketch.getName(),
BaseNoGui.VERSION_NAME_LONG));
} else {
setTitle(I18n.format(tr("{0} - {1} | Arduino {2}"), sketch.getName(),
current.getFileName(), BaseNoGui.VERSION_NAME_LONG));
}
}
}
/**
* Actually handle the save command. If 'immediately' is set to false,
* this will happen in another thread so that the message area
* will update and the save button will stay highlighted while the
* save is happening. If 'immediately' is true, then it will happen
* immediately. This is used during a quit, because invokeLater()
* won't run properly while a quit is happening. This fixes
* <A HREF="http://dev.processing.org/bugs/show_bug.cgi?id=276">Bug 276</A>.
*/
public boolean handleSave(boolean immediately) {
//stopRunner();
handleStop(); // 0136
removeAllLineHighlights();
if (untitled) {
return handleSaveAs();
// need to get the name, user might also cancel here
} else if (immediately) {
return handleSave2();
} else {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
handleSave2();
}
});
}
return true;
}
private boolean handleSave2() {
toolbar.activateSave();
statusNotice(tr("Saving..."));
boolean saved = false;
try {
if (PreferencesData.getBoolean("editor.autoformat_currentfile_before_saving")) {
Tool formatTool = getOrCreateToolInstance("cc.arduino.packages.formatter.AStyle");
formatTool.run();
}
boolean wasReadOnly = sketchController.isReadOnly();
String previousMainFilePath = sketch.getMainFilePath();
saved = sketchController.save();
if (saved) {
statusNotice(tr("Done Saving."));
if (wasReadOnly) {
base.removeRecentSketchPath(previousMainFilePath);
}
base.storeRecentSketches(sketchController);
base.rebuildRecentSketchesMenuItems();
} else {
statusEmpty();
}
// rebuild sketch menu in case a save-as was forced
// Disabling this for 0125, instead rebuild the menu inside
// the Save As method of the Sketch object, since that's the
// only one who knows whether something was renamed.
//sketchbook.rebuildMenus();
//sketchbook.rebuildMenusAsync();
} catch (Exception e) {
// show the error as a message in the window
statusError(e);
// zero out the current action,
// so that checkModified2 will just do nothing
//checkModifiedMode = 0;
// this is used when another operation calls a save
}
//toolbar.clear();
toolbar.deactivateSave();
return saved;
}
public boolean handleSaveAs() {
//stopRunner(); // formerly from 0135
handleStop();
toolbar.activateSave();
//SwingUtilities.invokeLater(new Runnable() {
//public void run() {
statusNotice(tr("Saving..."));
try {
if (sketchController.saveAs()) {
base.storeRecentSketches(sketchController);
base.rebuildRecentSketchesMenuItems();
statusNotice(tr("Done Saving."));
// Disabling this for 0125, instead rebuild the menu inside
// the Save As method of the Sketch object, since that's the
// only one who knows whether something was renamed.
//sketchbook.rebuildMenusAsync();
} else {
statusNotice(tr("Save Canceled."));
return false;
}
} catch (Exception e) {
// show the error as a message in the window
statusError(e);
} finally {
// make sure the toolbar button deactivates
toolbar.deactivateSave();
// Update editor window title in case of "Save as..."
updateTitle();
header.rebuild();
}
return true;
}
private boolean serialPrompt() {
List<BoardPortJCheckBoxMenuItem> items = new ArrayList<>();
for (int i = 0; i < portMenu.getItemCount(); i++) {
if (portMenu.getItem(i) instanceof BoardPortJCheckBoxMenuItem)
items.add((BoardPortJCheckBoxMenuItem) portMenu.getItem(i));
}
String port = PreferencesData.get("serial.port");
String title;
if (port == null || port.isEmpty()) {
title = tr("Serial port not selected.");
} else {
title = I18n.format(tr("Serial port {0} not found."), port);
}
String question = tr("Retry the upload with another serial port?");
BoardPortJCheckBoxMenuItem result = (BoardPortJCheckBoxMenuItem) JOptionPane
.showInputDialog(this, title + "\n" + question, title,
JOptionPane.PLAIN_MESSAGE, null, items.toArray(), 0);
if (result == null)
return false;
result.doClick();
base.onBoardOrPortChange();
return true;
}
/**
* Called by Sketch → Export.
* Handles calling the export() function on sketch, and
* queues all the gui status stuff that comes along with it.
* <p/>
* Made synchronized to (hopefully) avoid problems of people
* hitting export twice, quickly, and horking things up.
*/
/**
* Handles calling the export() function on sketch, and
* queues all the gui status stuff that comes along with it.
*
* Made synchronized to (hopefully) avoid problems of people
* hitting export twice, quickly, and horking things up.
*/
synchronized public void handleExport(final boolean usingProgrammer) {
if (PreferencesData.getBoolean("editor.save_on_verify")) {
if (sketch.isModified() && !sketchController.isReadOnly()) {
handleSave(true);
}
}
toolbar.activateExport();
console.clear();
status.progress(tr("Uploading to I/O Board..."));
avoidMultipleOperations = true;
new Thread(timeoutUploadHandler).start();
new Thread(usingProgrammer ? uploadUsingProgrammerHandler : uploadHandler).start();
}
class UploadHandler implements Runnable {
boolean usingProgrammer = false;
public void setUsingProgrammer(boolean usingProgrammer) {
this.usingProgrammer = usingProgrammer;
}
public void run() {
try {
uploading = true;
removeAllLineHighlights();
if (serialMonitor != null) {
serialMonitor.suspend();
}
if (serialPlotter != null) {
serialPlotter.suspend();
}
boolean success = sketchController.exportApplet(usingProgrammer);
if (success) {
statusNotice(tr("Done uploading."));
}
} catch (SerialNotFoundException e) {
if (portMenu.getItemCount() == 0) {
statusError(tr("Serial port not selected."));
} else {
if (serialPrompt()) {
run();
} else {
statusNotice(tr("Upload canceled."));
}
}
} catch (PreferencesMapException e) {
statusError(I18n.format(
tr("Error while uploading: missing '{0}' configuration parameter"),
e.getMessage()));
} catch (RunnerException e) {
//statusError("Error during upload.");
//e.printStackTrace();
status.unprogress();
statusError(e);
} catch (Exception e) {
e.printStackTrace();
} finally {
populatePortMenu();
avoidMultipleOperations = false;
}
status.unprogress();
uploading = false;
//toolbar.clear();
toolbar.deactivateExport();
resumeOrCloseSerialMonitor();
resumeOrCloseSerialPlotter();
base.onBoardOrPortChange();
}
}
static public boolean isUploading() {
return uploading;
}
private void resumeOrCloseSerialMonitor() {
// Return the serial monitor window to its initial state
if (serialMonitor != null) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// noop
}
BoardPort boardPort = BaseNoGui.getDiscoveryManager().find(PreferencesData.get("serial.port"));
long sleptFor = 0;
while (boardPort == null && sleptFor < MAX_TIME_AWAITING_FOR_RESUMING_SERIAL_MONITOR) {
try {
Thread.sleep(100);
sleptFor += 100;
boardPort = BaseNoGui.getDiscoveryManager().find(PreferencesData.get("serial.port"));
} catch (InterruptedException e) {
// noop
}
}
try {
if (serialMonitor != null) {
serialMonitor.resume(boardPort);
if (boardPort == null) {
serialMonitor.close();
handleSerial();
} else {
serialMonitor.resume(boardPort);
}
}
} catch (Exception e) {
statusError(e);
}
}
}
private void resumeOrCloseSerialPlotter() {
// Return the serial plotter window to its initial state
if (serialPlotter != null) {
BoardPort boardPort = BaseNoGui.getDiscoveryManager().find(PreferencesData.get("serial.port"));
try {
if (serialPlotter != null)
serialPlotter.resume(boardPort);
if (boardPort == null) {
serialPlotter.close();
handlePlotter();
} else {
serialPlotter.resume(boardPort);
}
} catch (Exception e) {
statusError(e);
}
}
}
class TimeoutUploadHandler implements Runnable {
public void run() {
try {
//10 seconds, than reactivate upload functionality and let the programmer pid being killed
Thread.sleep(1000 * 10);
if (uploading) {
avoidMultipleOperations = false;
}
} catch (InterruptedException e) {
// noop
}
}
}
public void handleSerial() {
if(serialPlotter != null) {
if(serialPlotter.isClosed()) {
serialPlotter = null;
} else {
statusError(tr("Serial monitor not available while plotter is open"));
return;
}
}
if (serialMonitor != null) {
// The serial monitor already exists
if (serialMonitor.isClosed()) {
serialMonitor.dispose();
// If it's closed, clear the refrence to the existing
// monitor and create a new one
serialMonitor = null;
}
else {
// If it's not closed, give it the focus
try {
serialMonitor.toFront();
serialMonitor.requestFocus();
return;
} catch (Exception e) {
// noop
}
}
}
BoardPort port = Base.getDiscoveryManager().find(PreferencesData.get("serial.port"));
if (port == null) {
statusError(I18n.format(tr("Board at {0} is not available"), PreferencesData.get("serial.port")));
return;
}
serialMonitor = new MonitorFactory().newMonitor(port);
if (serialMonitor == null) {
String board = port.getPrefs().get("board");
String boardName = BaseNoGui.getPlatform().resolveDeviceByBoardID(BaseNoGui.packages, board);
statusError(I18n.format(tr("Serial monitor is not supported on network ports such as {0} for the {1} in this release"), PreferencesData.get("serial.port"), boardName));
return;
}
base.addEditorFontResizeListeners(serialMonitor);
Base.setIcon(serialMonitor);
// If currently uploading, disable the monitor (it will be later
// enabled when done uploading)
if (uploading || avoidMultipleOperations) {
try {
serialMonitor.suspend();
} catch (Exception e) {
statusError(e);
}
}
boolean success = false;
do {
if (serialMonitor.requiresAuthorization() && !PreferencesData.has(serialMonitor.getAuthorizationKey())) {
PasswordAuthorizationDialog dialog = new PasswordAuthorizationDialog(this, tr("Type board password to access its console"));
dialog.setLocationRelativeTo(this);
dialog.setVisible(true);
if (dialog.isCancelled()) {
statusNotice(tr("Unable to open serial monitor"));
return;
}
PreferencesData.set(serialMonitor.getAuthorizationKey(), dialog.getPassword());
}
try {
if (!avoidMultipleOperations) {
serialMonitor.open();
}
serialMonitor.setVisible(true);
success = true;
statusEmpty();
} catch (ConnectException e) {
statusError(tr("Unable to connect: is the sketch using the bridge?"));
} catch (JSchException e) {
statusError(tr("Unable to connect: wrong password?"));
} catch (SerialException e) {
String errorMessage = e.getMessage();
if (e.getCause() != null && e.getCause() instanceof SerialPortException) {
errorMessage += " (" + ((SerialPortException) e.getCause()).getExceptionType() + ")";
}
serialMonitor = null;
statusError(errorMessage);
try {
serialMonitor.close();
} catch (Exception e1) {
// noop
}
} catch (Exception e) {
statusError(e);
} finally {
if (serialMonitor != null && serialMonitor.requiresAuthorization() && !success) {
PreferencesData.remove(serialMonitor.getAuthorizationKey());
}
}
} while (serialMonitor != null && serialMonitor.requiresAuthorization() && !success);
}
public void handlePlotter() {
if(serialMonitor != null) {
if(serialMonitor.isClosed()) {
serialMonitor = null;
} else {
statusError(tr("Plotter not available while serial monitor is open"));
return;
}
}
if (serialPlotter != null) {
// The serial plotter already exists
if (serialPlotter.isClosed()) {
// If it's closed, clear the refrence to the existing
// plotter and create a new one
serialPlotter.dispose();
serialPlotter = null;
}
else {
// If it's not closed, give it the focus
try {
serialPlotter.toFront();
serialPlotter.requestFocus();
return;
} catch (Exception e) {
// noop
}
}
}
BoardPort port = Base.getDiscoveryManager().find(PreferencesData.get("serial.port"));
if (port == null) {
statusError(I18n.format(tr("Board at {0} is not available"), PreferencesData.get("serial.port")));
return;
}
serialPlotter = new SerialPlotter(port);
Base.setIcon(serialPlotter);
// If currently uploading, disable the plotter (it will be later
// enabled when done uploading)
if (uploading) {
try {
serialPlotter.suspend();
} catch (Exception e) {
statusError(e);
}
}
boolean success = false;
do {
if (serialPlotter.requiresAuthorization() && !PreferencesData.has(serialPlotter.getAuthorizationKey())) {
PasswordAuthorizationDialog dialog = new PasswordAuthorizationDialog(this, tr("Type board password to access its console"));
dialog.setLocationRelativeTo(this);
dialog.setVisible(true);
if (dialog.isCancelled()) {
statusNotice(tr("Unable to open serial plotter"));
return;
}
PreferencesData.set(serialPlotter.getAuthorizationKey(), dialog.getPassword());
}
try {
serialPlotter.open();
serialPlotter.setVisible(true);
success = true;
statusEmpty();
} catch (ConnectException e) {
statusError(tr("Unable to connect: is the sketch using the bridge?"));
} catch (JSchException e) {
statusError(tr("Unable to connect: wrong password?"));
} catch (SerialException e) {
String errorMessage = e.getMessage();
if (e.getCause() != null && e.getCause() instanceof SerialPortException) {
errorMessage += " (" + ((SerialPortException) e.getCause()).getExceptionType() + ")";
}
statusError(errorMessage);
serialPlotter = null;
} catch (Exception e) {
statusError(e);
} finally {
if (serialPlotter != null && serialPlotter.requiresAuthorization() && !success) {
PreferencesData.remove(serialPlotter.getAuthorizationKey());
}
}
} while (serialPlotter != null && serialPlotter.requiresAuthorization() && !success);
}
private void handleBurnBootloader() {
console.clear();
EditorConsole.setCurrentEditorConsole(this.console);
statusNotice(tr("Burning bootloader to I/O Board (this may take a minute)..."));
new Thread(() -> {
try {
Uploader uploader = new SerialUploader();
if (uploader.burnBootloader()) {
SwingUtilities.invokeLater(() -> statusNotice(tr("Done burning bootloader.")));
} else {
SwingUtilities.invokeLater(() -> statusError(tr("Error while burning bootloader.")));
// error message will already be visible
}
} catch (SerialNotFoundException e) {
SwingUtilities.invokeLater(() -> statusError(tr("Error while burning bootloader: please select a serial port.")));
} catch (PreferencesMapException e) {
SwingUtilities.invokeLater(() -> {
statusError(I18n.format(
tr("Error while burning bootloader: missing '{0}' configuration parameter"),
e.getMessage()));
});
} catch (RunnerException e) {
SwingUtilities.invokeLater(() -> statusError(e.getMessage()));
} catch (Exception e) {
SwingUtilities.invokeLater(() -> statusError(tr("Error while burning bootloader.")));
e.printStackTrace();
}
}).start();
}
private void handleBoardInfo() {
console.clear();
String selectedPort = PreferencesData.get("serial.port");
List<BoardPort> ports = Base.getDiscoveryManager().discovery();
String label = "";
String vid = "";
String pid = "";
String iserial = "";
String protocol = "";
boolean found = false;
for (BoardPort port : ports) {
if (port.getAddress().equals(selectedPort)) {
label = port.getBoardName();
vid = port.getPrefs().get("vid");
pid = port.getPrefs().get("pid");
iserial = port.getPrefs().get("iserial");
protocol = port.getProtocol();
found = true;
break;
}
}
if (!found) {
statusNotice(tr("Please select a port to obtain board info"));
return;
}
if (protocol.equals("network")) {
statusNotice(tr("Network port, can't obtain info"));
return;
}
if (vid == null || vid.equals("") || vid.equals("0000")) {
statusNotice(tr("Native serial port, can't obtain info"));
return;
}
if (iserial == null || iserial.equals("")) {
iserial = tr("Upload any sketch to obtain it");
}
if (label == null) {
label = tr("Unknown board");
}
String infos = I18n.format("BN: {0}\nVID: {1}\nPID: {2}\nSN: {3}", label, vid, pid, iserial);
JTextArea textArea = new JTextArea(infos);
JOptionPane.showMessageDialog(this, textArea, tr("Board Info"), JOptionPane.PLAIN_MESSAGE);
}
/**
* Handler for File → Page Setup.
*/
private void handlePageSetup() {
PrinterJob printerJob = PrinterJob.getPrinterJob();
if (pageFormat == null) {
pageFormat = printerJob.defaultPage();
}
pageFormat = printerJob.pageDialog(pageFormat);
}
/**
* Handler for File → Print.
*/
private void handlePrint() {
statusNotice(tr("Printing..."));
//printerJob = null;
PrinterJob printerJob = PrinterJob.getPrinterJob();
if (pageFormat != null) {
//System.out.println("setting page format " + pageFormat);
printerJob.setPrintable(getCurrentTab().getTextArea(), pageFormat);
} else {
printerJob.setPrintable(getCurrentTab().getTextArea());
}
// set the name of the job to the code name
printerJob.setJobName(getCurrentTab().getSketchFile().getPrettyName());
if (printerJob.printDialog()) {
try {
printerJob.print();
statusNotice(tr("Done printing."));
} catch (PrinterException pe) {
statusError(tr("Error while printing."));
pe.printStackTrace();
}
} else {
statusNotice(tr("Printing canceled."));
}
//printerJob = null; // clear this out?
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/**
* Show an error int the status bar.
*/
public void statusError(String what) {
System.err.println(what);
status.error(what);
//new Exception("deactivating RUN").printStackTrace();
toolbar.deactivateRun();
}
/**
* Show an exception in the editor status bar.
*/
public void statusError(Exception e) {
e.printStackTrace();
// if (e == null) {
// System.err.println("Editor.statusError() was passed a null exception.");
// return;
// }
if (e instanceof RunnerException) {
RunnerException re = (RunnerException) e;
if (re.hasCodeFile()) {
selectTab(findTabIndex(re.getCodeFile()));
}
if (re.hasCodeLine()) {
int line = re.getCodeLine();
// subtract one from the end so that the \n ain't included
if (line >= getCurrentTab().getTextArea().getLineCount()) {
// The error is at the end of this current chunk of code,
// so the last line needs to be selected.
line = getCurrentTab().getTextArea().getLineCount() - 1;
if (getCurrentTab().getLineText(line).length() == 0) {
// The last line may be zero length, meaning nothing to select.
// If so, back up one more line.
line--;
}
}
if (line < 0 || line >= getCurrentTab().getTextArea().getLineCount()) {
System.err.println(I18n.format(tr("Bad error line: {0}"), line));
} else {
try {
addLineHighlight(line);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
}
}
// Since this will catch all Exception types, spend some time figuring
// out which kind and try to give a better error message to the user.
String mess = e.getMessage();
if (mess != null) {
String javaLang = "java.lang.";
if (mess.indexOf(javaLang) == 0) {
mess = mess.substring(javaLang.length());
}
String rxString = "RuntimeException: ";
if (mess.indexOf(rxString) == 0) {
mess = mess.substring(rxString.length());
}
statusError(mess);
}
// e.printStackTrace();
}
/**
* Show a notice message in the editor status bar.
*/
public void statusNotice(String msg) {
status.notice(msg);
}
/**
* Clear the status area.
*/
private void statusEmpty() {
statusNotice(EMPTY);
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
protected void onBoardOrPortChange() {
lineStatus.updateBoardAndPort();
lineStatus.repaint();
}
public void addCompilerProgressListener(CompilerProgressListener listener){
this.status.addCompilerProgressListener(listener);
}
}
| cmaglie/Arduino | app/src/processing/app/Editor.java |
2,755 | /* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2004-11 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package processing.app;
import java.awt.*;
import java.io.*;
import java.util.*;
import processing.app.ui.Toolkit;
import processing.core.*;
/**
* Storage class for theme settings. This was separated from the Preferences
* class for 1.0 so that the coloring wouldn't conflict with previous releases
* and to make way for future ability to customize.
*/
public class Settings {
/**
* Copy of the defaults in case the user mangles a preference.
* It's necessary to keep a copy of the defaults around, because the user may
* have replaced a setting on their own. In the past, we used to load the
* defaults, then replace those with what was in the user's preferences file.
* Problem is, if something like a font entry in the user's file no longer
* parses properly, we need to be able to get back to a clean version of that
* setting so we can recover.
*/
HashMap<String,String> defaults;
/** Table of attributes/values. */
HashMap<String,String> table = new HashMap<String,String>();;
/** Associated file for this settings data. */
File file;
public Settings(File file) throws IOException {
this.file = file;
if (file.exists()) {
load();
}
// clone the hash table
defaults = (HashMap<String,String>) table.clone();
}
public void load() {
load(file);
}
public void load(File additions) {
String[] lines = PApplet.loadStrings(additions);
for (String line : lines) {
if ((line.length() == 0) ||
(line.charAt(0) == '#')) continue;
// this won't properly handle = signs being in the text
int equals = line.indexOf('=');
if (equals != -1) {
String key = line.substring(0, equals).trim();
String value = line.substring(equals + 1).trim();
table.put(key, value);
}
}
// check for platform-specific properties in the defaults
String platformExt = "." + Platform.getName();
int platformExtLength = platformExt.length();
for (String key : table.keySet()) {
if (key.endsWith(platformExt)) {
// this is a key specific to a particular platform
String actualKey = key.substring(0, key.length() - platformExtLength);
String value = get(key);
table.put(actualKey, value);
}
}
}
public void save() {
PrintWriter writer = PApplet.createWriter(file);
for (String key : table.keySet()) {
writer.println(key + "=" + table.get(key));
}
writer.flush();
writer.close();
}
public String get(String attribute) {
return table.get(attribute);
}
public String getDefault(String attribute) {
return defaults.get(attribute);
}
public void set(String attribute, String value) {
table.put(attribute, value);
}
public boolean getBoolean(String attribute) {
String value = get(attribute);
if (value == null) {
System.err.println("Boolean not found: " + attribute);
return false;
}
return Boolean.parseBoolean(value);
}
public void setBoolean(String attribute, boolean value) {
set(attribute, value ? "true" : "false");
}
public int getInteger(String attribute) {
String value = get(attribute);
if (value == null) {
System.err.println("Integer not found: " + attribute);
return 0;
}
return Integer.parseInt(value);
}
public void setInteger(String key, int value) {
set(key, String.valueOf(value));
}
public Color getColor(String attribute) {
Color parsed = null;
String s = get(attribute);
if ((s != null) && (s.indexOf("#") == 0)) {
try {
int v = Integer.parseInt(s.substring(1), 16);
parsed = new Color(v);
} catch (Exception e) {
}
}
return parsed;
}
public void setColor(String attr, Color what) {
set(attr, "#" + PApplet.hex(what.getRGB() & 0xffffff, 6));
}
// identical version found in Preferences.java
public Font getFont(String attr) {
try {
boolean replace = false;
String value = get(attr);
if (value == null) {
// use the default font instead
value = getDefault(attr);
replace = true;
}
String[] pieces = PApplet.split(value, ',');
if (pieces.length != 3) {
value = getDefault(attr);
pieces = PApplet.split(value, ',');
replace = true;
}
String name = pieces[0];
int style = Font.PLAIN; // equals zero
if (pieces[1].indexOf("bold") != -1) { //$NON-NLS-1$
style |= Font.BOLD;
}
if (pieces[1].indexOf("italic") != -1) { //$NON-NLS-1$
style |= Font.ITALIC;
}
int size = PApplet.parseInt(pieces[2], 12);
size = Toolkit.zoom(size);
// replace bad font with the default from lib/preferences.txt
if (replace) {
set(attr, value);
}
if (!name.startsWith("processing.")) {
return new Font(name, style, size);
} else {
if (pieces[0].equals("processing.sans")) {
return Toolkit.getSansFont(size, style);
} else if (pieces[0].equals("processing.mono")) {
return Toolkit.getMonoFont(size, style);
}
}
} catch (Exception e) {
// Adding try/catch block because this may be where
// a lot of startup crashes are happening.
Messages.log("Error with font " + get(attr) + " for attribute " + attr);
}
return new Font("Dialog", Font.PLAIN, 12);
}
} | processing/processing | app/src/processing/app/Settings.java |
2,756 | /*
* Scala (https://www.scala-lang.org)
*
* Copyright EPFL and Lightbend, Inc.
*
* Licensed under Apache License 2.0
* (http://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/
package scala.runtime;
public final class VolatileObjectRef<T> implements java.io.Serializable {
private static final long serialVersionUID = -9055728157600312291L;
volatile public T elem;
public VolatileObjectRef(T elem) { this.elem = elem; }
@Override
public String toString() { return String.valueOf(elem); }
public static <U> VolatileObjectRef<U> create(U e) { return new VolatileObjectRef<U>(e); }
public static VolatileObjectRef<Object> zero() { return new VolatileObjectRef<Object>(null); }
}
| scala/scala | src/library/scala/runtime/VolatileObjectRef.java |
2,757 | /*
* Scala (https://www.scala-lang.org)
*
* Copyright EPFL and Lightbend, Inc.
*
* Licensed under Apache License 2.0
* (http://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/
package scala.collection.concurrent;
final class Gen {}
| scala/scala | src/library/scala/collection/concurrent/Gen.java |
2,758 | /*
* Copyright 2018 The Netty Project
*
* The Netty Project licenses this file to you 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:
*
* https://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 io.netty.microbench.buffer;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.buffer.UnpooledUnsafeDirectByteBuf;
import io.netty.microbench.util.AbstractMicrobenchmark;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.TearDown;
import java.nio.ByteBuffer;
public class UnsafeByteBufBenchmark extends AbstractMicrobenchmark {
private ByteBuf unsafeBuffer;
private ByteBuffer byteBuffer;
@Setup
public void setup() {
unsafeBuffer = new UnpooledUnsafeDirectByteBuf(UnpooledByteBufAllocator.DEFAULT, 64, 64);
byteBuffer = ByteBuffer.allocateDirect(64);
}
@TearDown
public void tearDown() {
unsafeBuffer.release();
}
@Benchmark
public long setGetLongUnsafeByteBuf() {
return unsafeBuffer.setLong(0, 1).getLong(0);
}
@Benchmark
public long setGetLongByteBuffer() {
return byteBuffer.putLong(0, 1).getLong(0);
}
@Benchmark
public ByteBuf setLongUnsafeByteBuf() {
return unsafeBuffer.setLong(0, 1);
}
@Benchmark
public ByteBuffer setLongByteBuffer() {
return byteBuffer.putLong(0, 1);
}
}
| netty/netty | microbench/src/main/java/io/netty/microbench/buffer/UnsafeByteBufBenchmark.java |
2,760 | /*
* Scala (https://www.scala-lang.org)
*
* Copyright EPFL and Lightbend, Inc.
*
* Licensed under Apache License 2.0
* (http://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/
package scala.runtime;
public final class VolatileBooleanRef implements java.io.Serializable {
private static final long serialVersionUID = -5730524563015615974L;
volatile public boolean elem;
public VolatileBooleanRef(boolean elem) { this.elem = elem; }
public String toString() { return String.valueOf(elem); }
public static VolatileBooleanRef create(boolean e) { return new VolatileBooleanRef(e); }
public static VolatileBooleanRef zero() { return new VolatileBooleanRef(false); }
}
| scala/scala | src/library/scala/runtime/VolatileBooleanRef.java |
2,761 | /*
* Copyright 2020 The Netty Project
*
* The Netty Project licenses this file to you 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:
*
* https://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 io.netty.microbench.search;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.search.AbstractMultiSearchProcessorFactory;
import io.netty.buffer.search.AbstractSearchProcessorFactory;
import io.netty.buffer.search.SearchProcessor;
import io.netty.buffer.search.SearchProcessorFactory;
import io.netty.microbench.util.AbstractMicrobenchmark;
import io.netty.util.internal.ResourcesUtil;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.CompilerControl;
import org.openjdk.jmh.annotations.CompilerControl.Mode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.TearDown;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.TimeUnit;
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Warmup(iterations = 5)
@Measurement(iterations = 5)
@Fork(1)
public class SearchRealDataBenchmark extends AbstractMicrobenchmark {
public enum Algorithm {
AHO_CORASIC {
@Override
SearchProcessorFactory newFactory(byte[] needle) {
return AbstractMultiSearchProcessorFactory.newAhoCorasicSearchProcessorFactory(needle);
}
},
KMP {
@Override
SearchProcessorFactory newFactory(byte[] needle) {
return AbstractSearchProcessorFactory.newKmpSearchProcessorFactory(needle);
}
},
BITAP {
@Override
SearchProcessorFactory newFactory(byte[] needle) {
return AbstractSearchProcessorFactory.newBitapSearchProcessorFactory(needle);
}
};
abstract SearchProcessorFactory newFactory(byte[] needle);
}
@Param
public Algorithm algorithm;
@Param
public ByteBufType bufferType;
private ByteBuf haystack;
private SearchProcessorFactory[] searchProcessorFactories;
private SearchProcessorFactory searchProcessorFactory;
private static final byte[][] NEEDLES = {
"Thank You".getBytes(),
"* Does not exist *".getBytes(),
"<li>".getBytes(),
"<body>".getBytes(),
"</li>".getBytes(),
"github.com".getBytes(),
" Does not exist 2 ".getBytes(),
"</html>".getBytes(),
"\"https://".getBytes(),
"Netty 4.1.45.Final released".getBytes()
};
private int needleId, searchFrom, haystackLength;
@Setup
public void setup() throws IOException {
File haystackFile = ResourcesUtil.getFile(SearchRealDataBenchmark.class, "netty-io-news.html");
byte[] haystackBytes = readBytes(haystackFile);
haystack = bufferType.newBuffer(haystackBytes);
needleId = 0;
searchFrom = 0;
haystackLength = haystack.readableBytes();
searchProcessorFactories = new SearchProcessorFactory[NEEDLES.length];
for (int i = 0; i < NEEDLES.length; i++) {
searchProcessorFactories[i] = algorithm.newFactory(NEEDLES[i]);
}
}
@Setup(Level.Invocation)
public void invocationSetup() {
needleId = (needleId + 1) % searchProcessorFactories.length;
searchProcessorFactory = searchProcessorFactories[needleId];
}
@TearDown
public void teardown() {
haystack.release();
}
@Benchmark
@CompilerControl(Mode.DONT_INLINE)
public int findFirst() {
return haystack.forEachByte(searchProcessorFactory.newSearchProcessor());
}
@Benchmark
@CompilerControl(Mode.DONT_INLINE)
public int findFirstFromIndex() {
searchFrom = (searchFrom + 100) % haystackLength;
return haystack.forEachByte(
searchFrom, haystackLength - searchFrom, searchProcessorFactory.newSearchProcessor());
}
@Benchmark
@CompilerControl(Mode.DONT_INLINE)
public void findAll(Blackhole blackHole) {
SearchProcessor searchProcessor = searchProcessorFactory.newSearchProcessor();
int pos = 0;
do {
pos = haystack.forEachByte(pos, haystackLength - pos, searchProcessor) + 1;
blackHole.consume(pos);
} while (pos > 0);
}
private static byte[] readBytes(File file) throws IOException {
InputStream in = new FileInputStream(file);
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
byte[] buf = new byte[8192];
for (;;) {
int ret = in.read(buf);
if (ret < 0) {
break;
}
out.write(buf, 0, ret);
}
return out.toByteArray();
} finally {
safeClose(out);
}
} finally {
safeClose(in);
}
}
private static void safeClose(InputStream in) {
try {
in.close();
} catch (IOException ignored) { }
}
private static void safeClose(OutputStream out) {
try {
out.close();
} catch (IOException ignored) { }
}
}
| netty/netty | microbench/src/main/java/io/netty/microbench/search/SearchRealDataBenchmark.java |
2,762 | /*
* Copyright (C) 2012 The Guava Authors
*
* 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 com.google.common.testing;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Throwables.throwIfUnchecked;
import static com.google.common.testing.NullPointerTester.isNullable;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.MutableClassToInstanceMap;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
import com.google.common.primitives.Ints;
import com.google.common.reflect.Invokable;
import com.google.common.reflect.Parameter;
import com.google.common.reflect.Reflection;
import com.google.common.reflect.TypeToken;
import com.google.common.testing.NullPointerTester.Visibility;
import com.google.common.testing.RelationshipTester.Item;
import com.google.common.testing.RelationshipTester.ItemReporter;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.CheckForNull;
import junit.framework.Assert;
import junit.framework.AssertionFailedError;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tester that runs automated sanity tests for any given class. A typical use case is to test static
* factory classes like:
*
* <pre>
* interface Book {...}
* public class Books {
* public static Book hardcover(String title) {...}
* public static Book paperback(String title) {...}
* }
* </pre>
*
* <p>And all the created {@code Book} instances can be tested with:
*
* <pre>
* new ClassSanityTester()
* .forAllPublicStaticMethods(Books.class)
* .thatReturn(Book.class)
* .testEquals(); // or testNulls(), testSerializable() etc.
* </pre>
*
* @author Ben Yu
* @since 14.0
*/
@GwtIncompatible
@J2ktIncompatible
public final class ClassSanityTester {
private static final Ordering<Invokable<?, ?>> BY_METHOD_NAME =
new Ordering<Invokable<?, ?>>() {
@Override
public int compare(Invokable<?, ?> left, Invokable<?, ?> right) {
return left.getName().compareTo(right.getName());
}
};
private static final Ordering<Invokable<?, ?>> BY_PARAMETERS =
new Ordering<Invokable<?, ?>>() {
@Override
public int compare(Invokable<?, ?> left, Invokable<?, ?> right) {
return Ordering.usingToString().compare(left.getParameters(), right.getParameters());
}
};
private static final Ordering<Invokable<?, ?>> BY_NUMBER_OF_PARAMETERS =
new Ordering<Invokable<?, ?>>() {
@Override
public int compare(Invokable<?, ?> left, Invokable<?, ?> right) {
return Ints.compare(left.getParameters().size(), right.getParameters().size());
}
};
private final MutableClassToInstanceMap<Object> defaultValues =
MutableClassToInstanceMap.create();
private final ListMultimap<Class<?>, Object> distinctValues = ArrayListMultimap.create();
private final NullPointerTester nullPointerTester = new NullPointerTester();
public ClassSanityTester() {
// TODO(benyu): bake these into ArbitraryInstances.
setDefault(byte.class, (byte) 1);
setDefault(Byte.class, (byte) 1);
setDefault(short.class, (short) 1);
setDefault(Short.class, (short) 1);
setDefault(int.class, 1);
setDefault(Integer.class, 1);
setDefault(long.class, 1L);
setDefault(Long.class, 1L);
setDefault(float.class, 1F);
setDefault(Float.class, 1F);
setDefault(double.class, 1D);
setDefault(Double.class, 1D);
setDefault(Class.class, Class.class);
}
/**
* Sets the default value for {@code type}. The default value isn't used in testing {@link
* Object#equals} because more than one sample instances are needed for testing inequality. To set
* distinct values for equality testing, use {@link #setDistinctValues} instead.
*/
@CanIgnoreReturnValue
public <T> ClassSanityTester setDefault(Class<T> type, T value) {
nullPointerTester.setDefault(type, value);
defaultValues.putInstance(type, value);
return this;
}
/**
* Sets distinct values for {@code type}, so that when a class {@code Foo} is tested for {@link
* Object#equals} and {@link Object#hashCode}, and its construction requires a parameter of {@code
* type}, the distinct values of {@code type} can be passed as parameters to create {@code Foo}
* instances that are unequal.
*
* <p>Calling {@code setDistinctValues(type, v1, v2)} also sets the default value for {@code type}
* that's used for {@link #testNulls}.
*
* <p>Only necessary for types where {@link ClassSanityTester} doesn't already know how to create
* distinct values.
*
* @return this tester instance
* @since 17.0
*/
@CanIgnoreReturnValue
public <T> ClassSanityTester setDistinctValues(Class<T> type, T value1, T value2) {
checkNotNull(type);
checkNotNull(value1);
checkNotNull(value2);
checkArgument(!Objects.equal(value1, value2), "Duplicate value provided.");
distinctValues.replaceValues(type, ImmutableList.of(value1, value2));
setDefault(type, value1);
return this;
}
/**
* Tests that {@code cls} properly checks null on all constructor and method parameters that
* aren't annotated nullable (according to the rules of {@link NullPointerTester}). In details:
*
* <ul>
* <li>All non-private static methods are checked such that passing null for any parameter
* that's not annotated nullable should throw {@link NullPointerException}.
* <li>If there is any non-private constructor or non-private static factory method declared by
* {@code cls}, all non-private instance methods will be checked too using the instance
* created by invoking the constructor or static factory method.
* <li>If there is any non-private constructor or non-private static factory method declared by
* {@code cls}:
* <ul>
* <li>Test will fail if default value for a parameter cannot be determined.
* <li>Test will fail if the factory method returns null so testing instance methods is
* impossible.
* <li>Test will fail if the constructor or factory method throws exception.
* </ul>
* <li>If there is no non-private constructor or non-private static factory method declared by
* {@code cls}, instance methods are skipped for nulls test.
* <li>Nulls test is not performed on method return values unless the method is a non-private
* static factory method whose return type is {@code cls} or {@code cls}'s subtype.
* </ul>
*/
public void testNulls(Class<?> cls) {
try {
doTestNulls(cls, Visibility.PACKAGE);
} catch (Exception e) {
throwIfUnchecked(e);
throw new RuntimeException(e);
}
}
void doTestNulls(Class<?> cls, Visibility visibility)
throws ParameterNotInstantiableException, IllegalAccessException, InvocationTargetException,
FactoryMethodReturnsNullException {
if (!Modifier.isAbstract(cls.getModifiers())) {
nullPointerTester.testConstructors(cls, visibility);
}
nullPointerTester.testStaticMethods(cls, visibility);
if (hasInstanceMethodToTestNulls(cls, visibility)) {
Object instance = instantiate(cls);
if (instance != null) {
nullPointerTester.testInstanceMethods(instance, visibility);
}
}
}
private boolean hasInstanceMethodToTestNulls(Class<?> c, Visibility visibility) {
for (Method method : nullPointerTester.getInstanceMethodsToTest(c, visibility)) {
for (Parameter param : Invokable.from(method).getParameters()) {
if (!NullPointerTester.isPrimitiveOrNullable(param)) {
return true;
}
}
}
return false;
}
/**
* Tests the {@link Object#equals} and {@link Object#hashCode} of {@code cls}. In details:
*
* <ul>
* <li>The non-private constructor or non-private static factory method with the most parameters
* is used to construct the sample instances. In case of tie, the candidate constructors or
* factories are tried one after another until one can be used to construct sample
* instances.
* <li>For the constructor or static factory method used to construct instances, it's checked
* that when equal parameters are passed, the result instance should also be equal; and vice
* versa.
* <li>If a non-private constructor or non-private static factory method exists:
* <ul>
* <li>Test will fail if default value for a parameter cannot be determined.
* <li>Test will fail if the factory method returns null so testing instance methods is
* impossible.
* <li>Test will fail if the constructor or factory method throws exception.
* </ul>
* <li>If there is no non-private constructor or non-private static factory method declared by
* {@code cls}, no test is performed.
* <li>Equality test is not performed on method return values unless the method is a non-private
* static factory method whose return type is {@code cls} or {@code cls}'s subtype.
* <li>Inequality check is not performed against state mutation methods such as {@link
* List#add}, or functional update methods such as {@link
* com.google.common.base.Joiner#skipNulls}.
* </ul>
*
* <p>Note that constructors taking a builder object cannot be tested effectively because
* semantics of builder can be arbitrarily complex. Still, a factory class can be created in the
* test to facilitate equality testing. For example:
*
* <pre>
* public class FooTest {
*
* private static class FooFactoryForTest {
* public static Foo create(String a, String b, int c, boolean d) {
* return Foo.builder()
* .setA(a)
* .setB(b)
* .setC(c)
* .setD(d)
* .build();
* }
* }
*
* public void testEquals() {
* new ClassSanityTester()
* .forAllPublicStaticMethods(FooFactoryForTest.class)
* .thatReturn(Foo.class)
* .testEquals();
* }
* }
* </pre>
*
* <p>It will test that Foo objects created by the {@code create(a, b, c, d)} factory method with
* equal parameters are equal and vice versa, thus indirectly tests the builder equality.
*/
public void testEquals(Class<?> cls) {
try {
doTestEquals(cls);
} catch (Exception e) {
throwIfUnchecked(e);
throw new RuntimeException(e);
}
}
void doTestEquals(Class<?> cls)
throws ParameterNotInstantiableException, ParameterHasNoDistinctValueException,
IllegalAccessException, InvocationTargetException, FactoryMethodReturnsNullException {
if (cls.isEnum()) {
return;
}
List<? extends Invokable<?, ?>> factories = Lists.reverse(getFactories(TypeToken.of(cls)));
if (factories.isEmpty()) {
return;
}
int numberOfParameters = factories.get(0).getParameters().size();
List<ParameterNotInstantiableException> paramErrors = Lists.newArrayList();
List<ParameterHasNoDistinctValueException> distinctValueErrors = Lists.newArrayList();
List<InvocationTargetException> instantiationExceptions = Lists.newArrayList();
List<FactoryMethodReturnsNullException> nullErrors = Lists.newArrayList();
// Try factories with the greatest number of parameters.
for (Invokable<?, ?> factory : factories) {
if (factory.getParameters().size() == numberOfParameters) {
try {
testEqualsUsing(factory);
return;
} catch (ParameterNotInstantiableException e) {
paramErrors.add(e);
} catch (ParameterHasNoDistinctValueException e) {
distinctValueErrors.add(e);
} catch (InvocationTargetException e) {
instantiationExceptions.add(e);
} catch (FactoryMethodReturnsNullException e) {
nullErrors.add(e);
}
}
}
throwFirst(paramErrors);
throwFirst(distinctValueErrors);
throwFirst(instantiationExceptions);
throwFirst(nullErrors);
}
/**
* Instantiates {@code cls} by invoking one of its non-private constructors or non-private static
* factory methods with the parameters automatically provided using dummy values.
*
* @return The instantiated instance, or {@code null} if the class has no non-private constructor
* or factory method to be constructed.
*/
<T> @Nullable T instantiate(Class<T> cls)
throws ParameterNotInstantiableException,
IllegalAccessException,
InvocationTargetException,
FactoryMethodReturnsNullException {
if (cls.isEnum()) {
T[] constants = cls.getEnumConstants();
if (constants != null && constants.length > 0) {
return constants[0];
} else {
return null;
}
}
TypeToken<T> type = TypeToken.of(cls);
List<ParameterNotInstantiableException> paramErrors = Lists.newArrayList();
List<InvocationTargetException> instantiationExceptions = Lists.newArrayList();
List<FactoryMethodReturnsNullException> nullErrors = Lists.newArrayList();
for (Invokable<?, ? extends T> factory : getFactories(type)) {
T instance;
try {
instance = instantiate(factory);
} catch (ParameterNotInstantiableException e) {
paramErrors.add(e);
continue;
} catch (InvocationTargetException e) {
instantiationExceptions.add(e);
continue;
}
if (instance == null) {
nullErrors.add(new FactoryMethodReturnsNullException(factory));
} else {
return instance;
}
}
throwFirst(paramErrors);
throwFirst(instantiationExceptions);
throwFirst(nullErrors);
return null;
}
/**
* Instantiates using {@code factory}. If {@code factory} is annotated nullable and returns null,
* null will be returned.
*
* @throws ParameterNotInstantiableException if the static methods cannot be invoked because the
* default value of a parameter cannot be determined.
* @throws IllegalAccessException if the class isn't public or is nested inside a non-public
* class, preventing its methods from being accessible.
* @throws InvocationTargetException if a static method threw exception.
*/
private <T> @Nullable T instantiate(Invokable<?, ? extends T> factory)
throws ParameterNotInstantiableException, InvocationTargetException, IllegalAccessException {
return invoke(factory, getDummyArguments(factory));
}
/**
* Returns an object responsible for performing sanity tests against the return values of all
* public static methods declared by {@code cls}, excluding superclasses.
*/
public FactoryMethodReturnValueTester forAllPublicStaticMethods(Class<?> cls) {
ImmutableList.Builder<Invokable<?, ?>> builder = ImmutableList.builder();
for (Method method : cls.getDeclaredMethods()) {
Invokable<?, ?> invokable = Invokable.from(method);
invokable.setAccessible(true);
if (invokable.isPublic() && invokable.isStatic() && !invokable.isSynthetic()) {
builder.add(invokable);
}
}
return new FactoryMethodReturnValueTester(cls, builder.build(), "public static methods");
}
/** Runs sanity tests against return values of static factory methods declared by a class. */
public final class FactoryMethodReturnValueTester {
private final Set<String> packagesToTest = Sets.newHashSet();
private final Class<?> declaringClass;
private final ImmutableList<Invokable<?, ?>> factories;
private final String factoryMethodsDescription;
private Class<?> returnTypeToTest = Object.class;
private FactoryMethodReturnValueTester(
Class<?> declaringClass,
ImmutableList<Invokable<?, ?>> factories,
String factoryMethodsDescription) {
this.declaringClass = declaringClass;
this.factories = factories;
this.factoryMethodsDescription = factoryMethodsDescription;
packagesToTest.add(Reflection.getPackageName(declaringClass));
}
/**
* Specifies that only the methods that are declared to return {@code returnType} or its subtype
* are tested.
*
* @return this tester object
*/
@CanIgnoreReturnValue
public FactoryMethodReturnValueTester thatReturn(Class<?> returnType) {
this.returnTypeToTest = returnType;
return this;
}
/**
* Tests null checks against the instance methods of the return values, if any.
*
* <p>Test fails if default value cannot be determined for a constructor or factory method
* parameter, or if the constructor or factory method throws exception.
*
* @return this tester
*/
@CanIgnoreReturnValue
public FactoryMethodReturnValueTester testNulls() throws Exception {
for (Invokable<?, ?> factory : getFactoriesToTest()) {
Object instance = instantiate(factory);
if (instance != null
&& packagesToTest.contains(Reflection.getPackageName(instance.getClass()))) {
try {
nullPointerTester.testAllPublicInstanceMethods(instance);
} catch (AssertionError e) {
AssertionError error =
new AssertionFailedError("Null check failed on return value of " + factory);
error.initCause(e);
throw error;
}
}
}
return this;
}
/**
* Tests {@link Object#equals} and {@link Object#hashCode} against the return values of the
* static methods, by asserting that when equal parameters are passed to the same static method,
* the return value should also be equal; and vice versa.
*
* <p>Test fails if default value cannot be determined for a constructor or factory method
* parameter, or if the constructor or factory method throws exception.
*
* @return this tester
*/
@CanIgnoreReturnValue
public FactoryMethodReturnValueTester testEquals() throws Exception {
for (Invokable<?, ?> factory : getFactoriesToTest()) {
try {
testEqualsUsing(factory);
} catch (FactoryMethodReturnsNullException e) {
// If the factory returns null, we just skip it.
}
}
return this;
}
/**
* Runs serialization test on the return values of the static methods.
*
* <p>Test fails if default value cannot be determined for a constructor or factory method
* parameter, or if the constructor or factory method throws exception.
*
* @return this tester
*/
@CanIgnoreReturnValue
@SuppressWarnings("CatchingUnchecked") // sneaky checked exception
public FactoryMethodReturnValueTester testSerializable() throws Exception {
for (Invokable<?, ?> factory : getFactoriesToTest()) {
Object instance = instantiate(factory);
if (instance != null) {
try {
SerializableTester.reserialize(instance);
} catch (Exception e) { // sneaky checked exception
AssertionError error =
new AssertionFailedError("Serialization failed on return value of " + factory);
error.initCause(e.getCause());
throw error;
}
}
}
return this;
}
/**
* Runs equals and serialization test on the return values.
*
* <p>Test fails if default value cannot be determined for a constructor or factory method
* parameter, or if the constructor or factory method throws exception.
*
* @return this tester
*/
@CanIgnoreReturnValue
@SuppressWarnings("CatchingUnchecked") // sneaky checked exception
public FactoryMethodReturnValueTester testEqualsAndSerializable() throws Exception {
for (Invokable<?, ?> factory : getFactoriesToTest()) {
try {
testEqualsUsing(factory);
} catch (FactoryMethodReturnsNullException e) {
// If the factory returns null, we just skip it.
}
Object instance = instantiate(factory);
if (instance != null) {
try {
SerializableTester.reserializeAndAssert(instance);
} catch (Exception e) { // sneaky checked exception
AssertionError error =
new AssertionFailedError("Serialization failed on return value of " + factory);
error.initCause(e.getCause());
throw error;
} catch (AssertionFailedError e) {
AssertionError error =
new AssertionFailedError(
"Return value of " + factory + " reserialized to an unequal value");
error.initCause(e);
throw error;
}
}
}
return this;
}
private ImmutableList<Invokable<?, ?>> getFactoriesToTest() {
ImmutableList.Builder<Invokable<?, ?>> builder = ImmutableList.builder();
for (Invokable<?, ?> factory : factories) {
if (returnTypeToTest.isAssignableFrom(factory.getReturnType().getRawType())) {
builder.add(factory);
}
}
ImmutableList<Invokable<?, ?>> factoriesToTest = builder.build();
Assert.assertFalse(
"No "
+ factoryMethodsDescription
+ " that return "
+ returnTypeToTest.getName()
+ " or subtype are found in "
+ declaringClass
+ ".",
factoriesToTest.isEmpty());
return factoriesToTest;
}
}
private void testEqualsUsing(final Invokable<?, ?> factory)
throws ParameterNotInstantiableException, ParameterHasNoDistinctValueException,
IllegalAccessException, InvocationTargetException, FactoryMethodReturnsNullException {
List<Parameter> params = factory.getParameters();
List<FreshValueGenerator> argGenerators = Lists.newArrayListWithCapacity(params.size());
List<@Nullable Object> args = Lists.newArrayListWithCapacity(params.size());
for (Parameter param : params) {
FreshValueGenerator generator = newFreshValueGenerator();
argGenerators.add(generator);
args.add(generateDummyArg(param, generator));
}
Object instance = createInstance(factory, args);
List<Object> equalArgs = generateEqualFactoryArguments(factory, params, args);
// Each group is a List of items, each item has a list of factory args.
final List<List<List<Object>>> argGroups = Lists.newArrayList();
argGroups.add(ImmutableList.of(args, equalArgs));
EqualsTester tester =
new EqualsTester(
new ItemReporter() {
@Override
String reportItem(Item<?> item) {
List<Object> factoryArgs = argGroups.get(item.groupNumber).get(item.itemNumber);
return factory.getName()
+ "("
+ Joiner.on(", ").useForNull("null").join(factoryArgs)
+ ")";
}
});
tester.addEqualityGroup(instance, createInstance(factory, equalArgs));
for (int i = 0; i < params.size(); i++) {
List<Object> newArgs = Lists.newArrayList(args);
Object newArg = argGenerators.get(i).generateFresh(params.get(i).getType());
if (newArg == null || Objects.equal(args.get(i), newArg)) {
if (params.get(i).getType().getRawType().isEnum()) {
continue; // Nothing better we can do if it's single-value enum
}
throw new ParameterHasNoDistinctValueException(params.get(i));
}
newArgs.set(i, newArg);
tester.addEqualityGroup(createInstance(factory, newArgs));
argGroups.add(ImmutableList.of(newArgs));
}
tester.testEquals();
}
/**
* Returns dummy factory arguments that are equal to {@code args} but may be different instances,
* to be used to construct a second instance of the same equality group.
*/
private List<Object> generateEqualFactoryArguments(
Invokable<?, ?> factory, List<Parameter> params, List<Object> args)
throws ParameterNotInstantiableException, FactoryMethodReturnsNullException,
InvocationTargetException, IllegalAccessException {
List<Object> equalArgs = Lists.newArrayList(args);
for (int i = 0; i < args.size(); i++) {
Parameter param = params.get(i);
Object arg = args.get(i);
// Use new fresh value generator because 'args' were populated with new fresh generator each.
// Two newFreshValueGenerator() instances should normally generate equal value sequence.
Object shouldBeEqualArg = generateDummyArg(param, newFreshValueGenerator());
if (arg != shouldBeEqualArg
&& Objects.equal(arg, shouldBeEqualArg)
&& hashCodeInsensitiveToArgReference(factory, args, i, shouldBeEqualArg)
&& hashCodeInsensitiveToArgReference(
factory, args, i, generateDummyArg(param, newFreshValueGenerator()))) {
// If the implementation uses identityHashCode(), referential equality is
// probably intended. So no point in using an equal-but-different factory argument.
// We check twice to avoid confusion caused by accidental hash collision.
equalArgs.set(i, shouldBeEqualArg);
}
}
return equalArgs;
}
private static boolean hashCodeInsensitiveToArgReference(
Invokable<?, ?> factory, List<Object> args, int i, Object alternateArg)
throws FactoryMethodReturnsNullException, InvocationTargetException, IllegalAccessException {
List<Object> tentativeArgs = Lists.newArrayList(args);
tentativeArgs.set(i, alternateArg);
return createInstance(factory, tentativeArgs).hashCode()
== createInstance(factory, args).hashCode();
}
// distinctValues is a type-safe class-values mapping, but we don't have a type-safe data
// structure to hold the mappings.
@SuppressWarnings({"unchecked", "rawtypes"})
private FreshValueGenerator newFreshValueGenerator() {
FreshValueGenerator generator =
new FreshValueGenerator() {
@Override
@CheckForNull
Object interfaceMethodCalled(Class<?> interfaceType, Method method) {
return getDummyValue(TypeToken.of(interfaceType).method(method).getReturnType());
}
};
for (Entry<Class<?>, Collection<Object>> entry : distinctValues.asMap().entrySet()) {
generator.addSampleInstances((Class) entry.getKey(), entry.getValue());
}
return generator;
}
private static @Nullable Object generateDummyArg(Parameter param, FreshValueGenerator generator)
throws ParameterNotInstantiableException {
if (isNullable(param)) {
return null;
}
Object arg = generator.generateFresh(param.getType());
if (arg == null) {
throw new ParameterNotInstantiableException(param);
}
return arg;
}
private static <X extends Throwable> void throwFirst(List<X> exceptions) throws X {
if (!exceptions.isEmpty()) {
throw exceptions.get(0);
}
}
/** Factories with the least number of parameters are listed first. */
private static <T> ImmutableList<Invokable<?, ? extends T>> getFactories(TypeToken<T> type) {
List<Invokable<?, ? extends T>> factories = Lists.newArrayList();
for (Method method : type.getRawType().getDeclaredMethods()) {
Invokable<?, ?> invokable = type.method(method);
if (!invokable.isPrivate()
&& !invokable.isSynthetic()
&& invokable.isStatic()
&& type.isSupertypeOf(invokable.getReturnType())) {
@SuppressWarnings("unchecked") // guarded by isAssignableFrom()
Invokable<?, ? extends T> factory = (Invokable<?, ? extends T>) invokable;
factories.add(factory);
}
}
if (!Modifier.isAbstract(type.getRawType().getModifiers())) {
for (Constructor<?> constructor : type.getRawType().getDeclaredConstructors()) {
Invokable<T, T> invokable = type.constructor(constructor);
if (!invokable.isPrivate() && !invokable.isSynthetic()) {
factories.add(invokable);
}
}
}
for (Invokable<?, ?> factory : factories) {
factory.setAccessible(true);
}
// Sorts methods/constructors with the least number of parameters first since it's likely easier
// to fill dummy parameter values for them. Ties are broken by name then by the string form of
// the parameter list.
return BY_NUMBER_OF_PARAMETERS
.compound(BY_METHOD_NAME)
.compound(BY_PARAMETERS)
.immutableSortedCopy(factories);
}
private List<Object> getDummyArguments(Invokable<?, ?> invokable)
throws ParameterNotInstantiableException {
List<Object> args = Lists.newArrayList();
for (Parameter param : invokable.getParameters()) {
if (isNullable(param)) {
args.add(null);
continue;
}
Object defaultValue = getDummyValue(param.getType());
if (defaultValue == null) {
throw new ParameterNotInstantiableException(param);
}
args.add(defaultValue);
}
return args;
}
@CheckForNull
private <T> T getDummyValue(TypeToken<T> type) {
Class<? super T> rawType = type.getRawType();
@SuppressWarnings("unchecked") // Assume all default values are generics safe.
T defaultValue = (T) defaultValues.getInstance(rawType);
if (defaultValue != null) {
return defaultValue;
}
@SuppressWarnings("unchecked") // ArbitraryInstances always returns generics-safe dummies.
T value = (T) ArbitraryInstances.get(rawType);
if (value != null) {
return value;
}
if (rawType.isInterface()) {
return new SerializableDummyProxy(this).newProxy(type);
}
return null;
}
private static <T> T createInstance(Invokable<?, ? extends T> factory, List<?> args)
throws FactoryMethodReturnsNullException, InvocationTargetException, IllegalAccessException {
T instance = invoke(factory, args);
if (instance == null) {
throw new FactoryMethodReturnsNullException(factory);
}
return instance;
}
private static <T> @Nullable T invoke(Invokable<?, ? extends T> factory, List<?> args)
throws InvocationTargetException, IllegalAccessException {
T returnValue = factory.invoke(null, args.toArray());
if (returnValue == null) {
Assert.assertTrue(
factory + " returns null but it's not annotated with @Nullable", isNullable(factory));
}
return returnValue;
}
/**
* Thrown if the test tries to invoke a constructor or static factory method but failed because
* the dummy value of a constructor or method parameter is unknown.
*/
@VisibleForTesting
static class ParameterNotInstantiableException extends Exception {
public ParameterNotInstantiableException(Parameter parameter) {
super(
"Cannot determine value for parameter "
+ parameter
+ " of "
+ parameter.getDeclaringInvokable());
}
}
/**
* Thrown if the test fails to generate two distinct non-null values of a constructor or factory
* parameter in order to test {@link Object#equals} and {@link Object#hashCode} of the declaring
* class.
*/
@VisibleForTesting
static class ParameterHasNoDistinctValueException extends Exception {
ParameterHasNoDistinctValueException(Parameter parameter) {
super(
"Cannot generate distinct value for parameter "
+ parameter
+ " of "
+ parameter.getDeclaringInvokable());
}
}
/**
* Thrown if the test tries to invoke a static factory method to test instance methods but the
* factory returned null.
*/
@VisibleForTesting
static class FactoryMethodReturnsNullException extends Exception {
public FactoryMethodReturnsNullException(Invokable<?, ?> factory) {
super(factory + " returns null and cannot be used to test instance methods.");
}
}
private static final class SerializableDummyProxy extends DummyProxy implements Serializable {
private final transient ClassSanityTester tester;
SerializableDummyProxy(ClassSanityTester tester) {
this.tester = tester;
}
@Override
<R> R dummyReturnValue(TypeToken<R> returnType) {
return tester.getDummyValue(returnType);
}
@Override
public boolean equals(@Nullable Object obj) {
return obj instanceof SerializableDummyProxy;
}
@Override
public int hashCode() {
return 0;
}
}
}
| google/guava | guava-testlib/src/com/google/common/testing/ClassSanityTester.java |
2,763 | package com.winterbe.java8.samples.stream;
import java.util.Optional;
/**
* @author Benjamin Winterberg
*/
public class Optional1 {
public static void main(String[] args) {
Optional<String> optional = Optional.of("bam");
optional.isPresent(); // true
optional.get(); // "bam"
optional.orElse("fallback"); // "bam"
optional.ifPresent((s) -> System.out.println(s.charAt(0))); // "b"
}
} | winterbe/java8-tutorial | src/com/winterbe/java8/samples/stream/Optional1.java |
2,764 | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
package com.google.protobuf;
import static com.google.protobuf.Internal.checkNotNull;
import static com.google.protobuf.WireFormat.FIXED32_SIZE;
import static com.google.protobuf.WireFormat.FIXED64_SIZE;
import static com.google.protobuf.WireFormat.MAX_VARINT32_SIZE;
import static com.google.protobuf.WireFormat.MAX_VARINT64_SIZE;
import static com.google.protobuf.WireFormat.MESSAGE_SET_ITEM;
import static com.google.protobuf.WireFormat.MESSAGE_SET_MESSAGE;
import static com.google.protobuf.WireFormat.MESSAGE_SET_TYPE_ID;
import static com.google.protobuf.WireFormat.WIRETYPE_END_GROUP;
import static com.google.protobuf.WireFormat.WIRETYPE_FIXED32;
import static com.google.protobuf.WireFormat.WIRETYPE_FIXED64;
import static com.google.protobuf.WireFormat.WIRETYPE_LENGTH_DELIMITED;
import static com.google.protobuf.WireFormat.WIRETYPE_START_GROUP;
import static com.google.protobuf.WireFormat.WIRETYPE_VARINT;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayDeque;
import java.util.List;
import java.util.Map;
import java.util.Queue;
/**
* A protobuf writer that serializes messages in their binary form. Messages are serialized in
* reverse in order to avoid calculating the serialized size of each nested message. Since the
* message size is not known in advance, the writer employs a strategy of chunking and buffer
* chaining. Buffers are allocated as-needed by a provided {@link BufferAllocator}. Once writing is
* finished, the application can access the buffers in forward-writing order by calling {@link
* #complete()}.
*
* <p>Once {@link #complete()} has been called, the writer can not be reused for additional writes.
* The {@link #getTotalBytesWritten()} will continue to reflect the total of the write and will not
* be reset.
*/
@CheckReturnValue
@ExperimentalApi
abstract class BinaryWriter extends ByteOutput implements Writer {
public static final int DEFAULT_CHUNK_SIZE = 4096;
private final BufferAllocator alloc;
private final int chunkSize;
final ArrayDeque<AllocatedBuffer> buffers = new ArrayDeque<AllocatedBuffer>(4);
int totalDoneBytes;
/**
* Creates a new {@link BinaryWriter} that will allocate heap buffers of {@link
* #DEFAULT_CHUNK_SIZE} as necessary.
*/
public static BinaryWriter newHeapInstance(BufferAllocator alloc) {
return newHeapInstance(alloc, DEFAULT_CHUNK_SIZE);
}
/**
* Creates a new {@link BinaryWriter} that will allocate heap buffers of {@code chunkSize} as
* necessary.
*/
public static BinaryWriter newHeapInstance(BufferAllocator alloc, int chunkSize) {
return isUnsafeHeapSupported()
? newUnsafeHeapInstance(alloc, chunkSize)
: newSafeHeapInstance(alloc, chunkSize);
}
/**
* Creates a new {@link BinaryWriter} that will allocate direct (i.e. non-heap) buffers of {@link
* #DEFAULT_CHUNK_SIZE} as necessary.
*/
public static BinaryWriter newDirectInstance(BufferAllocator alloc) {
return newDirectInstance(alloc, DEFAULT_CHUNK_SIZE);
}
/**
* Creates a new {@link BinaryWriter} that will allocate direct (i.e. non-heap) buffers of {@code
* chunkSize} as necessary.
*/
public static BinaryWriter newDirectInstance(BufferAllocator alloc, int chunkSize) {
return isUnsafeDirectSupported()
? newUnsafeDirectInstance(alloc, chunkSize)
: newSafeDirectInstance(alloc, chunkSize);
}
static boolean isUnsafeHeapSupported() {
return UnsafeHeapWriter.isSupported();
}
static boolean isUnsafeDirectSupported() {
return UnsafeDirectWriter.isSupported();
}
static BinaryWriter newSafeHeapInstance(BufferAllocator alloc, int chunkSize) {
return new SafeHeapWriter(alloc, chunkSize);
}
static BinaryWriter newUnsafeHeapInstance(BufferAllocator alloc, int chunkSize) {
if (!isUnsafeHeapSupported()) {
throw new UnsupportedOperationException("Unsafe operations not supported");
}
return new UnsafeHeapWriter(alloc, chunkSize);
}
static BinaryWriter newSafeDirectInstance(BufferAllocator alloc, int chunkSize) {
return new SafeDirectWriter(alloc, chunkSize);
}
static BinaryWriter newUnsafeDirectInstance(BufferAllocator alloc, int chunkSize) {
if (!isUnsafeDirectSupported()) {
throw new UnsupportedOperationException("Unsafe operations not supported");
}
return new UnsafeDirectWriter(alloc, chunkSize);
}
/** Only allow subclassing for inner classes. */
private BinaryWriter(BufferAllocator alloc, int chunkSize) {
if (chunkSize <= 0) {
throw new IllegalArgumentException("chunkSize must be > 0");
}
this.alloc = checkNotNull(alloc, "alloc");
this.chunkSize = chunkSize;
}
@Override
public final FieldOrder fieldOrder() {
return FieldOrder.DESCENDING;
}
/**
* Completes the write operation and returns a queue of {@link AllocatedBuffer} objects in
* forward-writing order. This method should only be called once.
*
* <p>After calling this method, the writer can not be reused. Create a new writer for future
* writes.
*/
@CanIgnoreReturnValue
public final Queue<AllocatedBuffer> complete() {
finishCurrentBuffer();
return buffers;
}
@Override
public final void writeSFixed32(int fieldNumber, int value) throws IOException {
writeFixed32(fieldNumber, value);
}
@Override
public final void writeInt64(int fieldNumber, long value) throws IOException {
writeUInt64(fieldNumber, value);
}
@Override
public final void writeSFixed64(int fieldNumber, long value) throws IOException {
writeFixed64(fieldNumber, value);
}
@Override
public final void writeFloat(int fieldNumber, float value) throws IOException {
writeFixed32(fieldNumber, Float.floatToRawIntBits(value));
}
@Override
public final void writeDouble(int fieldNumber, double value) throws IOException {
writeFixed64(fieldNumber, Double.doubleToRawLongBits(value));
}
@Override
public final void writeEnum(int fieldNumber, int value) throws IOException {
writeInt32(fieldNumber, value);
}
@Override
public final void writeInt32List(int fieldNumber, List<Integer> list, boolean packed)
throws IOException {
if (list instanceof IntArrayList) {
writeInt32List_Internal(fieldNumber, (IntArrayList) list, packed);
} else {
writeInt32List_Internal(fieldNumber, list, packed);
}
}
private void writeInt32List_Internal(int fieldNumber, List<Integer> list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * MAX_VARINT64_SIZE));
int prevBytes = getTotalBytesWritten();
for (int i = list.size() - 1; i >= 0; --i) {
writeInt32(list.get(i));
}
int length = getTotalBytesWritten() - prevBytes;
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
} else {
for (int i = list.size() - 1; i >= 0; --i) {
writeInt32(fieldNumber, list.get(i));
}
}
}
private void writeInt32List_Internal(int fieldNumber, IntArrayList list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * MAX_VARINT64_SIZE));
int prevBytes = getTotalBytesWritten();
for (int i = list.size() - 1; i >= 0; --i) {
writeInt32(list.getInt(i));
}
int length = getTotalBytesWritten() - prevBytes;
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
} else {
for (int i = list.size() - 1; i >= 0; --i) {
writeInt32(fieldNumber, list.getInt(i));
}
}
}
@Override
public final void writeFixed32List(int fieldNumber, List<Integer> list, boolean packed)
throws IOException {
if (list instanceof IntArrayList) {
writeFixed32List_Internal(fieldNumber, (IntArrayList) list, packed);
} else {
writeFixed32List_Internal(fieldNumber, list, packed);
}
}
private void writeFixed32List_Internal(int fieldNumber, List<Integer> list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * FIXED32_SIZE));
int prevBytes = getTotalBytesWritten();
for (int i = list.size() - 1; i >= 0; --i) {
writeFixed32(list.get(i));
}
int length = getTotalBytesWritten() - prevBytes;
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
} else {
for (int i = list.size() - 1; i >= 0; --i) {
writeFixed32(fieldNumber, list.get(i));
}
}
}
private void writeFixed32List_Internal(int fieldNumber, IntArrayList list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * FIXED32_SIZE));
int prevBytes = getTotalBytesWritten();
for (int i = list.size() - 1; i >= 0; --i) {
writeFixed32(list.getInt(i));
}
int length = getTotalBytesWritten() - prevBytes;
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
} else {
for (int i = list.size() - 1; i >= 0; --i) {
writeFixed32(fieldNumber, list.getInt(i));
}
}
}
@Override
public final void writeInt64List(int fieldNumber, List<Long> list, boolean packed)
throws IOException {
writeUInt64List(fieldNumber, list, packed);
}
@Override
public final void writeUInt64List(int fieldNumber, List<Long> list, boolean packed)
throws IOException {
if (list instanceof LongArrayList) {
writeUInt64List_Internal(fieldNumber, (LongArrayList) list, packed);
} else {
writeUInt64List_Internal(fieldNumber, list, packed);
}
}
private void writeUInt64List_Internal(int fieldNumber, List<Long> list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * MAX_VARINT64_SIZE));
int prevBytes = getTotalBytesWritten();
for (int i = list.size() - 1; i >= 0; --i) {
writeVarint64(list.get(i));
}
int length = getTotalBytesWritten() - prevBytes;
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
} else {
for (int i = list.size() - 1; i >= 0; --i) {
writeUInt64(fieldNumber, list.get(i));
}
}
}
private void writeUInt64List_Internal(int fieldNumber, LongArrayList list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * MAX_VARINT64_SIZE));
int prevBytes = getTotalBytesWritten();
for (int i = list.size() - 1; i >= 0; --i) {
writeVarint64(list.getLong(i));
}
int length = getTotalBytesWritten() - prevBytes;
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
} else {
for (int i = list.size() - 1; i >= 0; --i) {
writeUInt64(fieldNumber, list.getLong(i));
}
}
}
@Override
public final void writeFixed64List(int fieldNumber, List<Long> list, boolean packed)
throws IOException {
if (list instanceof LongArrayList) {
writeFixed64List_Internal(fieldNumber, (LongArrayList) list, packed);
} else {
writeFixed64List_Internal(fieldNumber, list, packed);
}
}
private void writeFixed64List_Internal(int fieldNumber, List<Long> list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * FIXED64_SIZE));
int prevBytes = getTotalBytesWritten();
for (int i = list.size() - 1; i >= 0; --i) {
writeFixed64(list.get(i));
}
int length = getTotalBytesWritten() - prevBytes;
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
} else {
for (int i = list.size() - 1; i >= 0; --i) {
writeFixed64(fieldNumber, list.get(i));
}
}
}
private void writeFixed64List_Internal(int fieldNumber, LongArrayList list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * FIXED64_SIZE));
int prevBytes = getTotalBytesWritten();
for (int i = list.size() - 1; i >= 0; --i) {
writeFixed64(list.getLong(i));
}
int length = getTotalBytesWritten() - prevBytes;
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
} else {
for (int i = list.size() - 1; i >= 0; --i) {
writeFixed64(fieldNumber, list.getLong(i));
}
}
}
@Override
public final void writeFloatList(int fieldNumber, List<Float> list, boolean packed)
throws IOException {
if (list instanceof FloatArrayList) {
writeFloatList_Internal(fieldNumber, (FloatArrayList) list, packed);
} else {
writeFloatList_Internal(fieldNumber, list, packed);
}
}
private void writeFloatList_Internal(int fieldNumber, List<Float> list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * FIXED32_SIZE));
int prevBytes = getTotalBytesWritten();
for (int i = list.size() - 1; i >= 0; --i) {
writeFixed32(Float.floatToRawIntBits(list.get(i)));
}
int length = getTotalBytesWritten() - prevBytes;
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
} else {
for (int i = list.size() - 1; i >= 0; --i) {
writeFloat(fieldNumber, list.get(i));
}
}
}
private void writeFloatList_Internal(int fieldNumber, FloatArrayList list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * FIXED32_SIZE));
int prevBytes = getTotalBytesWritten();
for (int i = list.size() - 1; i >= 0; --i) {
writeFixed32(Float.floatToRawIntBits(list.getFloat(i)));
}
int length = getTotalBytesWritten() - prevBytes;
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
} else {
for (int i = list.size() - 1; i >= 0; --i) {
writeFloat(fieldNumber, list.getFloat(i));
}
}
}
@Override
public final void writeDoubleList(int fieldNumber, List<Double> list, boolean packed)
throws IOException {
if (list instanceof DoubleArrayList) {
writeDoubleList_Internal(fieldNumber, (DoubleArrayList) list, packed);
} else {
writeDoubleList_Internal(fieldNumber, list, packed);
}
}
private void writeDoubleList_Internal(int fieldNumber, List<Double> list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * FIXED64_SIZE));
int prevBytes = getTotalBytesWritten();
for (int i = list.size() - 1; i >= 0; --i) {
writeFixed64(Double.doubleToRawLongBits(list.get(i)));
}
int length = getTotalBytesWritten() - prevBytes;
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
} else {
for (int i = list.size() - 1; i >= 0; --i) {
writeDouble(fieldNumber, list.get(i));
}
}
}
private void writeDoubleList_Internal(int fieldNumber, DoubleArrayList list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * FIXED64_SIZE));
int prevBytes = getTotalBytesWritten();
for (int i = list.size() - 1; i >= 0; --i) {
writeFixed64(Double.doubleToRawLongBits(list.getDouble(i)));
}
int length = getTotalBytesWritten() - prevBytes;
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
} else {
for (int i = list.size() - 1; i >= 0; --i) {
writeDouble(fieldNumber, list.getDouble(i));
}
}
}
@Override
public final void writeEnumList(int fieldNumber, List<Integer> list, boolean packed)
throws IOException {
writeInt32List(fieldNumber, list, packed);
}
@Override
public final void writeBoolList(int fieldNumber, List<Boolean> list, boolean packed)
throws IOException {
if (list instanceof BooleanArrayList) {
writeBoolList_Internal(fieldNumber, (BooleanArrayList) list, packed);
} else {
writeBoolList_Internal(fieldNumber, list, packed);
}
}
private void writeBoolList_Internal(int fieldNumber, List<Boolean> list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + list.size());
int prevBytes = getTotalBytesWritten();
for (int i = list.size() - 1; i >= 0; --i) {
writeBool(list.get(i));
}
int length = getTotalBytesWritten() - prevBytes;
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
} else {
for (int i = list.size() - 1; i >= 0; --i) {
writeBool(fieldNumber, list.get(i));
}
}
}
private void writeBoolList_Internal(int fieldNumber, BooleanArrayList list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + list.size());
int prevBytes = getTotalBytesWritten();
for (int i = list.size() - 1; i >= 0; --i) {
writeBool(list.getBoolean(i));
}
int length = getTotalBytesWritten() - prevBytes;
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
} else {
for (int i = list.size() - 1; i >= 0; --i) {
writeBool(fieldNumber, list.getBoolean(i));
}
}
}
@Override
public final void writeStringList(int fieldNumber, List<String> list) throws IOException {
if (list instanceof LazyStringList) {
final LazyStringList lazyList = (LazyStringList) list;
for (int i = list.size() - 1; i >= 0; i--) {
writeLazyString(fieldNumber, lazyList.getRaw(i));
}
} else {
for (int i = list.size() - 1; i >= 0; i--) {
writeString(fieldNumber, list.get(i));
}
}
}
private void writeLazyString(int fieldNumber, Object value) throws IOException {
if (value instanceof String) {
writeString(fieldNumber, (String) value);
} else {
writeBytes(fieldNumber, (ByteString) value);
}
}
@Override
public final void writeBytesList(int fieldNumber, List<ByteString> list) throws IOException {
for (int i = list.size() - 1; i >= 0; i--) {
writeBytes(fieldNumber, list.get(i));
}
}
@Override
public final void writeUInt32List(int fieldNumber, List<Integer> list, boolean packed)
throws IOException {
if (list instanceof IntArrayList) {
writeUInt32List_Internal(fieldNumber, (IntArrayList) list, packed);
} else {
writeUInt32List_Internal(fieldNumber, list, packed);
}
}
private void writeUInt32List_Internal(int fieldNumber, List<Integer> list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * MAX_VARINT32_SIZE));
int prevBytes = getTotalBytesWritten();
for (int i = list.size() - 1; i >= 0; --i) {
writeVarint32(list.get(i));
}
int length = getTotalBytesWritten() - prevBytes;
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
} else {
for (int i = list.size() - 1; i >= 0; --i) {
writeUInt32(fieldNumber, list.get(i));
}
}
}
private void writeUInt32List_Internal(int fieldNumber, IntArrayList list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * MAX_VARINT32_SIZE));
int prevBytes = getTotalBytesWritten();
for (int i = list.size() - 1; i >= 0; --i) {
writeVarint32(list.getInt(i));
}
int length = getTotalBytesWritten() - prevBytes;
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
} else {
for (int i = list.size() - 1; i >= 0; --i) {
writeUInt32(fieldNumber, list.getInt(i));
}
}
}
@Override
public final void writeSFixed32List(int fieldNumber, List<Integer> list, boolean packed)
throws IOException {
writeFixed32List(fieldNumber, list, packed);
}
@Override
public final void writeSFixed64List(int fieldNumber, List<Long> list, boolean packed)
throws IOException {
writeFixed64List(fieldNumber, list, packed);
}
@Override
public final void writeSInt32List(int fieldNumber, List<Integer> list, boolean packed)
throws IOException {
if (list instanceof IntArrayList) {
writeSInt32List_Internal(fieldNumber, (IntArrayList) list, packed);
} else {
writeSInt32List_Internal(fieldNumber, list, packed);
}
}
private void writeSInt32List_Internal(int fieldNumber, List<Integer> list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * MAX_VARINT32_SIZE));
int prevBytes = getTotalBytesWritten();
for (int i = list.size() - 1; i >= 0; --i) {
writeSInt32(list.get(i));
}
int length = getTotalBytesWritten() - prevBytes;
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
} else {
for (int i = list.size() - 1; i >= 0; --i) {
writeSInt32(fieldNumber, list.get(i));
}
}
}
private void writeSInt32List_Internal(int fieldNumber, IntArrayList list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * MAX_VARINT32_SIZE));
int prevBytes = getTotalBytesWritten();
for (int i = list.size() - 1; i >= 0; --i) {
writeSInt32(list.getInt(i));
}
int length = getTotalBytesWritten() - prevBytes;
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
} else {
for (int i = list.size() - 1; i >= 0; --i) {
writeSInt32(fieldNumber, list.getInt(i));
}
}
}
@Override
public final void writeSInt64List(int fieldNumber, List<Long> list, boolean packed)
throws IOException {
if (list instanceof LongArrayList) {
writeSInt64List_Internal(fieldNumber, (LongArrayList) list, packed);
} else {
writeSInt64List_Internal(fieldNumber, list, packed);
}
}
private static final int MAP_KEY_NUMBER = 1;
private static final int MAP_VALUE_NUMBER = 2;
@Override
public <K, V> void writeMap(int fieldNumber, MapEntryLite.Metadata<K, V> metadata, Map<K, V> map)
throws IOException {
// TODO: Reverse write those entries.
for (Map.Entry<K, V> entry : map.entrySet()) {
int prevBytes = getTotalBytesWritten();
writeMapEntryField(this, MAP_VALUE_NUMBER, metadata.valueType, entry.getValue());
writeMapEntryField(this, MAP_KEY_NUMBER, metadata.keyType, entry.getKey());
int length = getTotalBytesWritten() - prevBytes;
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
}
}
static final void writeMapEntryField(
Writer writer, int fieldNumber, WireFormat.FieldType fieldType, Object object)
throws IOException {
switch (fieldType) {
case BOOL:
writer.writeBool(fieldNumber, (Boolean) object);
break;
case FIXED32:
writer.writeFixed32(fieldNumber, (Integer) object);
break;
case FIXED64:
writer.writeFixed64(fieldNumber, (Long) object);
break;
case INT32:
writer.writeInt32(fieldNumber, (Integer) object);
break;
case INT64:
writer.writeInt64(fieldNumber, (Long) object);
break;
case SFIXED32:
writer.writeSFixed32(fieldNumber, (Integer) object);
break;
case SFIXED64:
writer.writeSFixed64(fieldNumber, (Long) object);
break;
case SINT32:
writer.writeSInt32(fieldNumber, (Integer) object);
break;
case SINT64:
writer.writeSInt64(fieldNumber, (Long) object);
break;
case STRING:
writer.writeString(fieldNumber, (String) object);
break;
case UINT32:
writer.writeUInt32(fieldNumber, (Integer) object);
break;
case UINT64:
writer.writeUInt64(fieldNumber, (Long) object);
break;
case FLOAT:
writer.writeFloat(fieldNumber, (Float) object);
break;
case DOUBLE:
writer.writeDouble(fieldNumber, (Double) object);
break;
case MESSAGE:
writer.writeMessage(fieldNumber, object);
break;
case BYTES:
writer.writeBytes(fieldNumber, (ByteString) object);
break;
case ENUM:
if (object instanceof Internal.EnumLite) {
writer.writeEnum(fieldNumber, ((Internal.EnumLite) object).getNumber());
} else if (object instanceof Integer) {
writer.writeEnum(fieldNumber, (Integer) object);
} else {
throw new IllegalArgumentException("Unexpected type for enum in map.");
}
break;
default:
throw new IllegalArgumentException("Unsupported map value type for: " + fieldType);
}
}
private void writeSInt64List_Internal(int fieldNumber, List<Long> list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * MAX_VARINT64_SIZE));
int prevBytes = getTotalBytesWritten();
for (int i = list.size() - 1; i >= 0; --i) {
writeSInt64(list.get(i));
}
int length = getTotalBytesWritten() - prevBytes;
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
} else {
for (int i = list.size() - 1; i >= 0; --i) {
writeSInt64(fieldNumber, list.get(i));
}
}
}
private void writeSInt64List_Internal(int fieldNumber, LongArrayList list, boolean packed)
throws IOException {
if (packed) {
requireSpace((MAX_VARINT32_SIZE * 2) + (list.size() * MAX_VARINT64_SIZE));
int prevBytes = getTotalBytesWritten();
for (int i = list.size() - 1; i >= 0; --i) {
writeSInt64(list.getLong(i));
}
int length = getTotalBytesWritten() - prevBytes;
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
} else {
for (int i = list.size() - 1; i >= 0; --i) {
writeSInt64(fieldNumber, list.getLong(i));
}
}
}
@Override
public final void writeMessageList(int fieldNumber, List<?> list) throws IOException {
for (int i = list.size() - 1; i >= 0; i--) {
writeMessage(fieldNumber, list.get(i));
}
}
@Override
public final void writeMessageList(int fieldNumber, List<?> list, Schema schema)
throws IOException {
for (int i = list.size() - 1; i >= 0; i--) {
writeMessage(fieldNumber, list.get(i), schema);
}
}
@Deprecated
@Override
public final void writeGroupList(int fieldNumber, List<?> list) throws IOException {
for (int i = list.size() - 1; i >= 0; i--) {
writeGroup(fieldNumber, list.get(i));
}
}
@Deprecated
@Override
public final void writeGroupList(int fieldNumber, List<?> list, Schema schema)
throws IOException {
for (int i = list.size() - 1; i >= 0; i--) {
writeGroup(fieldNumber, list.get(i), schema);
}
}
@Override
public final void writeMessageSetItem(int fieldNumber, Object value) throws IOException {
writeTag(MESSAGE_SET_ITEM, WIRETYPE_END_GROUP);
if (value instanceof ByteString) {
writeBytes(MESSAGE_SET_MESSAGE, (ByteString) value);
} else {
writeMessage(MESSAGE_SET_MESSAGE, value);
}
writeUInt32(MESSAGE_SET_TYPE_ID, fieldNumber);
writeTag(MESSAGE_SET_ITEM, WIRETYPE_START_GROUP);
}
final AllocatedBuffer newHeapBuffer() {
return alloc.allocateHeapBuffer(chunkSize);
}
final AllocatedBuffer newHeapBuffer(int capacity) {
return alloc.allocateHeapBuffer(Math.max(capacity, chunkSize));
}
final AllocatedBuffer newDirectBuffer() {
return alloc.allocateDirectBuffer(chunkSize);
}
final AllocatedBuffer newDirectBuffer(int capacity) {
return alloc.allocateDirectBuffer(Math.max(capacity, chunkSize));
}
/**
* Gets the total number of bytes that have been written. This will not be reset by a call to
* {@link #complete()}.
*/
public abstract int getTotalBytesWritten();
abstract void requireSpace(int size);
abstract void finishCurrentBuffer();
abstract void writeTag(int fieldNumber, int wireType);
abstract void writeVarint32(int value);
abstract void writeInt32(int value);
abstract void writeSInt32(int value);
abstract void writeFixed32(int value);
abstract void writeVarint64(long value);
abstract void writeSInt64(long value);
abstract void writeFixed64(long value);
abstract void writeBool(boolean value);
abstract void writeString(String in);
/**
* Not using the version in CodedOutputStream due to the fact that benchmarks have shown a
* performance improvement when returning a byte (rather than an int).
*/
private static byte computeUInt64SizeNoTag(long value) {
// handle two popular special cases up front ...
if ((value & (~0L << 7)) == 0L) {
// Byte 1
return 1;
}
if (value < 0L) {
// Byte 10
return 10;
}
// ... leaving us with 8 remaining, which we can divide and conquer
byte n = 2;
if ((value & (~0L << 35)) != 0L) {
// Byte 6-9
n += 4; // + (value >>> 63);
value >>>= 28;
}
if ((value & (~0L << 21)) != 0L) {
// Byte 4-5 or 8-9
n += 2;
value >>>= 14;
}
if ((value & (~0L << 14)) != 0L) {
// Byte 3 or 7
n += 1;
}
return n;
}
/** Writer that uses safe operations on target array. */
private static final class SafeHeapWriter extends BinaryWriter {
private AllocatedBuffer allocatedBuffer;
private byte[] buffer;
private int offset;
private int limit;
private int offsetMinusOne;
private int limitMinusOne;
private int pos;
SafeHeapWriter(BufferAllocator alloc, int chunkSize) {
super(alloc, chunkSize);
nextBuffer();
}
@Override
void finishCurrentBuffer() {
if (allocatedBuffer != null) {
totalDoneBytes += bytesWrittenToCurrentBuffer();
allocatedBuffer.position((pos - allocatedBuffer.arrayOffset()) + 1);
allocatedBuffer = null;
pos = 0;
limitMinusOne = 0;
}
}
private void nextBuffer() {
nextBuffer(newHeapBuffer());
}
private void nextBuffer(int capacity) {
nextBuffer(newHeapBuffer(capacity));
}
private void nextBuffer(AllocatedBuffer allocatedBuffer) {
if (!allocatedBuffer.hasArray()) {
throw new RuntimeException("Allocator returned non-heap buffer");
}
finishCurrentBuffer();
buffers.addFirst(allocatedBuffer);
this.allocatedBuffer = allocatedBuffer;
this.buffer = allocatedBuffer.array();
int arrayOffset = allocatedBuffer.arrayOffset();
this.limit = arrayOffset + allocatedBuffer.limit();
this.offset = arrayOffset + allocatedBuffer.position();
this.offsetMinusOne = offset - 1;
this.limitMinusOne = limit - 1;
this.pos = limitMinusOne;
}
@Override
public int getTotalBytesWritten() {
return totalDoneBytes + bytesWrittenToCurrentBuffer();
}
int bytesWrittenToCurrentBuffer() {
return limitMinusOne - pos;
}
int spaceLeft() {
return pos - offsetMinusOne;
}
@Override
public void writeUInt32(int fieldNumber, int value) throws IOException {
requireSpace(MAX_VARINT32_SIZE * 2);
writeVarint32(value);
writeTag(fieldNumber, WIRETYPE_VARINT);
}
@Override
public void writeInt32(int fieldNumber, int value) throws IOException {
requireSpace(MAX_VARINT32_SIZE + MAX_VARINT64_SIZE);
writeInt32(value);
writeTag(fieldNumber, WIRETYPE_VARINT);
}
@Override
public void writeSInt32(int fieldNumber, int value) throws IOException {
requireSpace(MAX_VARINT32_SIZE * 2);
writeSInt32(value);
writeTag(fieldNumber, WIRETYPE_VARINT);
}
@Override
public void writeFixed32(int fieldNumber, int value) throws IOException {
requireSpace(MAX_VARINT32_SIZE + FIXED32_SIZE);
writeFixed32(value);
writeTag(fieldNumber, WIRETYPE_FIXED32);
}
@Override
public void writeUInt64(int fieldNumber, long value) throws IOException {
requireSpace(MAX_VARINT32_SIZE + MAX_VARINT64_SIZE);
writeVarint64(value);
writeTag(fieldNumber, WIRETYPE_VARINT);
}
@Override
public void writeSInt64(int fieldNumber, long value) throws IOException {
requireSpace(MAX_VARINT32_SIZE + MAX_VARINT64_SIZE);
writeSInt64(value);
writeTag(fieldNumber, WIRETYPE_VARINT);
}
@Override
public void writeFixed64(int fieldNumber, long value) throws IOException {
requireSpace(MAX_VARINT32_SIZE + FIXED64_SIZE);
writeFixed64(value);
writeTag(fieldNumber, WIRETYPE_FIXED64);
}
@Override
public void writeBool(int fieldNumber, boolean value) throws IOException {
requireSpace(MAX_VARINT32_SIZE + 1);
write((byte) (value ? 1 : 0));
writeTag(fieldNumber, WIRETYPE_VARINT);
}
@Override
public void writeString(int fieldNumber, String value) throws IOException {
int prevBytes = getTotalBytesWritten();
writeString(value);
int length = getTotalBytesWritten() - prevBytes;
requireSpace(2 * MAX_VARINT32_SIZE);
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
}
@Override
public void writeBytes(int fieldNumber, ByteString value) throws IOException {
try {
value.writeToReverse(this);
} catch (IOException e) {
// Should never happen since the writer does not throw.
throw new RuntimeException(e);
}
requireSpace(MAX_VARINT32_SIZE * 2);
writeVarint32(value.size());
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
}
@Override
public void writeMessage(int fieldNumber, Object value) throws IOException {
int prevBytes = getTotalBytesWritten();
Protobuf.getInstance().writeTo(value, this);
int length = getTotalBytesWritten() - prevBytes;
requireSpace(MAX_VARINT32_SIZE * 2);
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
}
@Override
public void writeMessage(int fieldNumber, Object value, Schema schema) throws IOException {
int prevBytes = getTotalBytesWritten();
schema.writeTo(value, this);
int length = getTotalBytesWritten() - prevBytes;
requireSpace(MAX_VARINT32_SIZE * 2);
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
}
@Deprecated
@Override
public void writeGroup(int fieldNumber, Object value) throws IOException {
writeTag(fieldNumber, WIRETYPE_END_GROUP);
Protobuf.getInstance().writeTo(value, this);
writeTag(fieldNumber, WIRETYPE_START_GROUP);
}
@Override
public void writeGroup(int fieldNumber, Object value, Schema schema) throws IOException {
writeTag(fieldNumber, WIRETYPE_END_GROUP);
schema.writeTo(value, this);
writeTag(fieldNumber, WIRETYPE_START_GROUP);
}
@Override
public void writeStartGroup(int fieldNumber) {
writeTag(fieldNumber, WIRETYPE_START_GROUP);
}
@Override
public void writeEndGroup(int fieldNumber) {
writeTag(fieldNumber, WIRETYPE_END_GROUP);
}
@Override
void writeInt32(int value) {
if (value >= 0) {
writeVarint32(value);
} else {
writeVarint64(value);
}
}
@Override
void writeSInt32(int value) {
writeVarint32(CodedOutputStream.encodeZigZag32(value));
}
@Override
void writeSInt64(long value) {
writeVarint64(CodedOutputStream.encodeZigZag64(value));
}
@Override
void writeBool(boolean value) {
write((byte) (value ? 1 : 0));
}
@Override
void writeTag(int fieldNumber, int wireType) {
writeVarint32(WireFormat.makeTag(fieldNumber, wireType));
}
@Override
void writeVarint32(int value) {
if ((value & (~0 << 7)) == 0) {
writeVarint32OneByte(value);
} else if ((value & (~0 << 14)) == 0) {
writeVarint32TwoBytes(value);
} else if ((value & (~0 << 21)) == 0) {
writeVarint32ThreeBytes(value);
} else if ((value & (~0 << 28)) == 0) {
writeVarint32FourBytes(value);
} else {
writeVarint32FiveBytes(value);
}
}
private void writeVarint32OneByte(int value) {
buffer[pos--] = (byte) value;
}
private void writeVarint32TwoBytes(int value) {
buffer[pos--] = (byte) (value >>> 7);
buffer[pos--] = (byte) ((value & 0x7F) | 0x80);
}
private void writeVarint32ThreeBytes(int value) {
buffer[pos--] = (byte) (value >>> 14);
buffer[pos--] = (byte) (((value >>> 7) & 0x7F) | 0x80);
buffer[pos--] = (byte) ((value & 0x7F) | 0x80);
}
private void writeVarint32FourBytes(int value) {
buffer[pos--] = (byte) (value >>> 21);
buffer[pos--] = (byte) (((value >>> 14) & 0x7F) | 0x80);
buffer[pos--] = (byte) (((value >>> 7) & 0x7F) | 0x80);
buffer[pos--] = (byte) ((value & 0x7F) | 0x80);
}
private void writeVarint32FiveBytes(int value) {
buffer[pos--] = (byte) (value >>> 28);
buffer[pos--] = (byte) (((value >>> 21) & 0x7F) | 0x80);
buffer[pos--] = (byte) (((value >>> 14) & 0x7F) | 0x80);
buffer[pos--] = (byte) (((value >>> 7) & 0x7F) | 0x80);
buffer[pos--] = (byte) ((value & 0x7F) | 0x80);
}
@Override
void writeVarint64(long value) {
switch (computeUInt64SizeNoTag(value)) {
case 1:
writeVarint64OneByte(value);
break;
case 2:
writeVarint64TwoBytes(value);
break;
case 3:
writeVarint64ThreeBytes(value);
break;
case 4:
writeVarint64FourBytes(value);
break;
case 5:
writeVarint64FiveBytes(value);
break;
case 6:
writeVarint64SixBytes(value);
break;
case 7:
writeVarint64SevenBytes(value);
break;
case 8:
writeVarint64EightBytes(value);
break;
case 9:
writeVarint64NineBytes(value);
break;
case 10:
writeVarint64TenBytes(value);
break;
}
}
private void writeVarint64OneByte(long value) {
buffer[pos--] = (byte) value;
}
private void writeVarint64TwoBytes(long value) {
buffer[pos--] = (byte) (value >>> 7);
buffer[pos--] = (byte) (((int) value & 0x7F) | 0x80);
}
private void writeVarint64ThreeBytes(long value) {
buffer[pos--] = (byte) (((int) value) >>> 14);
buffer[pos--] = (byte) (((value >>> 7) & 0x7F) | 0x80);
buffer[pos--] = (byte) ((value & 0x7F) | 0x80);
}
private void writeVarint64FourBytes(long value) {
buffer[pos--] = (byte) (value >>> 21);
buffer[pos--] = (byte) (((value >>> 14) & 0x7F) | 0x80);
buffer[pos--] = (byte) (((value >>> 7) & 0x7F) | 0x80);
buffer[pos--] = (byte) ((value & 0x7F) | 0x80);
}
private void writeVarint64FiveBytes(long value) {
buffer[pos--] = (byte) (value >>> 28);
buffer[pos--] = (byte) (((value >>> 21) & 0x7F) | 0x80);
buffer[pos--] = (byte) (((value >>> 14) & 0x7F) | 0x80);
buffer[pos--] = (byte) (((value >>> 7) & 0x7F) | 0x80);
buffer[pos--] = (byte) ((value & 0x7F) | 0x80);
}
private void writeVarint64SixBytes(long value) {
buffer[pos--] = (byte) (value >>> 35);
buffer[pos--] = (byte) (((value >>> 28) & 0x7F) | 0x80);
buffer[pos--] = (byte) (((value >>> 21) & 0x7F) | 0x80);
buffer[pos--] = (byte) (((value >>> 14) & 0x7F) | 0x80);
buffer[pos--] = (byte) (((value >>> 7) & 0x7F) | 0x80);
buffer[pos--] = (byte) ((value & 0x7F) | 0x80);
}
private void writeVarint64SevenBytes(long value) {
buffer[pos--] = (byte) (value >>> 42);
buffer[pos--] = (byte) (((value >>> 35) & 0x7F) | 0x80);
buffer[pos--] = (byte) (((value >>> 28) & 0x7F) | 0x80);
buffer[pos--] = (byte) (((value >>> 21) & 0x7F) | 0x80);
buffer[pos--] = (byte) (((value >>> 14) & 0x7F) | 0x80);
buffer[pos--] = (byte) (((value >>> 7) & 0x7F) | 0x80);
buffer[pos--] = (byte) ((value & 0x7F) | 0x80);
}
private void writeVarint64EightBytes(long value) {
buffer[pos--] = (byte) (value >>> 49);
buffer[pos--] = (byte) (((value >>> 42) & 0x7F) | 0x80);
buffer[pos--] = (byte) (((value >>> 35) & 0x7F) | 0x80);
buffer[pos--] = (byte) (((value >>> 28) & 0x7F) | 0x80);
buffer[pos--] = (byte) (((value >>> 21) & 0x7F) | 0x80);
buffer[pos--] = (byte) (((value >>> 14) & 0x7F) | 0x80);
buffer[pos--] = (byte) (((value >>> 7) & 0x7F) | 0x80);
buffer[pos--] = (byte) ((value & 0x7F) | 0x80);
}
private void writeVarint64NineBytes(long value) {
buffer[pos--] = (byte) (value >>> 56);
buffer[pos--] = (byte) (((value >>> 49) & 0x7F) | 0x80);
buffer[pos--] = (byte) (((value >>> 42) & 0x7F) | 0x80);
buffer[pos--] = (byte) (((value >>> 35) & 0x7F) | 0x80);
buffer[pos--] = (byte) (((value >>> 28) & 0x7F) | 0x80);
buffer[pos--] = (byte) (((value >>> 21) & 0x7F) | 0x80);
buffer[pos--] = (byte) (((value >>> 14) & 0x7F) | 0x80);
buffer[pos--] = (byte) (((value >>> 7) & 0x7F) | 0x80);
buffer[pos--] = (byte) ((value & 0x7F) | 0x80);
}
private void writeVarint64TenBytes(long value) {
buffer[pos--] = (byte) (value >>> 63);
buffer[pos--] = (byte) (((value >>> 56) & 0x7F) | 0x80);
buffer[pos--] = (byte) (((value >>> 49) & 0x7F) | 0x80);
buffer[pos--] = (byte) (((value >>> 42) & 0x7F) | 0x80);
buffer[pos--] = (byte) (((value >>> 35) & 0x7F) | 0x80);
buffer[pos--] = (byte) (((value >>> 28) & 0x7F) | 0x80);
buffer[pos--] = (byte) (((value >>> 21) & 0x7F) | 0x80);
buffer[pos--] = (byte) (((value >>> 14) & 0x7F) | 0x80);
buffer[pos--] = (byte) (((value >>> 7) & 0x7F) | 0x80);
buffer[pos--] = (byte) ((value & 0x7F) | 0x80);
}
@Override
void writeFixed32(int value) {
buffer[pos--] = (byte) ((value >> 24) & 0xFF);
buffer[pos--] = (byte) ((value >> 16) & 0xFF);
buffer[pos--] = (byte) ((value >> 8) & 0xFF);
buffer[pos--] = (byte) (value & 0xFF);
}
@Override
void writeFixed64(long value) {
buffer[pos--] = (byte) ((int) (value >> 56) & 0xFF);
buffer[pos--] = (byte) ((int) (value >> 48) & 0xFF);
buffer[pos--] = (byte) ((int) (value >> 40) & 0xFF);
buffer[pos--] = (byte) ((int) (value >> 32) & 0xFF);
buffer[pos--] = (byte) ((int) (value >> 24) & 0xFF);
buffer[pos--] = (byte) ((int) (value >> 16) & 0xFF);
buffer[pos--] = (byte) ((int) (value >> 8) & 0xFF);
buffer[pos--] = (byte) ((int) (value) & 0xFF);
}
@Override
void writeString(String in) {
// Request enough space to write the ASCII string.
requireSpace(in.length());
// We know the buffer is big enough...
int i = in.length() - 1;
// Set pos to the start of the ASCII string.
pos -= i;
// Designed to take advantage of
// https://wiki.openjdk.java.net/display/HotSpotInternals/RangeCheckElimination
for (char c; i >= 0 && (c = in.charAt(i)) < 0x80; i--) {
buffer[pos + i] = (byte) c;
}
if (i == -1) {
// Move pos past the String.
pos -= 1;
return;
}
pos += i;
for (char c; i >= 0; i--) {
c = in.charAt(i);
if (c < 0x80 && pos > offsetMinusOne) {
buffer[pos--] = (byte) c;
} else if (c < 0x800 && pos > offset) { // 11 bits, two UTF-8 bytes
buffer[pos--] = (byte) (0x80 | (0x3F & c));
buffer[pos--] = (byte) ((0xF << 6) | (c >>> 6));
} else if ((c < Character.MIN_SURROGATE || Character.MAX_SURROGATE < c)
&& pos > (offset + 1)) {
// Maximum single-char code point is 0xFFFF, 16 bits, three UTF-8 bytes
buffer[pos--] = (byte) (0x80 | (0x3F & c));
buffer[pos--] = (byte) (0x80 | (0x3F & (c >>> 6)));
buffer[pos--] = (byte) ((0xF << 5) | (c >>> 12));
} else if (pos > (offset + 2)) {
// Minimum code point represented by a surrogate pair is 0x10000, 17 bits,
// four UTF-8 bytes
char high = 0;
if (i == 0 || !Character.isSurrogatePair(high = in.charAt(i - 1), c)) {
throw new Utf8.UnpairedSurrogateException(i - 1, i);
}
i--;
int codePoint = Character.toCodePoint(high, c);
buffer[pos--] = (byte) (0x80 | (0x3F & codePoint));
buffer[pos--] = (byte) (0x80 | (0x3F & (codePoint >>> 6)));
buffer[pos--] = (byte) (0x80 | (0x3F & (codePoint >>> 12)));
buffer[pos--] = (byte) ((0xF << 4) | (codePoint >>> 18));
} else {
// Buffer is full - allocate a new one and revisit the current character.
requireSpace(i);
i++;
}
}
}
@Override
public void write(byte value) {
buffer[pos--] = value;
}
@Override
public void write(byte[] value, int offset, int length) {
if (spaceLeft() < length) {
nextBuffer(length);
}
pos -= length;
System.arraycopy(value, offset, buffer, pos + 1, length);
}
@Override
public void writeLazy(byte[] value, int offset, int length) {
if (spaceLeft() < length) {
// We consider the value to be immutable (likely the internals of a ByteString). Just
// wrap it in a Netty buffer and add it to the output buffer.
totalDoneBytes += length;
buffers.addFirst(AllocatedBuffer.wrap(value, offset, length));
// Advance the writer to the next buffer.
// TODO: Consider slicing if space available above some threshold.
nextBuffer();
return;
}
pos -= length;
System.arraycopy(value, offset, buffer, pos + 1, length);
}
@Override
public void write(ByteBuffer value) {
int length = value.remaining();
if (spaceLeft() < length) {
nextBuffer(length);
}
pos -= length;
value.get(buffer, pos + 1, length);
}
@Override
public void writeLazy(ByteBuffer value) {
int length = value.remaining();
if (spaceLeft() < length) {
// We consider the value to be immutable (likely the internals of a ByteString). Just
// wrap it in a Netty buffer and add it to the output buffer.
totalDoneBytes += length;
buffers.addFirst(AllocatedBuffer.wrap(value));
// Advance the writer to the next buffer.
// TODO: Consider slicing if space available above some threshold.
nextBuffer();
}
pos -= length;
value.get(buffer, pos + 1, length);
}
@Override
void requireSpace(int size) {
if (spaceLeft() < size) {
nextBuffer(size);
}
}
}
/** Writer that uses unsafe operations on a target array. */
private static final class UnsafeHeapWriter extends BinaryWriter {
private AllocatedBuffer allocatedBuffer;
private byte[] buffer;
private long offset;
private long limit;
private long offsetMinusOne;
private long limitMinusOne;
private long pos;
UnsafeHeapWriter(BufferAllocator alloc, int chunkSize) {
super(alloc, chunkSize);
nextBuffer();
}
/** Indicates whether the required unsafe operations are supported on this platform. */
static boolean isSupported() {
return UnsafeUtil.hasUnsafeArrayOperations();
}
@Override
void finishCurrentBuffer() {
if (allocatedBuffer != null) {
totalDoneBytes += bytesWrittenToCurrentBuffer();
allocatedBuffer.position((arrayPos() - allocatedBuffer.arrayOffset()) + 1);
allocatedBuffer = null;
pos = 0;
limitMinusOne = 0;
}
}
private int arrayPos() {
return (int) pos;
}
private void nextBuffer() {
nextBuffer(newHeapBuffer());
}
private void nextBuffer(int capacity) {
nextBuffer(newHeapBuffer(capacity));
}
private void nextBuffer(AllocatedBuffer allocatedBuffer) {
if (!allocatedBuffer.hasArray()) {
throw new RuntimeException("Allocator returned non-heap buffer");
}
finishCurrentBuffer();
buffers.addFirst(allocatedBuffer);
this.allocatedBuffer = allocatedBuffer;
this.buffer = allocatedBuffer.array();
int arrayOffset = allocatedBuffer.arrayOffset();
this.limit = (long) arrayOffset + allocatedBuffer.limit();
this.offset = (long) arrayOffset + allocatedBuffer.position();
this.offsetMinusOne = offset - 1;
this.limitMinusOne = limit - 1;
this.pos = limitMinusOne;
}
@Override
public int getTotalBytesWritten() {
return totalDoneBytes + bytesWrittenToCurrentBuffer();
}
int bytesWrittenToCurrentBuffer() {
return (int) (limitMinusOne - pos);
}
int spaceLeft() {
return (int) (pos - offsetMinusOne);
}
@Override
public void writeUInt32(int fieldNumber, int value) {
requireSpace(MAX_VARINT32_SIZE * 2);
writeVarint32(value);
writeTag(fieldNumber, WIRETYPE_VARINT);
}
@Override
public void writeInt32(int fieldNumber, int value) {
requireSpace(MAX_VARINT32_SIZE + MAX_VARINT64_SIZE);
writeInt32(value);
writeTag(fieldNumber, WIRETYPE_VARINT);
}
@Override
public void writeSInt32(int fieldNumber, int value) {
requireSpace(MAX_VARINT32_SIZE * 2);
writeSInt32(value);
writeTag(fieldNumber, WIRETYPE_VARINT);
}
@Override
public void writeFixed32(int fieldNumber, int value) {
requireSpace(MAX_VARINT32_SIZE + FIXED32_SIZE);
writeFixed32(value);
writeTag(fieldNumber, WIRETYPE_FIXED32);
}
@Override
public void writeUInt64(int fieldNumber, long value) {
requireSpace(MAX_VARINT32_SIZE + MAX_VARINT64_SIZE);
writeVarint64(value);
writeTag(fieldNumber, WIRETYPE_VARINT);
}
@Override
public void writeSInt64(int fieldNumber, long value) {
requireSpace(MAX_VARINT32_SIZE + MAX_VARINT64_SIZE);
writeSInt64(value);
writeTag(fieldNumber, WIRETYPE_VARINT);
}
@Override
public void writeFixed64(int fieldNumber, long value) {
requireSpace(MAX_VARINT32_SIZE + FIXED64_SIZE);
writeFixed64(value);
writeTag(fieldNumber, WIRETYPE_FIXED64);
}
@Override
public void writeBool(int fieldNumber, boolean value) {
requireSpace(MAX_VARINT32_SIZE + 1);
write((byte) (value ? 1 : 0));
writeTag(fieldNumber, WIRETYPE_VARINT);
}
@Override
public void writeString(int fieldNumber, String value) {
int prevBytes = getTotalBytesWritten();
writeString(value);
int length = getTotalBytesWritten() - prevBytes;
requireSpace(2 * MAX_VARINT32_SIZE);
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
}
@Override
public void writeBytes(int fieldNumber, ByteString value) {
try {
value.writeToReverse(this);
} catch (IOException e) {
// Should never happen since the writer does not throw.
throw new RuntimeException(e);
}
requireSpace(MAX_VARINT32_SIZE * 2);
writeVarint32(value.size());
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
}
@Override
public void writeMessage(int fieldNumber, Object value) throws IOException {
int prevBytes = getTotalBytesWritten();
Protobuf.getInstance().writeTo(value, this);
int length = getTotalBytesWritten() - prevBytes;
requireSpace(MAX_VARINT32_SIZE * 2);
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
}
@Override
public void writeMessage(int fieldNumber, Object value, Schema schema) throws IOException {
int prevBytes = getTotalBytesWritten();
schema.writeTo(value, this);
int length = getTotalBytesWritten() - prevBytes;
requireSpace(MAX_VARINT32_SIZE * 2);
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
}
@Override
public void writeGroup(int fieldNumber, Object value) throws IOException {
writeTag(fieldNumber, WIRETYPE_END_GROUP);
Protobuf.getInstance().writeTo(value, this);
writeTag(fieldNumber, WIRETYPE_START_GROUP);
}
@Override
public void writeGroup(int fieldNumber, Object value, Schema schema) throws IOException {
writeTag(fieldNumber, WIRETYPE_END_GROUP);
schema.writeTo(value, this);
writeTag(fieldNumber, WIRETYPE_START_GROUP);
}
@Override
public void writeStartGroup(int fieldNumber) {
writeTag(fieldNumber, WIRETYPE_START_GROUP);
}
@Override
public void writeEndGroup(int fieldNumber) {
writeTag(fieldNumber, WIRETYPE_END_GROUP);
}
@Override
void writeInt32(int value) {
if (value >= 0) {
writeVarint32(value);
} else {
writeVarint64(value);
}
}
@Override
void writeSInt32(int value) {
writeVarint32(CodedOutputStream.encodeZigZag32(value));
}
@Override
void writeSInt64(long value) {
writeVarint64(CodedOutputStream.encodeZigZag64(value));
}
@Override
void writeBool(boolean value) {
write((byte) (value ? 1 : 0));
}
@Override
void writeTag(int fieldNumber, int wireType) {
writeVarint32(WireFormat.makeTag(fieldNumber, wireType));
}
@Override
void writeVarint32(int value) {
if ((value & (~0 << 7)) == 0) {
writeVarint32OneByte(value);
} else if ((value & (~0 << 14)) == 0) {
writeVarint32TwoBytes(value);
} else if ((value & (~0 << 21)) == 0) {
writeVarint32ThreeBytes(value);
} else if ((value & (~0 << 28)) == 0) {
writeVarint32FourBytes(value);
} else {
writeVarint32FiveBytes(value);
}
}
private void writeVarint32OneByte(int value) {
UnsafeUtil.putByte(buffer, pos--, (byte) value);
}
private void writeVarint32TwoBytes(int value) {
UnsafeUtil.putByte(buffer, pos--, (byte) (value >>> 7));
UnsafeUtil.putByte(buffer, pos--, (byte) ((value & 0x7F) | 0x80));
}
private void writeVarint32ThreeBytes(int value) {
UnsafeUtil.putByte(buffer, pos--, (byte) (value >>> 14));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 7) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) ((value & 0x7F) | 0x80));
}
private void writeVarint32FourBytes(int value) {
UnsafeUtil.putByte(buffer, pos--, (byte) (value >>> 21));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 14) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 7) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) ((value & 0x7F) | 0x80));
}
private void writeVarint32FiveBytes(int value) {
UnsafeUtil.putByte(buffer, pos--, (byte) (value >>> 28));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 21) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 14) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 7) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) ((value & 0x7F) | 0x80));
}
@Override
void writeVarint64(long value) {
switch (computeUInt64SizeNoTag(value)) {
case 1:
writeVarint64OneByte(value);
break;
case 2:
writeVarint64TwoBytes(value);
break;
case 3:
writeVarint64ThreeBytes(value);
break;
case 4:
writeVarint64FourBytes(value);
break;
case 5:
writeVarint64FiveBytes(value);
break;
case 6:
writeVarint64SixBytes(value);
break;
case 7:
writeVarint64SevenBytes(value);
break;
case 8:
writeVarint64EightBytes(value);
break;
case 9:
writeVarint64NineBytes(value);
break;
case 10:
writeVarint64TenBytes(value);
break;
}
}
private void writeVarint64OneByte(long value) {
UnsafeUtil.putByte(buffer, pos--, (byte) value);
}
private void writeVarint64TwoBytes(long value) {
UnsafeUtil.putByte(buffer, pos--, (byte) (value >>> 7));
UnsafeUtil.putByte(buffer, pos--, (byte) (((int) value & 0x7F) | 0x80));
}
private void writeVarint64ThreeBytes(long value) {
UnsafeUtil.putByte(buffer, pos--, (byte) (((int) value) >>> 14));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 7) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) ((value & 0x7F) | 0x80));
}
private void writeVarint64FourBytes(long value) {
UnsafeUtil.putByte(buffer, pos--, (byte) (value >>> 21));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 14) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 7) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) ((value & 0x7F) | 0x80));
}
private void writeVarint64FiveBytes(long value) {
UnsafeUtil.putByte(buffer, pos--, (byte) (value >>> 28));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 21) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 14) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 7) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) ((value & 0x7F) | 0x80));
}
private void writeVarint64SixBytes(long value) {
UnsafeUtil.putByte(buffer, pos--, (byte) (value >>> 35));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 28) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 21) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 14) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 7) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) ((value & 0x7F) | 0x80));
}
private void writeVarint64SevenBytes(long value) {
UnsafeUtil.putByte(buffer, pos--, (byte) (value >>> 42));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 35) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 28) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 21) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 14) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 7) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) ((value & 0x7F) | 0x80));
}
private void writeVarint64EightBytes(long value) {
UnsafeUtil.putByte(buffer, pos--, (byte) (value >>> 49));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 42) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 35) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 28) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 21) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 14) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 7) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) ((value & 0x7F) | 0x80));
}
private void writeVarint64NineBytes(long value) {
UnsafeUtil.putByte(buffer, pos--, (byte) (value >>> 56));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 49) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 42) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 35) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 28) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 21) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 14) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 7) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) ((value & 0x7F) | 0x80));
}
private void writeVarint64TenBytes(long value) {
UnsafeUtil.putByte(buffer, pos--, (byte) (value >>> 63));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 56) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 49) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 42) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 35) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 28) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 21) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 14) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) (((value >>> 7) & 0x7F) | 0x80));
UnsafeUtil.putByte(buffer, pos--, (byte) ((value & 0x7F) | 0x80));
}
@Override
void writeFixed32(int value) {
UnsafeUtil.putByte(buffer, pos--, (byte) ((value >> 24) & 0xFF));
UnsafeUtil.putByte(buffer, pos--, (byte) ((value >> 16) & 0xFF));
UnsafeUtil.putByte(buffer, pos--, (byte) ((value >> 8) & 0xFF));
UnsafeUtil.putByte(buffer, pos--, (byte) (value & 0xFF));
}
@Override
void writeFixed64(long value) {
UnsafeUtil.putByte(buffer, pos--, (byte) ((int) (value >> 56) & 0xFF));
UnsafeUtil.putByte(buffer, pos--, (byte) ((int) (value >> 48) & 0xFF));
UnsafeUtil.putByte(buffer, pos--, (byte) ((int) (value >> 40) & 0xFF));
UnsafeUtil.putByte(buffer, pos--, (byte) ((int) (value >> 32) & 0xFF));
UnsafeUtil.putByte(buffer, pos--, (byte) ((int) (value >> 24) & 0xFF));
UnsafeUtil.putByte(buffer, pos--, (byte) ((int) (value >> 16) & 0xFF));
UnsafeUtil.putByte(buffer, pos--, (byte) ((int) (value >> 8) & 0xFF));
UnsafeUtil.putByte(buffer, pos--, (byte) ((int) (value) & 0xFF));
}
@Override
void writeString(String in) {
// Request enough space to write the ASCII string.
requireSpace(in.length());
// We know the buffer is big enough...
int i = in.length() - 1;
// Set pos to the start of the ASCII string.
// pos -= i;
// Designed to take advantage of
// https://wiki.openjdk.java.net/display/HotSpotInternals/RangeCheckElimination
for (char c; i >= 0 && (c = in.charAt(i)) < 0x80; i--) {
UnsafeUtil.putByte(buffer, pos--, (byte) c);
}
if (i == -1) {
// Move pos past the String.
return;
}
for (char c; i >= 0; i--) {
c = in.charAt(i);
if (c < 0x80 && pos > offsetMinusOne) {
UnsafeUtil.putByte(buffer, pos--, (byte) c);
} else if (c < 0x800 && pos > offset) { // 11 bits, two UTF-8 bytes
UnsafeUtil.putByte(buffer, pos--, (byte) (0x80 | (0x3F & c)));
UnsafeUtil.putByte(buffer, pos--, (byte) ((0xF << 6) | (c >>> 6)));
} else if ((c < Character.MIN_SURROGATE || Character.MAX_SURROGATE < c)
&& pos > offset + 1) {
// Maximum single-char code point is 0xFFFF, 16 bits, three UTF-8 bytes
UnsafeUtil.putByte(buffer, pos--, (byte) (0x80 | (0x3F & c)));
UnsafeUtil.putByte(buffer, pos--, (byte) (0x80 | (0x3F & (c >>> 6))));
UnsafeUtil.putByte(buffer, pos--, (byte) ((0xF << 5) | (c >>> 12)));
} else if (pos > offset + 2) {
// Minimum code point represented by a surrogate pair is 0x10000, 17 bits,
// four UTF-8 bytes
final char high;
if (i == 0 || !Character.isSurrogatePair(high = in.charAt(i - 1), c)) {
throw new Utf8.UnpairedSurrogateException(i - 1, i);
}
i--;
int codePoint = Character.toCodePoint(high, c);
UnsafeUtil.putByte(buffer, pos--, (byte) (0x80 | (0x3F & codePoint)));
UnsafeUtil.putByte(buffer, pos--, (byte) (0x80 | (0x3F & (codePoint >>> 6))));
UnsafeUtil.putByte(buffer, pos--, (byte) (0x80 | (0x3F & (codePoint >>> 12))));
UnsafeUtil.putByte(buffer, pos--, (byte) ((0xF << 4) | (codePoint >>> 18)));
} else {
// Buffer is full - allocate a new one and revisit the current character.
requireSpace(i);
i++;
}
}
}
@Override
public void write(byte value) {
UnsafeUtil.putByte(buffer, pos--, value);
}
@Override
public void write(byte[] value, int offset, int length) {
if (offset < 0 || offset + length > value.length) {
throw new ArrayIndexOutOfBoundsException(
String.format("value.length=%d, offset=%d, length=%d", value.length, offset, length));
}
requireSpace(length);
pos -= length;
System.arraycopy(value, offset, buffer, arrayPos() + 1, length);
}
@Override
public void writeLazy(byte[] value, int offset, int length) {
if (offset < 0 || offset + length > value.length) {
throw new ArrayIndexOutOfBoundsException(
String.format("value.length=%d, offset=%d, length=%d", value.length, offset, length));
}
if (spaceLeft() < length) {
// We consider the value to be immutable (likely the internals of a ByteString). Just
// wrap it in a Netty buffer and add it to the output buffer.
totalDoneBytes += length;
buffers.addFirst(AllocatedBuffer.wrap(value, offset, length));
// Advance the writer to the next buffer.
// TODO: Consider slicing if space available above some threshold.
nextBuffer();
return;
}
pos -= length;
System.arraycopy(value, offset, buffer, arrayPos() + 1, length);
}
@Override
public void write(ByteBuffer value) {
int length = value.remaining();
requireSpace(length);
pos -= length;
value.get(buffer, arrayPos() + 1, length);
}
@Override
public void writeLazy(ByteBuffer value) {
int length = value.remaining();
if (spaceLeft() < length) {
// We consider the value to be immutable (likely the internals of a ByteString). Just
// wrap it in a Netty buffer and add it to the output buffer.
totalDoneBytes += length;
buffers.addFirst(AllocatedBuffer.wrap(value));
// Advance the writer to the next buffer.
// TODO: Consider slicing if space available above some threshold.
nextBuffer();
}
pos -= length;
value.get(buffer, arrayPos() + 1, length);
}
@Override
void requireSpace(int size) {
if (spaceLeft() < size) {
nextBuffer(size);
}
}
}
/** Writer that uses safe operations on a target {@link ByteBuffer}. */
private static final class SafeDirectWriter extends BinaryWriter {
private ByteBuffer buffer;
private int limitMinusOne;
private int pos;
SafeDirectWriter(BufferAllocator alloc, int chunkSize) {
super(alloc, chunkSize);
nextBuffer();
}
private void nextBuffer() {
nextBuffer(newDirectBuffer());
}
private void nextBuffer(int capacity) {
nextBuffer(newDirectBuffer(capacity));
}
private void nextBuffer(AllocatedBuffer allocatedBuffer) {
if (!allocatedBuffer.hasNioBuffer()) {
throw new RuntimeException("Allocated buffer does not have NIO buffer");
}
ByteBuffer nioBuffer = allocatedBuffer.nioBuffer();
if (!nioBuffer.isDirect()) {
throw new RuntimeException("Allocator returned non-direct buffer");
}
finishCurrentBuffer();
buffers.addFirst(allocatedBuffer);
buffer = nioBuffer;
Java8Compatibility.limit(buffer, buffer.capacity());
Java8Compatibility.position(buffer, 0);
// Set byte order to little endian for fast writing of fixed 32/64.
buffer.order(ByteOrder.LITTLE_ENDIAN);
limitMinusOne = buffer.limit() - 1;
pos = limitMinusOne;
}
@Override
public int getTotalBytesWritten() {
return totalDoneBytes + bytesWrittenToCurrentBuffer();
}
private int bytesWrittenToCurrentBuffer() {
return limitMinusOne - pos;
}
private int spaceLeft() {
return pos + 1;
}
@Override
void finishCurrentBuffer() {
if (buffer != null) {
totalDoneBytes += bytesWrittenToCurrentBuffer();
// Update the indices on the netty buffer.
Java8Compatibility.position(buffer, pos + 1);
buffer = null;
pos = 0;
limitMinusOne = 0;
}
}
@Override
public void writeUInt32(int fieldNumber, int value) {
requireSpace(MAX_VARINT32_SIZE * 2);
writeVarint32(value);
writeTag(fieldNumber, WIRETYPE_VARINT);
}
@Override
public void writeInt32(int fieldNumber, int value) {
requireSpace(MAX_VARINT32_SIZE + MAX_VARINT64_SIZE);
writeInt32(value);
writeTag(fieldNumber, WIRETYPE_VARINT);
}
@Override
public void writeSInt32(int fieldNumber, int value) {
requireSpace(MAX_VARINT32_SIZE * 2);
writeSInt32(value);
writeTag(fieldNumber, WIRETYPE_VARINT);
}
@Override
public void writeFixed32(int fieldNumber, int value) {
requireSpace(MAX_VARINT32_SIZE + FIXED32_SIZE);
writeFixed32(value);
writeTag(fieldNumber, WIRETYPE_FIXED32);
}
@Override
public void writeUInt64(int fieldNumber, long value) {
requireSpace(MAX_VARINT32_SIZE + MAX_VARINT64_SIZE);
writeVarint64(value);
writeTag(fieldNumber, WIRETYPE_VARINT);
}
@Override
public void writeSInt64(int fieldNumber, long value) {
requireSpace(MAX_VARINT32_SIZE + MAX_VARINT64_SIZE);
writeSInt64(value);
writeTag(fieldNumber, WIRETYPE_VARINT);
}
@Override
public void writeFixed64(int fieldNumber, long value) {
requireSpace(MAX_VARINT32_SIZE + FIXED64_SIZE);
writeFixed64(value);
writeTag(fieldNumber, WIRETYPE_FIXED64);
}
@Override
public void writeBool(int fieldNumber, boolean value) {
requireSpace(MAX_VARINT32_SIZE + 1);
write((byte) (value ? 1 : 0));
writeTag(fieldNumber, WIRETYPE_VARINT);
}
@Override
public void writeString(int fieldNumber, String value) {
int prevBytes = getTotalBytesWritten();
writeString(value);
int length = getTotalBytesWritten() - prevBytes;
requireSpace(2 * MAX_VARINT32_SIZE);
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
}
@Override
public void writeBytes(int fieldNumber, ByteString value) {
try {
value.writeToReverse(this);
} catch (IOException e) {
// Should never happen since the writer does not throw.
throw new RuntimeException(e);
}
requireSpace(MAX_VARINT32_SIZE * 2);
writeVarint32(value.size());
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
}
@Override
public void writeMessage(int fieldNumber, Object value) throws IOException {
int prevBytes = getTotalBytesWritten();
Protobuf.getInstance().writeTo(value, this);
int length = getTotalBytesWritten() - prevBytes;
requireSpace(MAX_VARINT32_SIZE * 2);
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
}
@Override
public void writeMessage(int fieldNumber, Object value, Schema schema) throws IOException {
int prevBytes = getTotalBytesWritten();
schema.writeTo(value, this);
int length = getTotalBytesWritten() - prevBytes;
requireSpace(MAX_VARINT32_SIZE * 2);
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
}
@Deprecated
@Override
public void writeGroup(int fieldNumber, Object value) throws IOException {
writeTag(fieldNumber, WIRETYPE_END_GROUP);
Protobuf.getInstance().writeTo(value, this);
writeTag(fieldNumber, WIRETYPE_START_GROUP);
}
@Override
public void writeGroup(int fieldNumber, Object value, Schema schema) throws IOException {
writeTag(fieldNumber, WIRETYPE_END_GROUP);
schema.writeTo(value, this);
writeTag(fieldNumber, WIRETYPE_START_GROUP);
}
@Deprecated
@Override
public void writeStartGroup(int fieldNumber) {
writeTag(fieldNumber, WIRETYPE_START_GROUP);
}
@Deprecated
@Override
public void writeEndGroup(int fieldNumber) {
writeTag(fieldNumber, WIRETYPE_END_GROUP);
}
@Override
void writeInt32(int value) {
if (value >= 0) {
writeVarint32(value);
} else {
writeVarint64(value);
}
}
@Override
void writeSInt32(int value) {
writeVarint32(CodedOutputStream.encodeZigZag32(value));
}
@Override
void writeSInt64(long value) {
writeVarint64(CodedOutputStream.encodeZigZag64(value));
}
@Override
void writeBool(boolean value) {
write((byte) (value ? 1 : 0));
}
@Override
void writeTag(int fieldNumber, int wireType) {
writeVarint32(WireFormat.makeTag(fieldNumber, wireType));
}
@Override
void writeVarint32(int value) {
if ((value & (~0 << 7)) == 0) {
writeVarint32OneByte(value);
} else if ((value & (~0 << 14)) == 0) {
writeVarint32TwoBytes(value);
} else if ((value & (~0 << 21)) == 0) {
writeVarint32ThreeBytes(value);
} else if ((value & (~0 << 28)) == 0) {
writeVarint32FourBytes(value);
} else {
writeVarint32FiveBytes(value);
}
}
private void writeVarint32OneByte(int value) {
buffer.put(pos--, (byte) value);
}
private void writeVarint32TwoBytes(int value) {
// Byte order is little-endian.
pos -= 2;
buffer.putShort(pos + 1, (short) (((value & (0x7F << 7)) << 1) | ((value & 0x7F) | 0x80)));
}
private void writeVarint32ThreeBytes(int value) {
// Byte order is little-endian.
pos -= 3;
buffer.putInt(
pos,
((value & (0x7F << 14)) << 10)
| (((value & (0x7F << 7)) | (0x80 << 7)) << 9)
| ((value & 0x7F) | 0x80) << 8);
}
private void writeVarint32FourBytes(int value) {
// Byte order is little-endian.
pos -= 4;
buffer.putInt(
pos + 1,
((value & (0x7F << 21)) << 3)
| (((value & (0x7F << 14)) | (0x80 << 14)) << 2)
| (((value & (0x7F << 7)) | (0x80 << 7)) << 1)
| ((value & 0x7F) | 0x80));
}
private void writeVarint32FiveBytes(int value) {
// Byte order is little-endian.
buffer.put(pos--, (byte) (value >>> 28));
pos -= 4;
buffer.putInt(
pos + 1,
((((value >>> 21) & 0x7F) | 0x80) << 24)
| ((((value >>> 14) & 0x7F) | 0x80) << 16)
| ((((value >>> 7) & 0x7F) | 0x80) << 8)
| ((value & 0x7F) | 0x80));
}
@Override
void writeVarint64(long value) {
switch (computeUInt64SizeNoTag(value)) {
case 1:
writeVarint64OneByte(value);
break;
case 2:
writeVarint64TwoBytes(value);
break;
case 3:
writeVarint64ThreeBytes(value);
break;
case 4:
writeVarint64FourBytes(value);
break;
case 5:
writeVarint64FiveBytes(value);
break;
case 6:
writeVarint64SixBytes(value);
break;
case 7:
writeVarint64SevenBytes(value);
break;
case 8:
writeVarint64EightBytes(value);
break;
case 9:
writeVarint64NineBytes(value);
break;
case 10:
writeVarint64TenBytes(value);
break;
}
}
private void writeVarint64OneByte(long value) {
writeVarint32OneByte((int) value);
}
private void writeVarint64TwoBytes(long value) {
writeVarint32TwoBytes((int) value);
}
private void writeVarint64ThreeBytes(long value) {
writeVarint32ThreeBytes((int) value);
}
private void writeVarint64FourBytes(long value) {
writeVarint32FourBytes((int) value);
}
private void writeVarint64FiveBytes(long value) {
// Byte order is little-endian.
pos -= 5;
buffer.putLong(
pos - 2,
((value & (0x7FL << 28)) << 28)
| (((value & (0x7F << 21)) | (0x80 << 21)) << 27)
| (((value & (0x7F << 14)) | (0x80 << 14)) << 26)
| (((value & (0x7F << 7)) | (0x80 << 7)) << 25)
| (((value & 0x7F) | 0x80)) << 24);
}
private void writeVarint64SixBytes(long value) {
// Byte order is little-endian.
pos -= 6;
buffer.putLong(
pos - 1,
((value & (0x7FL << 35)) << 21)
| (((value & (0x7FL << 28)) | (0x80L << 28)) << 20)
| (((value & (0x7F << 21)) | (0x80 << 21)) << 19)
| (((value & (0x7F << 14)) | (0x80 << 14)) << 18)
| (((value & (0x7F << 7)) | (0x80 << 7)) << 17)
| (((value & 0x7F) | 0x80)) << 16);
}
private void writeVarint64SevenBytes(long value) {
// Byte order is little-endian.
pos -= 7;
buffer.putLong(
pos,
((value & (0x7FL << 42)) << 14)
| (((value & (0x7FL << 35)) | (0x80L << 35)) << 13)
| (((value & (0x7FL << 28)) | (0x80L << 28)) << 12)
| (((value & (0x7F << 21)) | (0x80 << 21)) << 11)
| (((value & (0x7F << 14)) | (0x80 << 14)) << 10)
| (((value & (0x7F << 7)) | (0x80 << 7)) << 9)
| (((value & 0x7F) | 0x80)) << 8);
}
private void writeVarint64EightBytes(long value) {
// Byte order is little-endian.
pos -= 8;
buffer.putLong(
pos + 1,
((value & (0x7FL << 49)) << 7)
| (((value & (0x7FL << 42)) | (0x80L << 42)) << 6)
| (((value & (0x7FL << 35)) | (0x80L << 35)) << 5)
| (((value & (0x7FL << 28)) | (0x80L << 28)) << 4)
| (((value & (0x7F << 21)) | (0x80 << 21)) << 3)
| (((value & (0x7F << 14)) | (0x80 << 14)) << 2)
| (((value & (0x7F << 7)) | (0x80 << 7)) << 1)
| ((value & 0x7F) | 0x80));
}
private void writeVarint64EightBytesWithSign(long value) {
// Byte order is little-endian.
pos -= 8;
buffer.putLong(
pos + 1,
(((value & (0x7FL << 49)) | (0x80L << 49)) << 7)
| (((value & (0x7FL << 42)) | (0x80L << 42)) << 6)
| (((value & (0x7FL << 35)) | (0x80L << 35)) << 5)
| (((value & (0x7FL << 28)) | (0x80L << 28)) << 4)
| (((value & (0x7F << 21)) | (0x80 << 21)) << 3)
| (((value & (0x7F << 14)) | (0x80 << 14)) << 2)
| (((value & (0x7F << 7)) | (0x80 << 7)) << 1)
| ((value & 0x7F) | 0x80));
}
private void writeVarint64NineBytes(long value) {
buffer.put(pos--, (byte) (value >>> 56));
writeVarint64EightBytesWithSign(value & 0xFFFFFFFFFFFFFFL);
}
private void writeVarint64TenBytes(long value) {
buffer.put(pos--, (byte) (value >>> 63));
buffer.put(pos--, (byte) (((value >>> 56) & 0x7F) | 0x80));
writeVarint64EightBytesWithSign(value & 0xFFFFFFFFFFFFFFL);
}
@Override
void writeFixed32(int value) {
pos -= 4;
buffer.putInt(pos + 1, value);
}
@Override
void writeFixed64(long value) {
pos -= 8;
buffer.putLong(pos + 1, value);
}
@Override
void writeString(String in) {
// Request enough space to write the ASCII string.
requireSpace(in.length());
// We know the buffer is big enough...
int i = in.length() - 1;
pos -= i;
// Designed to take advantage of
// https://wiki.openjdk.java.net/display/HotSpotInternals/RangeCheckElimination
for (char c; i >= 0 && (c = in.charAt(i)) < 0x80; i--) {
buffer.put(pos + i, (byte) c);
}
if (i == -1) {
// Move the position past the ASCII string.
pos -= 1;
return;
}
pos += i;
for (char c; i >= 0; i--) {
c = in.charAt(i);
if (c < 0x80 && pos >= 0) {
buffer.put(pos--, (byte) c);
} else if (c < 0x800 && pos > 0) { // 11 bits, two UTF-8 bytes
buffer.put(pos--, (byte) (0x80 | (0x3F & c)));
buffer.put(pos--, (byte) ((0xF << 6) | (c >>> 6)));
} else if ((c < Character.MIN_SURROGATE || Character.MAX_SURROGATE < c) && pos > 1) {
// Maximum single-char code point is 0xFFFF, 16 bits, three UTF-8 bytes
buffer.put(pos--, (byte) (0x80 | (0x3F & c)));
buffer.put(pos--, (byte) (0x80 | (0x3F & (c >>> 6))));
buffer.put(pos--, (byte) ((0xF << 5) | (c >>> 12)));
} else if (pos > 2) {
// Minimum code point represented by a surrogate pair is 0x10000, 17 bits,
// four UTF-8 bytes
char high = 0;
if (i == 0 || !Character.isSurrogatePair(high = in.charAt(i - 1), c)) {
throw new Utf8.UnpairedSurrogateException(i - 1, i);
}
i--;
int codePoint = Character.toCodePoint(high, c);
buffer.put(pos--, (byte) (0x80 | (0x3F & codePoint)));
buffer.put(pos--, (byte) (0x80 | (0x3F & (codePoint >>> 6))));
buffer.put(pos--, (byte) (0x80 | (0x3F & (codePoint >>> 12))));
buffer.put(pos--, (byte) ((0xF << 4) | (codePoint >>> 18)));
} else {
// Buffer is full - allocate a new one and revisit the current character.
requireSpace(i);
i++;
}
}
}
@Override
public void write(byte value) {
buffer.put(pos--, value);
}
@Override
public void write(byte[] value, int offset, int length) {
if (spaceLeft() < length) {
nextBuffer(length);
}
pos -= length;
Java8Compatibility.position(buffer, pos + 1);
buffer.put(value, offset, length);
}
@Override
public void writeLazy(byte[] value, int offset, int length) {
if (spaceLeft() < length) {
// We consider the value to be immutable (likely the internals of a ByteString). Just
// wrap it in a Netty buffer and add it to the output buffer.
totalDoneBytes += length;
buffers.addFirst(AllocatedBuffer.wrap(value, offset, length));
// Advance the writer to the next buffer.
// TODO: Consider slicing if space available above some threshold.
nextBuffer();
return;
}
pos -= length;
Java8Compatibility.position(buffer, pos + 1);
buffer.put(value, offset, length);
}
@Override
public void write(ByteBuffer value) {
int length = value.remaining();
if (spaceLeft() < length) {
nextBuffer(length);
}
pos -= length;
Java8Compatibility.position(buffer, pos + 1);
buffer.put(value);
}
@Override
public void writeLazy(ByteBuffer value) {
int length = value.remaining();
if (spaceLeft() < length) {
// We consider the value to be immutable (likely the internals of a ByteString). Just
// wrap it in a Netty buffer and add it to the output buffer.
totalDoneBytes += length;
buffers.addFirst(AllocatedBuffer.wrap(value));
// Advance the writer to the next buffer.
// TODO: Consider slicing if space available above some threshold.
nextBuffer();
return;
}
pos -= length;
Java8Compatibility.position(buffer, pos + 1);
buffer.put(value);
}
@Override
void requireSpace(int size) {
if (spaceLeft() < size) {
nextBuffer(size);
}
}
}
/** Writer that uses unsafe operations on a target {@link ByteBuffer}. */
private static final class UnsafeDirectWriter extends BinaryWriter {
private ByteBuffer buffer;
private long bufferOffset;
private long limitMinusOne;
private long pos;
UnsafeDirectWriter(BufferAllocator alloc, int chunkSize) {
super(alloc, chunkSize);
nextBuffer();
}
/** Indicates whether the required unsafe operations are supported on this platform. */
private static boolean isSupported() {
return UnsafeUtil.hasUnsafeByteBufferOperations();
}
private void nextBuffer() {
nextBuffer(newDirectBuffer());
}
private void nextBuffer(int capacity) {
nextBuffer(newDirectBuffer(capacity));
}
private void nextBuffer(AllocatedBuffer allocatedBuffer) {
if (!allocatedBuffer.hasNioBuffer()) {
throw new RuntimeException("Allocated buffer does not have NIO buffer");
}
ByteBuffer nioBuffer = allocatedBuffer.nioBuffer();
if (!nioBuffer.isDirect()) {
throw new RuntimeException("Allocator returned non-direct buffer");
}
finishCurrentBuffer();
buffers.addFirst(allocatedBuffer);
buffer = nioBuffer;
Java8Compatibility.limit(buffer, buffer.capacity());
Java8Compatibility.position(buffer, 0);
bufferOffset = UnsafeUtil.addressOffset(buffer);
limitMinusOne = bufferOffset + (buffer.limit() - 1);
pos = limitMinusOne;
}
@Override
public int getTotalBytesWritten() {
return totalDoneBytes + bytesWrittenToCurrentBuffer();
}
private int bytesWrittenToCurrentBuffer() {
return (int) (limitMinusOne - pos);
}
private int spaceLeft() {
return bufferPos() + 1;
}
@Override
void finishCurrentBuffer() {
if (buffer != null) {
totalDoneBytes += bytesWrittenToCurrentBuffer();
// Update the indices on the netty buffer.
Java8Compatibility.position(buffer, bufferPos() + 1);
buffer = null;
pos = 0;
limitMinusOne = 0;
}
}
private int bufferPos() {
return (int) (pos - bufferOffset);
}
@Override
public void writeUInt32(int fieldNumber, int value) {
requireSpace(MAX_VARINT32_SIZE * 2);
writeVarint32(value);
writeTag(fieldNumber, WIRETYPE_VARINT);
}
@Override
public void writeInt32(int fieldNumber, int value) {
requireSpace(MAX_VARINT32_SIZE + MAX_VARINT64_SIZE);
writeInt32(value);
writeTag(fieldNumber, WIRETYPE_VARINT);
}
@Override
public void writeSInt32(int fieldNumber, int value) {
requireSpace(MAX_VARINT32_SIZE * 2);
writeSInt32(value);
writeTag(fieldNumber, WIRETYPE_VARINT);
}
@Override
public void writeFixed32(int fieldNumber, int value) {
requireSpace(MAX_VARINT32_SIZE + FIXED32_SIZE);
writeFixed32(value);
writeTag(fieldNumber, WIRETYPE_FIXED32);
}
@Override
public void writeUInt64(int fieldNumber, long value) {
requireSpace(MAX_VARINT32_SIZE + MAX_VARINT64_SIZE);
writeVarint64(value);
writeTag(fieldNumber, WIRETYPE_VARINT);
}
@Override
public void writeSInt64(int fieldNumber, long value) {
requireSpace(MAX_VARINT32_SIZE + MAX_VARINT64_SIZE);
writeSInt64(value);
writeTag(fieldNumber, WIRETYPE_VARINT);
}
@Override
public void writeFixed64(int fieldNumber, long value) {
requireSpace(MAX_VARINT32_SIZE + FIXED64_SIZE);
writeFixed64(value);
writeTag(fieldNumber, WIRETYPE_FIXED64);
}
@Override
public void writeBool(int fieldNumber, boolean value) {
requireSpace(MAX_VARINT32_SIZE + 1);
write((byte) (value ? 1 : 0));
writeTag(fieldNumber, WIRETYPE_VARINT);
}
@Override
public void writeString(int fieldNumber, String value) {
int prevBytes = getTotalBytesWritten();
writeString(value);
int length = getTotalBytesWritten() - prevBytes;
requireSpace(2 * MAX_VARINT32_SIZE);
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
}
@Override
public void writeBytes(int fieldNumber, ByteString value) {
try {
value.writeToReverse(this);
} catch (IOException e) {
// Should never happen since the writer does not throw.
throw new RuntimeException(e);
}
requireSpace(MAX_VARINT32_SIZE * 2);
writeVarint32(value.size());
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
}
@Override
public void writeMessage(int fieldNumber, Object value) throws IOException {
int prevBytes = getTotalBytesWritten();
Protobuf.getInstance().writeTo(value, this);
int length = getTotalBytesWritten() - prevBytes;
requireSpace(MAX_VARINT32_SIZE * 2);
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
}
@Override
public void writeMessage(int fieldNumber, Object value, Schema schema) throws IOException {
int prevBytes = getTotalBytesWritten();
schema.writeTo(value, this);
int length = getTotalBytesWritten() - prevBytes;
requireSpace(MAX_VARINT32_SIZE * 2);
writeVarint32(length);
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
}
@Override
public void writeGroup(int fieldNumber, Object value) throws IOException {
writeTag(fieldNumber, WIRETYPE_END_GROUP);
Protobuf.getInstance().writeTo(value, this);
writeTag(fieldNumber, WIRETYPE_START_GROUP);
}
@Override
public void writeGroup(int fieldNumber, Object value, Schema schema) throws IOException {
writeTag(fieldNumber, WIRETYPE_END_GROUP);
schema.writeTo(value, this);
writeTag(fieldNumber, WIRETYPE_START_GROUP);
}
@Deprecated
@Override
public void writeStartGroup(int fieldNumber) {
writeTag(fieldNumber, WIRETYPE_START_GROUP);
}
@Deprecated
@Override
public void writeEndGroup(int fieldNumber) {
writeTag(fieldNumber, WIRETYPE_END_GROUP);
}
@Override
void writeInt32(int value) {
if (value >= 0) {
writeVarint32(value);
} else {
writeVarint64(value);
}
}
@Override
void writeSInt32(int value) {
writeVarint32(CodedOutputStream.encodeZigZag32(value));
}
@Override
void writeSInt64(long value) {
writeVarint64(CodedOutputStream.encodeZigZag64(value));
}
@Override
void writeBool(boolean value) {
write((byte) (value ? 1 : 0));
}
@Override
void writeTag(int fieldNumber, int wireType) {
writeVarint32(WireFormat.makeTag(fieldNumber, wireType));
}
@Override
void writeVarint32(int value) {
if ((value & (~0 << 7)) == 0) {
writeVarint32OneByte(value);
} else if ((value & (~0 << 14)) == 0) {
writeVarint32TwoBytes(value);
} else if ((value & (~0 << 21)) == 0) {
writeVarint32ThreeBytes(value);
} else if ((value & (~0 << 28)) == 0) {
writeVarint32FourBytes(value);
} else {
writeVarint32FiveBytes(value);
}
}
private void writeVarint32OneByte(int value) {
UnsafeUtil.putByte(pos--, (byte) value);
}
private void writeVarint32TwoBytes(int value) {
UnsafeUtil.putByte(pos--, (byte) (value >>> 7));
UnsafeUtil.putByte(pos--, (byte) ((value & 0x7F) | 0x80));
}
private void writeVarint32ThreeBytes(int value) {
UnsafeUtil.putByte(pos--, (byte) (value >>> 14));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 7) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) ((value & 0x7F) | 0x80));
}
private void writeVarint32FourBytes(int value) {
UnsafeUtil.putByte(pos--, (byte) (value >>> 21));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 14) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 7) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) ((value & 0x7F) | 0x80));
}
private void writeVarint32FiveBytes(int value) {
UnsafeUtil.putByte(pos--, (byte) (value >>> 28));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 21) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 14) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 7) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) ((value & 0x7F) | 0x80));
}
@Override
void writeVarint64(long value) {
switch (computeUInt64SizeNoTag(value)) {
case 1:
writeVarint64OneByte(value);
break;
case 2:
writeVarint64TwoBytes(value);
break;
case 3:
writeVarint64ThreeBytes(value);
break;
case 4:
writeVarint64FourBytes(value);
break;
case 5:
writeVarint64FiveBytes(value);
break;
case 6:
writeVarint64SixBytes(value);
break;
case 7:
writeVarint64SevenBytes(value);
break;
case 8:
writeVarint64EightBytes(value);
break;
case 9:
writeVarint64NineBytes(value);
break;
case 10:
writeVarint64TenBytes(value);
break;
}
}
private void writeVarint64OneByte(long value) {
UnsafeUtil.putByte(pos--, (byte) value);
}
private void writeVarint64TwoBytes(long value) {
UnsafeUtil.putByte(pos--, (byte) (value >>> 7));
UnsafeUtil.putByte(pos--, (byte) (((int) value & 0x7F) | 0x80));
}
private void writeVarint64ThreeBytes(long value) {
UnsafeUtil.putByte(pos--, (byte) (((int) value) >>> 14));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 7) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) ((value & 0x7F) | 0x80));
}
private void writeVarint64FourBytes(long value) {
UnsafeUtil.putByte(pos--, (byte) (value >>> 21));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 14) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 7) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) ((value & 0x7F) | 0x80));
}
private void writeVarint64FiveBytes(long value) {
UnsafeUtil.putByte(pos--, (byte) (value >>> 28));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 21) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 14) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 7) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) ((value & 0x7F) | 0x80));
}
private void writeVarint64SixBytes(long value) {
UnsafeUtil.putByte(pos--, (byte) (value >>> 35));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 28) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 21) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 14) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 7) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) ((value & 0x7F) | 0x80));
}
private void writeVarint64SevenBytes(long value) {
UnsafeUtil.putByte(pos--, (byte) (value >>> 42));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 35) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 28) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 21) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 14) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 7) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) ((value & 0x7F) | 0x80));
}
private void writeVarint64EightBytes(long value) {
UnsafeUtil.putByte(pos--, (byte) (value >>> 49));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 42) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 35) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 28) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 21) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 14) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 7) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) ((value & 0x7F) | 0x80));
}
private void writeVarint64NineBytes(long value) {
UnsafeUtil.putByte(pos--, (byte) (value >>> 56));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 49) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 42) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 35) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 28) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 21) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 14) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 7) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) ((value & 0x7F) | 0x80));
}
private void writeVarint64TenBytes(long value) {
UnsafeUtil.putByte(pos--, (byte) (value >>> 63));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 56) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 49) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 42) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 35) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 28) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 21) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 14) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) (((value >>> 7) & 0x7F) | 0x80));
UnsafeUtil.putByte(pos--, (byte) ((value & 0x7F) | 0x80));
}
@Override
void writeFixed32(int value) {
UnsafeUtil.putByte(pos--, (byte) ((value >> 24) & 0xFF));
UnsafeUtil.putByte(pos--, (byte) ((value >> 16) & 0xFF));
UnsafeUtil.putByte(pos--, (byte) ((value >> 8) & 0xFF));
UnsafeUtil.putByte(pos--, (byte) (value & 0xFF));
}
@Override
void writeFixed64(long value) {
UnsafeUtil.putByte(pos--, (byte) ((int) (value >> 56) & 0xFF));
UnsafeUtil.putByte(pos--, (byte) ((int) (value >> 48) & 0xFF));
UnsafeUtil.putByte(pos--, (byte) ((int) (value >> 40) & 0xFF));
UnsafeUtil.putByte(pos--, (byte) ((int) (value >> 32) & 0xFF));
UnsafeUtil.putByte(pos--, (byte) ((int) (value >> 24) & 0xFF));
UnsafeUtil.putByte(pos--, (byte) ((int) (value >> 16) & 0xFF));
UnsafeUtil.putByte(pos--, (byte) ((int) (value >> 8) & 0xFF));
UnsafeUtil.putByte(pos--, (byte) ((int) (value) & 0xFF));
}
@Override
void writeString(String in) {
// Request enough space to write the ASCII string.
requireSpace(in.length());
// We know the buffer is big enough...
int i = in.length() - 1;
// Designed to take advantage of
// https://wiki.openjdk.java.net/display/HotSpotInternals/RangeCheckElimination
for (char c; i >= 0 && (c = in.charAt(i)) < 0x80; i--) {
UnsafeUtil.putByte(pos--, (byte) c);
}
if (i == -1) {
// ASCII.
return;
}
for (char c; i >= 0; i--) {
c = in.charAt(i);
if (c < 0x80 && pos >= bufferOffset) {
UnsafeUtil.putByte(pos--, (byte) c);
} else if (c < 0x800 && pos > bufferOffset) { // 11 bits, two UTF-8 bytes
UnsafeUtil.putByte(pos--, (byte) (0x80 | (0x3F & c)));
UnsafeUtil.putByte(pos--, (byte) ((0xF << 6) | (c >>> 6)));
} else if ((c < Character.MIN_SURROGATE || Character.MAX_SURROGATE < c)
&& pos > bufferOffset + 1) {
// Maximum single-char code point is 0xFFFF, 16 bits, three UTF-8 bytes
UnsafeUtil.putByte(pos--, (byte) (0x80 | (0x3F & c)));
UnsafeUtil.putByte(pos--, (byte) (0x80 | (0x3F & (c >>> 6))));
UnsafeUtil.putByte(pos--, (byte) ((0xF << 5) | (c >>> 12)));
} else if (pos > bufferOffset + 2) {
// Minimum code point represented by a surrogate pair is 0x10000, 17 bits,
// four UTF-8 bytes
final char high;
if (i == 0 || !Character.isSurrogatePair(high = in.charAt(i - 1), c)) {
throw new Utf8.UnpairedSurrogateException(i - 1, i);
}
i--;
int codePoint = Character.toCodePoint(high, c);
UnsafeUtil.putByte(pos--, (byte) (0x80 | (0x3F & codePoint)));
UnsafeUtil.putByte(pos--, (byte) (0x80 | (0x3F & (codePoint >>> 6))));
UnsafeUtil.putByte(pos--, (byte) (0x80 | (0x3F & (codePoint >>> 12))));
UnsafeUtil.putByte(pos--, (byte) ((0xF << 4) | (codePoint >>> 18)));
} else {
// Buffer is full - allocate a new one and revisit the current character.
requireSpace(i);
i++;
}
}
}
@Override
public void write(byte value) {
UnsafeUtil.putByte(pos--, value);
}
@Override
public void write(byte[] value, int offset, int length) {
if (spaceLeft() < length) {
nextBuffer(length);
}
pos -= length;
Java8Compatibility.position(buffer, bufferPos() + 1);
buffer.put(value, offset, length);
}
@Override
public void writeLazy(byte[] value, int offset, int length) {
if (spaceLeft() < length) {
// We consider the value to be immutable (likely the internals of a ByteString). Just
// wrap it in a Netty buffer and add it to the output buffer.
totalDoneBytes += length;
buffers.addFirst(AllocatedBuffer.wrap(value, offset, length));
// Advance the writer to the next buffer.
// TODO: Consider slicing if space available above some threshold.
nextBuffer();
return;
}
pos -= length;
Java8Compatibility.position(buffer, bufferPos() + 1);
buffer.put(value, offset, length);
}
@Override
public void write(ByteBuffer value) {
int length = value.remaining();
if (spaceLeft() < length) {
nextBuffer(length);
}
pos -= length;
Java8Compatibility.position(buffer, bufferPos() + 1);
buffer.put(value);
}
@Override
public void writeLazy(ByteBuffer value) {
int length = value.remaining();
if (spaceLeft() < length) {
// We consider the value to be immutable (likely the internals of a ByteString). Just
// wrap it in a Netty buffer and add it to the output buffer.
totalDoneBytes += length;
buffers.addFirst(AllocatedBuffer.wrap(value));
// Advance the writer to the next buffer.
// TODO: Consider slicing if space available above some threshold.
nextBuffer();
return;
}
pos -= length;
Java8Compatibility.position(buffer, bufferPos() + 1);
buffer.put(value);
}
@Override
void requireSpace(int size) {
if (spaceLeft() < size) {
nextBuffer(size);
}
}
}
}
| protocolbuffers/protobuf | java/core/src/main/java/com/google/protobuf/BinaryWriter.java |
2,765 | /*
* Zinc - The incremental compiler for Scala.
* Copyright Scala Center, Lightbend, and Mark Harrah
*
* Scala (https://www.scala-lang.org)
* Copyright EPFL and Lightbend, Inc.
*
* Licensed under Apache License 2.0
* (http://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/
package scala.tools.xsbt;
import scala.tools.nsc.Global;
public class ReflectAccess {
public static String compactifyName(Global g, String s) { return g.compactifyName(s); }
}
| scala/scala | src/sbt-bridge/scala/tools/xsbt/ReflectAccess.java |
2,766 | /*
* Copyright 2017 The Netty Project
*
* The Netty Project licenses this file to you 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:
*
* https://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 io.netty.microbenchmark.common;
import io.netty.microbench.util.AbstractMicrobenchmark;
import io.netty.util.NetUtil;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.annotations.Warmup;
import java.util.concurrent.TimeUnit;
@Threads(1)
@Warmup(iterations = 3)
@Measurement(iterations = 3)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public class IsValidIpV6Benchmark extends AbstractMicrobenchmark {
@Param({
"127.0.0.1", "fdf8:f53b:82e4::53", "2001::1",
"2001:0000:4136:e378:8000:63bf:3fff:fdd2", "0:0:0:0:0:0:10.0.0.1"
})
private String ip;
private static boolean isValidIp4Word(String word) {
char c;
if (word.length() < 1 || word.length() > 3) {
return false;
}
for (int i = 0; i < word.length(); i++) {
c = word.charAt(i);
if (!(c >= '0' && c <= '9')) {
return false;
}
}
return Integer.parseInt(word) <= 255;
}
private static boolean isValidHexChar(char c) {
return c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f';
}
private static boolean isValidIPv4MappedChar(char c) {
return c == 'f' || c == 'F';
}
public static boolean isValidIpV6AddressOld(String ipAddress) {
boolean doubleColon = false;
int numberOfColons = 0;
int numberOfPeriods = 0;
StringBuilder word = new StringBuilder();
char c = 0;
char prevChar;
int startOffset = 0; // offset for [] ip addresses
int endOffset = ipAddress.length();
if (endOffset < 2) {
return false;
}
// Strip []
if (ipAddress.charAt(0) == '[') {
if (ipAddress.charAt(endOffset - 1) != ']') {
return false; // must have a close ]
}
startOffset = 1;
endOffset--;
}
// Strip the interface name/index after the percent sign.
int percentIdx = ipAddress.indexOf('%', startOffset);
if (percentIdx >= 0) {
endOffset = percentIdx;
}
for (int i = startOffset; i < endOffset; i++) {
prevChar = c;
c = ipAddress.charAt(i);
switch (c) {
// case for the last 32-bits represented as IPv4 x:x:x:x:x:x:d.d.d.d
case '.':
numberOfPeriods++;
if (numberOfPeriods > 3) {
return false;
}
if (numberOfPeriods == 1) {
// Verify this address is of the correct structure to contain an IPv4 address.
// It must be IPv4-Mapped or IPv4-Compatible
// (see https://tools.ietf.org/html/rfc4291#section-2.5.5).
int j = i - word.length() - 2; // index of character before the previous ':'.
final int beginColonIndex = ipAddress.lastIndexOf(':', j);
if (beginColonIndex == -1) {
return false;
}
char tmpChar = ipAddress.charAt(j);
if (isValidIPv4MappedChar(tmpChar)) {
if (j - beginColonIndex != 4 ||
!isValidIPv4MappedChar(ipAddress.charAt(j - 1)) ||
!isValidIPv4MappedChar(ipAddress.charAt(j - 2)) ||
!isValidIPv4MappedChar(ipAddress.charAt(j - 3))) {
return false;
}
j -= 5;
} else if (tmpChar == '0' || tmpChar == ':') {
--j;
} else {
return false;
}
// a special case ::1:2:3:4:5:d.d.d.d allows 7 colons with an
// IPv4 ending, otherwise 7 :'s is bad
if ((numberOfColons != 6 && !doubleColon) || numberOfColons > 7 ||
(numberOfColons == 7 && (ipAddress.charAt(startOffset) != ':' ||
ipAddress.charAt(1 + startOffset) != ':'))) {
return false;
}
for (; j >= startOffset; --j) {
tmpChar = ipAddress.charAt(j);
if (tmpChar != '0' && tmpChar != ':') {
return false;
}
}
}
if (!isValidIp4Word(word.toString())) {
return false;
}
word.delete(0, word.length());
break;
case ':':
// FIX "IP6 mechanism syntax #ip6-bad1"
// An IPV6 address cannot start with a single ":".
// Either it can start with "::" or with a number.
if (i == startOffset && (endOffset <= i || ipAddress.charAt(i + 1) != ':')) {
return false;
}
// END FIX "IP6 mechanism syntax #ip6-bad1"
numberOfColons++;
if (numberOfColons > 8) {
return false;
}
if (numberOfPeriods > 0) {
return false;
}
if (prevChar == ':') {
if (doubleColon) {
return false;
}
doubleColon = true;
}
word.delete(0, word.length());
break;
default:
if (word != null && word.length() > 3) {
return false;
}
if (!isValidHexChar(c)) {
return false;
}
word.append(c);
}
}
// Check if we have an IPv4 ending
if (numberOfPeriods > 0) {
// There is a test case with 7 colons and valid ipv4 this should resolve it
return numberOfPeriods == 3 &&
(isValidIp4Word(word.toString()) && (numberOfColons < 7 || doubleColon));
} else {
// If we're at then end and we haven't had 7 colons then there is a
// problem unless we encountered a doubleColon
if (numberOfColons != 7 && !doubleColon) {
return false;
}
if (word.length() == 0) {
// If we have an empty word at the end, it means we ended in either
// a : or a .
// If we did not end in :: then this is invalid
return ipAddress.charAt(endOffset - 1) != ':' ||
ipAddress.charAt(endOffset - 2) == ':';
} else {
return numberOfColons != 8 || ipAddress.charAt(startOffset) == ':';
}
}
}
// Tests
@Benchmark
public boolean isValidIpV6AddressOld() {
return isValidIpV6AddressOld(ip);
}
@Benchmark
public boolean isValidIpV6AddressNew() {
return NetUtil.isValidIpV6Address(ip);
}
}
| netty/netty | microbench/src/main/java/io/netty/microbenchmark/common/IsValidIpV6Benchmark.java |
2,767 | // Copyright 2014 The Bazel Authors. All rights reserved.
//
// 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 com.google.devtools.build.skyframe;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.concurrent.ThreadSafety.ThreadSafe;
import com.google.devtools.build.skyframe.SkyFunction.Reset;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import javax.annotation.Nullable;
/**
* A node in the graph. All operations on this class are thread-safe.
*
* <p>This interface is public only for the benefit of alternative graph implementations outside of
* the package.
*
* <p>Certain graph implementations' node entries can throw {@link InterruptedException} on various
* accesses. Such exceptions should not be caught locally -- they should be allowed to propagate up.
*/
public interface NodeEntry {
/**
* Return code for {@link #addReverseDepAndCheckIfDone} and {@link
* #checkIfDoneForDirtyReverseDep}.
*/
enum DependencyState {
/** The node is done. */
DONE,
/**
* The node has not started evaluating, and needs to be scheduled for its first evaluation pass.
* The caller getting this return value is responsible for scheduling its evaluation and
* signaling the reverse dependency node when this node is done.
*/
NEEDS_SCHEDULING,
/**
* The node was already created, but isn't done yet. The evaluator is responsible for signaling
* the reverse dependency node.
*/
ALREADY_EVALUATING
}
/** Represents the various states in a node's lifecycle. */
enum LifecycleState {
/**
* The entry has never started evaluating. The next call to {@link #addReverseDepAndCheckIfDone}
* will put the entry into the {@link #NEEDS_REBUILDING} state and return {@link
* DependencyState#NEEDS_SCHEDULING}.
*/
NOT_YET_EVALUATING,
/**
* The node's dependencies need to be checked to see if it needs to be rebuilt. The dependencies
* must be obtained through calls to {@link #getNextDirtyDirectDeps} and checked.
*/
CHECK_DEPENDENCIES,
/**
* All of the node's dependencies are unchanged, and the value itself was not marked changed, so
* its current value is still valid -- it need not be rebuilt.
*/
VERIFIED_CLEAN,
/**
* A rebuilding is required for one of the following reasons:
*
* <ol>
* <li>One of the node's dependencies changed.
* <li>The node is built by a {@link FunctionHermeticity#NONHERMETIC} function and its value
* is known to have changed due to state outside of Skyframe.
* <li>The node was {@linkplain DirtyType#REWIND rewound}.
* </ol>
*/
NEEDS_REBUILDING,
/** A rebuilding is in progress. */
REBUILDING,
/** The node {@link #isDone}. */
DONE,
}
/** Ways that a node may be dirtied. */
enum DirtyType {
/**
* Indicates that the node is being marked dirty because it has a dependency that was marked
* dirty.
*
* <p>A node P dirtied with {@code DIRTY} is re-evaluated during the evaluation phase if it is
* requested and directly depends on some node C whose value changed since the last evaluation
* of P. If it is requested and there is no such node C, P is {@linkplain #markClean marked
* clean}.
*/
DIRTY,
/**
* Indicates that the node is being marked dirty because its value from a previous evaluation is
* no longer valid, even if none of its dependencies change.
*
* <p>This is typically used to indicate that a value produced by a {@link
* FunctionHermeticity#NONHERMETIC} function is no longer valid because some state outside of
* Skyframe has changed (e.g. a change to the filesystem).
*
* <p>A node dirtied with {@code CHANGE} is re-evaluated during the evaluation phase if it is
* requested, regardless of the state of its dependencies. If it re-evaluates to the same value,
* dirty parents are not necessarily re-evaluated.
*/
CHANGE,
/**
* Similar to {@link #CHANGE} except may be used intra-evaluation to indicate that the node's
* value (which may be from either a previous evaluation or the current evaluation) is no longer
* valid.
*
* <p>A node dirtied with {@code REWIND} is re-evaluated during the evaluation phase if it is
* requested, regardless of the state of its dependencies. Even if it re-evaluates to the same
* value, dirty parents are re-evaluated.
*
* <p>Rewinding is tolerated but no-op if the node is already dirty or is done with an
* {@linkplain #getErrorInfo() error} (regardless of the error's {@link
* com.google.devtools.build.skyframe.SkyFunctionException.Transience}).
*/
REWIND
}
/** Returns whether the entry has been built and is finished evaluating. */
@ThreadSafe
boolean isDone();
/** Inverse of {@link #isDone}. */
@ThreadSafe
boolean isDirty();
/**
* Returns true if the entry is marked changed, meaning that it must be re-evaluated even if its
* dependencies' values have not changed.
*/
@ThreadSafe
boolean isChanged();
/**
* Marks this node dirty as specified by the provided {@link DirtyType}.
*
* <p>{@code markDirty(DirtyType.DIRTY)} may only be called on a node P for which {@code
* P.isDone() || P.isChanged()} (the latter is permitted but has no effect). Similarly, {@code
* markDirty(DirtyType.CHANGE)} may only be called on a node P for which {@code P.isDone() ||
* !P.isChanged()}. Otherwise, this will throw {@link IllegalStateException}.
*
* <p>{@code markDirty(DirtyType.REWIND)} may be called at any time (even multiple times
* concurrently), although it only has an effect if the node {@link #isDone} with no error.
*
* @return if the node transitioned from done to dirty as a result of this call, a {@link
* MarkedDirtyResult} which may include the node's reverse deps; otherwise {@code null}
*/
@Nullable
@ThreadSafe
MarkedDirtyResult markDirty(DirtyType dirtyType) throws InterruptedException;
/**
* Returned by {@link #markDirty} if that call changed the node from done to dirty.
*
* <p>For nodes marked dirty during invalidation ({@link DirtyType#DIRTY} and {@link
* DirtyType#CHANGE}), contains a {@link Collection} of the node's reverse deps for efficiency, so
* that the invalidator can schedule the invalidation of a node's reverse deps immediately
* afterwards.
*
* <p>For nodes marked dirty intra-evaluation ({@link DirtyType#REWIND}), reverse deps are not
* needed by the caller, so {@link #getReverseDepsUnsafe} must not be called.
*
* <p>Warning: {@link #getReverseDepsUnsafe()} may return a live view of the reverse deps
* collection of the marked-dirty node. The consumer of this data must be careful only to iterate
* over and consume its values while that collection is guaranteed not to change. This is true
* during invalidation, because reverse deps don't change during invalidation.
*/
abstract class MarkedDirtyResult {
private static final MarkedDirtyResult RESULT_FOR_REWINDING =
new MarkedDirtyResult() {
@Override
public Collection<SkyKey> getReverseDepsUnsafe() {
throw new IllegalStateException("Should not need reverse deps for rewinding");
}
};
public static MarkedDirtyResult withReverseDeps(Collection<SkyKey> reverseDepsUnsafe) {
return new ResultWithReverseDeps(reverseDepsUnsafe);
}
static MarkedDirtyResult forRewinding() {
return RESULT_FOR_REWINDING;
}
private MarkedDirtyResult() {}
public abstract Collection<SkyKey> getReverseDepsUnsafe();
private static final class ResultWithReverseDeps extends MarkedDirtyResult {
private final Collection<SkyKey> reverseDepsUnsafe;
private ResultWithReverseDeps(Collection<SkyKey> reverseDepsUnsafe) {
this.reverseDepsUnsafe = checkNotNull(reverseDepsUnsafe);
}
@Override
public Collection<SkyKey> getReverseDepsUnsafe() {
return reverseDepsUnsafe;
}
}
}
/**
* Returns the value stored in this entry, or {@code null} if it has only an error.
*
* <p>This method may only be called when the node {@link #isDone}.
*/
@ThreadSafe
@Nullable
SkyValue getValue() throws InterruptedException;
/**
* Returns an immutable iterable of the direct deps of this node. This method may only be called
* after the evaluation of this node is complete.
*
* <p>This method is not very efficient, but is only be called in limited circumstances -- when
* the node is about to be deleted, or when the node is expected to have no direct deps (in which
* case the overhead is not so bad). It should not be called repeatedly for the same node, since
* each call takes time proportional to the number of direct deps of the node.
*/
@ThreadSafe
Iterable<SkyKey> getDirectDeps() throws InterruptedException;
/**
* Returns {@code true} if this node has at least one direct dep.
*
* <p>Prefer calling this over {@link #getDirectDeps} if possible.
*
* <p>This method may only be called after the evaluation of this node is complete.
*/
@ThreadSafe
boolean hasAtLeastOneDep() throws InterruptedException;
/** Removes a reverse dependency, which must be present. */
@ThreadSafe
void removeReverseDep(SkyKey reverseDep) throws InterruptedException;
/**
* Removes any reverse dependencies that are in {@code deletedKeys}. Must only be called from an
* invalidation that is deleting nodes from the graph. Sacrifices correctness checks (that the
* deleted rdeps were actually rdeps of this entry) for better performance.
*/
@ThreadSafe
void removeReverseDepsFromDoneEntryDueToDeletion(Set<SkyKey> deletedKeys);
/**
* Returns a copy of the set of reverse dependencies. Note that this introduces a potential
* check-then-act race; {@link #removeReverseDep} may fail for a key that is returned here.
*
* <p>May only be called on a done node entry.
*/
@ThreadSafe
Collection<SkyKey> getReverseDepsForDoneEntry() throws InterruptedException;
/**
* Returns raw {@link SkyValue} stored in this entry, which may include metadata associated with
* it (like events and errors).
*
* <p>This method returns {@code null} if the evaluation of this node is not complete, i.e., after
* node creation or dirtying and before {@link #setValue} has been called. Callers should assert
* that the returned value is not {@code null} whenever they expect the node should be done.
*
* <p>Use the static methods of {@link ValueWithMetadata} to extract metadata if necessary.
*/
@ThreadSafe
@Nullable
SkyValue getValueMaybeWithMetadata() throws InterruptedException;
/**
* Returns the last known value of this node, even if it was {@linkplain #markDirty marked dirty}.
*
* <p>If this node {@link #isDone}, this is equivalent to {@link #getValue}. Unlike {@link
* #getValue}, however, this method may be called at any point in the node's lifecycle. Returns
* {@code null} if this node was never built or has no value because it is in error.
*/
@ThreadSafe
@Nullable
SkyValue toValue() throws InterruptedException;
/**
* Returns the error, if any, associated to this node. This method may only be called after the
* evaluation of this node is complete, i.e., after {@link #setValue} has been called.
*/
@Nullable
@ThreadSafe
ErrorInfo getErrorInfo() throws InterruptedException;
/**
* Returns the set of reverse deps that have been declared so far this build. Only for use in
* debugging and when bubbling errors up in the --nokeep_going case, where we need to know what
* parents this entry has.
*/
@ThreadSafe
Set<SkyKey> getInProgressReverseDeps();
/**
* Transitions the node from the EVALUATING to the DONE state and simultaneously sets it to the
* given value and error state. It then returns the set of reverse dependencies that need to be
* signaled.
*
* <p>This is an atomic operation to avoid a race where two threads work on two nodes, where one
* node depends on another (b depends on a). When a finishes, it signals <b>exactly</b> the set of
* reverse dependencies that are registered at the time of the {@code setValue} call. If b comes
* in before a, it is signaled (and re-scheduled) by a, otherwise it needs to do that itself.
*
* <p>Nodes may elect to use either {@code graphVersion} or {@code maxTransitiveSourceVersion} (if
* not {@code null}) for their {@linkplain #getVersion version}. The choice can be distinguished
* by calling {@link #getMaxTransitiveSourceVersion} - a return of {@code null} indicates that the
* node uses the graph version.
*
* <p>If the entry determines that the new value is equal to the previous value, the entry may
* keep its current version. Callers can query that version to see if the node considers its value
* to have changed.
*
* @param value the new value of this node
* @param graphVersion the version of the graph at which this node is being written
* @param maxTransitiveSourceVersion the maximal version of this node's dependencies from source,
* or {@code null} if source versions are not being tracked
*/
@ThreadSafe
Set<SkyKey> setValue(
SkyValue value, Version graphVersion, @Nullable Version maxTransitiveSourceVersion)
throws InterruptedException;
/**
* Sets the max transitive source version of this node so far while it is being evaluated. May
* only be called when {@link #isDirty()} is {@code true}.
*
* <p>This method helps to track the in-progress max transitive source version across Skyframe
* restarts. The eventual max transitive source version is set when {@link #setValue} is called.
*
* <p>This function is a no-op if source versions are not being tracked.
*/
default void setTemporaryMaxTransitiveSourceVersion(
@Nullable Version maxTransitiveSourceVersion) {}
/**
* Queries if the node is done and adds the given key as a reverse dependency. The return code
* indicates whether a) the node is done, b) the reverse dependency is the first one, so the node
* needs to be scheduled, or c) the reverse dependency was added, and the node does not need to be
* scheduled.
*
* <p>This method <b>must</b> be called before any processing of the entry. This encourages
* callers to check that the entry is ready to be processed.
*
* <p>Adding the dependency and checking if the node needs to be scheduled is an atomic operation
* to avoid a race where two threads work on two nodes, where one depends on the other (b depends
* on a). In that case, we need to ensure that b is re-scheduled exactly once when a is done.
* However, a may complete first, in which case b has to re-schedule itself. Also see {@link
* #setValue}.
*
* <p>If the parameter is {@code null}, then no reverse dependency is added, but we still check if
* the node needs to be scheduled.
*
* <p>If {@code reverseDep} is a rebuilding dirty entry that was already a reverse dep of this
* entry, then {@link #checkIfDoneForDirtyReverseDep} must be called instead.
*/
@ThreadSafe
DependencyState addReverseDepAndCheckIfDone(@Nullable SkyKey reverseDep)
throws InterruptedException;
/**
* Similar to {@link #addReverseDepAndCheckIfDone}, except that {@code reverseDep} must already be
* a reverse dep of this entry. Should be used when reverseDep has been marked dirty and is
* checking its dependencies for changes or is rebuilding. The caller must treat the return value
* just as they would the return value of {@link #addReverseDepAndCheckIfDone} by scheduling this
* node for evaluation if needed.
*/
@ThreadSafe
DependencyState checkIfDoneForDirtyReverseDep(SkyKey reverseDep) throws InterruptedException;
Collection<SkyKey> getAllReverseDepsForNodeBeingDeleted();
/**
* Tell this entry that one of its dependencies is now done. Callers must check the return value,
* and if true, they must re-schedule this node for evaluation.
*
* <p>Even if {@code childVersion} is not at most {@link #getVersion}, this entry may not rebuild,
* in the case that the entry already rebuilt at {@code childVersion} and discovered that it had
* the same value as at an earlier version. For instance, after evaluating at version v1, at
* version v2, child has a new value, but parent re-evaluates and finds it has the same value,
* child.getVersion() will return v2 and parent.getVersion() will return v1. At v3 parent is
* dirtied and checks its dep on child. child signals parent with version v2. That should not in
* and of itself trigger a rebuild, since parent has already rebuilt with child at v2.
*
* @param childVersion If this entry {@link #isDirty} and the last version at which this entry was
* evaluated did not include the changes at version {@code childVersion} (for instance, if
* {@code childVersion} is after the last version at which this entry was evaluated), then
* this entry records that one of its children has changed since it was last evaluated. Thus,
* the next call to {@link #getLifecycleState} will return {@link
* LifecycleState#NEEDS_REBUILDING}.
* @param childForDebugging for use in debugging (can be used to identify specific children that
* invalidate this node)
*/
@ThreadSafe
boolean signalDep(Version childVersion, @Nullable SkyKey childForDebugging);
/**
* Marks this entry as up-to-date at this version.
*
* @return {@link NodeValueAndRdepsToSignal} containing the SkyValue and reverse deps to signal.
*/
@ThreadSafe
NodeValueAndRdepsToSignal markClean() throws InterruptedException;
/**
* Returned by {@link #markClean} after making a node as clean. This is an aggregate object that
* contains the NodeEntry's SkyValue and its reverse dependencies that signal this node is done (a
* subset of all of the node's reverse dependencies).
*/
final class NodeValueAndRdepsToSignal {
private final SkyValue value;
private final Set<SkyKey> rDepsToSignal;
public NodeValueAndRdepsToSignal(SkyValue value, Set<SkyKey> rDepsToSignal) {
this.value = value;
this.rDepsToSignal = rDepsToSignal;
}
SkyValue getValue() {
return this.value;
}
Set<SkyKey> getRdepsToSignal() {
return this.rDepsToSignal;
}
}
/**
* Called on a dirty node during {@linkplain LifecycleState#CHECK_DEPENDENCIES dependency
* checking} to force the node to be re-evaluated, even if none of its dependencies are known to
* have changed.
*
* <p>Used when a caller has reason to believe that re-evaluating may yield a new result, such as
* when the prior evaluation encountered a transient error.
*/
@ThreadSafe
void forceRebuild();
/** Returns the current version of this node. */
@ThreadSafe
Version getVersion();
/**
* Returns the maximal version of this node's dependencies from source.
*
* <p>This version should only be tracked when non-hermetic functions {@linkplain
* SkyFunction.Environment#injectVersionForNonHermeticFunction inject} source versions. Otherwise,
* returns {@code null} to signal that source versions are not being tracked.
*/
@ThreadSafe
@Nullable
default Version getMaxTransitiveSourceVersion() {
return null;
}
/**
* Returns the state of this entry as enumerated by {@link LifecycleState}.
*
* <p>This method may be called at any time. Returns {@link LifecycleState#DONE} iff the node
* {@link #isDone}.
*/
@ThreadSafe
LifecycleState getLifecycleState();
/**
* Should only be called if the entry is in the {@link LifecycleState#CHECK_DEPENDENCIES} state.
* During the examination to see if the entry must be re-evaluated, this method returns the next
* group of children to be checked. Callers should have already called {@link #getLifecycleState}
* and received a return value of {@link LifecycleState#CHECK_DEPENDENCIES} before calling this
* method -- any other return value from {@link #getLifecycleState} means that this method must
* not be called, since whether or not the node needs to be rebuilt is already known.
*
* <p>Deps are returned in groups. The deps in each group were requested in parallel by the {@code
* SkyFunction} last build, meaning independently of the values of any other deps in this group
* (although possibly depending on deps in earlier groups). Thus the caller may check all the deps
* in this group in parallel, since the deps in all previous groups are verified unchanged. See
* {@link SkyFunction.Environment#getValuesAndExceptions} for more on dependency groups.
*
* @see DirtyBuildingState#getNextDirtyDirectDeps()
*/
@ThreadSafe
List<SkyKey> getNextDirtyDirectDeps() throws InterruptedException;
/**
* Returns all deps of a node that has not yet finished evaluating. In other words, if a node has
* a reverse dep on this node, its key will be in the returned set here.
*
* <p>The returned set is the union of:
*
* <ul>
* <li>This node's {@linkplain #getTemporaryDirectDeps temporary direct deps}.
* <li>Deps from a previous evaluation, if this this node was {@linkplain #markDirty marked
* dirty} (all the elements that would have been returned by successive calls to {@link
* #getNextDirtyDirectDeps} or, equivalently, one call to {@link
* #getAllRemainingDirtyDirectDeps}).
* <li>This node's {@linkplain #getResetDirectDeps reset direct deps}.
* </ul>
*
* <p>This method should only be called when this node is about to be deleted after an aborted
* evaluation. After such an evaluation, any nodes that did not finish evaluating are deleted, as
* are any nodes that depend on them, which are necessarily also not done. If this node is to be
* deleted because of this, we must delete it as a reverse dep from other nodes. This method
* returns that list of other nodes. This method may not be called on done nodes, since they do
* not need to be deleted after aborted evaluations.
*
* <p>This method must not be called twice: the next thing done to this node after this method is
* called should be the removal of the node from the graph.
*/
ImmutableSet<SkyKey> getAllDirectDepsForIncompleteNode() throws InterruptedException;
/**
* If an entry {@link #isDirty}, returns all direct deps that were present last build, but have
* not yet been verified to be present during the current build. Implementations may lazily remove
* these deps, since in many cases they will be added back during this build, even though the node
* may have a changed value. However, any elements of this returned set that have not been added
* back by the end of evaluation <i>must</i> be removed from any done nodes, in order to preserve
* graph consistency.
*
* <p>Returns the empty set if an entry is not dirty. In either case, the entry must already have
* started evaluation.
*
* <p>This method does not mutate the entry. In particular, multiple calls to this method will
* always produce the same result until the entry finishes evaluation. Contrast with {@link
* #getAllDirectDepsForIncompleteNode}.
*/
ImmutableSet<SkyKey> getAllRemainingDirtyDirectDeps() throws InterruptedException;
/**
* Notifies a node that it is about to be rebuilt. This method can only be called if the node
* {@link LifecycleState#NEEDS_REBUILDING}. After this call, this node is ready to be rebuilt (it
* will be in {@link LifecycleState#REBUILDING}).
*/
void markRebuilding();
/**
* Returns the {@link GroupedDeps} of direct dependencies. This may only be called while the node
* is being evaluated (i.e. before {@link #setValue} and after {@link #markDirty}.
*/
@ThreadSafe
GroupedDeps getTemporaryDirectDeps();
@ThreadSafe
boolean noDepsLastBuild();
/**
* Remove dep from direct deps. This should only be called if this entry is about to be committed
* as a cycle node, but some of its children were not checked for cycles, either because the cycle
* was discovered before some children were checked; some children didn't have a chance to finish
* before the evaluator aborted; or too many cycles were found when it came time to check the
* children.
*/
@ThreadSafe
void removeUnfinishedDeps(Set<SkyKey> unfinishedDeps);
/**
* Prepares this node to reset its evaluation from scratch in order to recover from an
* inconsistency.
*
* <p>Temporary direct deps should be cleared by this call, as they will be added again when
* requested during the restarted evaluation of this node. If the graph keeps dependency edges,
* however, the temporary direct deps must be accounted for in {@link #getResetDirectDeps}.
*
* <p>Called on a {@link LifecycleState#REBUILDING} node when one of the following scenarios is
* observed:
*
* <ol>
* <li>One or more already requested dependencies are not done. This may happen when a
* dependency's node was dropped from the graph to save memory, or if a dependency was
* {@linkplain DirtyType#REWIND rewound} by another node.
* <li>The corresponding {@link SkyFunction} for this node returned {@link Reset} to indicate
* that one or more dependencies were done but are in need of {@linkplain DirtyType#REWIND
* rewinding} to regenerate their values.
* </ol>
*
* <p>This method is similar to calling {@link #markDirty} with {@link DirtyType#REWIND} with an
* important distinction: rewinding is initiated on a <em>done</em> node because of an issue with
* its <em>value</em>, while this method is called on a <em>building</em> node because of an issue
* with a <em>dependency</em>. The dependency will be rewound if we are in scenario 2 above.
*
* <p>Reverse deps on the other hand should be preserved - parents waiting on this node are
* unaware that it is being restarted and will not register themselves again, yet they still need
* to be signaled when this node is done.
*/
@ThreadSafe
void resetEvaluationFromScratch();
/**
* If the graph keeps dependency edges and {@link #resetEvaluationFromScratch} has been called on
* this node since it was last done, returns the set of temporary direct deps that were registered
* prior to the restart. Otherwise, returns an empty set.
*
* <p>Called on a {@link LifecycleState#REBUILDING} node when it is about to finish evaluating.
* Used to determine which of its {@linkplain #getTemporaryDirectDeps temporary direct deps} have
* already registered a corresponding reverse dep, in order to avoid creating duplicate rdep
* edges.
*
* <p>Like {@link #getAllRemainingDirtyDirectDeps}, keys in the returned set are assumed to have
* already registered an rdep on this node. Unlike {@link #getAllRemainingDirtyDirectDeps},
* however, deps in the returned set may have only been registered at the current evaluation
* version, not a previous one.
*
* <p>If this node was reset multiple times since it was last done, must return deps requested
* prior to <em>any</em> of those restarts, not just the most recent one.
*/
@ThreadSafe
ImmutableSet<SkyKey> getResetDirectDeps();
/**
* Adds a temporary direct dep in its own group.
*
* <p>The given dep must not be present in this node's existing temporary direct deps.
*/
@ThreadSafe
void addSingletonTemporaryDirectDep(SkyKey dep);
/**
* Adds a temporary direct group.
*
* <p>The group must be duplicate-free and not contain any deps in common with this node's
* existing temporary direct deps.
*/
@ThreadSafe
void addTemporaryDirectDepGroup(List<SkyKey> group);
/**
* Adds temporary direct deps in groups.
*
* <p>The iteration order of the given deps along with the {@code groupSizes} parameter dictate
* how deps are grouped. For example, if {@code deps = {a,b,c}} and {@code groupSizes = [2, 1]},
* then there will be two groups: {@code [a,b]} and {@code [c]}. The sum of {@code groupSizes}
* must equal the size of {@code deps}. Note that it only makes sense to call this method with a
* set implementation that has a stable iteration order.
*
* <p>The given set of deps must not contain any deps in common with this node's existing
* temporary direct deps.
*/
@ThreadSafe
void addTemporaryDirectDepsInGroups(Set<SkyKey> deps, List<Integer> groupSizes);
void addExternalDep();
/**
* Returns true if the node has been signaled exactly as many times as it has temporary
* dependencies, or if {@code getKey().supportsPartialReevaluation()}. This may only be called
* while the node is being evaluated (i.e. before {@link #setValue} and after {@link #markDirty}).
*/
@ThreadSafe
boolean isReadyToEvaluate();
/**
* Returns true if the node has not been signaled exactly as many times as it has temporary
* dependencies. This may only be called while the node is being evaluated (i.e. before {@link
* #setValue} and after {@link #markDirty}).
*
* <p>The node must not complete or be reset while in this state because it may yet be signaled.
*/
@ThreadSafe
boolean hasUnsignaledDeps();
}
| bazelbuild/bazel | src/main/java/com/google/devtools/build/skyframe/NodeEntry.java |
2,768 | /*
* Copyright 2016 The Netty Project
*
* The Netty Project licenses this file to you 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:
*
* https://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 io.netty.microbench.http;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.DefaultHttpRequest;
import io.netty.handler.codec.http.DefaultLastHttpContent;
import io.netty.handler.codec.http.EmptyHttpHeaders;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.DefaultHttpHeadersFactory;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpRequestEncoder;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.microbench.channel.EmbeddedChannelWriteReleaseHandlerContext;
import io.netty.microbench.util.AbstractMicrobenchmark;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import org.openjdk.jmh.annotations.Warmup;
@State(Scope.Thread)
@Fork(2)
@Warmup(iterations = 5)
@Measurement(iterations = 10)
public class HttpRequestEncoderBenchmark extends AbstractMicrobenchmark {
private HttpRequestEncoder encoder;
private FullHttpRequest fullRequest;
private LastHttpContent lastContent;
private HttpRequest contentLengthRequest;
private HttpRequest chunkedRequest;
private ByteBuf content;
private ChannelHandlerContext context;
@Param({ "true", "false" })
public boolean pooledAllocator;
@Param({ "true", "false" })
public boolean voidPromise;
@Param({ "false", "true" })
public boolean typePollution;
@Param({ "128" })
private int contentBytes;
@Setup(Level.Trial)
public void setup() throws Exception {
byte[] bytes = new byte[contentBytes];
content = Unpooled.buffer(bytes.length);
content.writeBytes(bytes);
ByteBuf testContent = Unpooled.unreleasableBuffer(content.asReadOnly());
DefaultHttpHeadersFactory headersFactory = DefaultHttpHeadersFactory.headersFactory().withValidation(false);
HttpHeaders headersWithChunked = headersFactory.newHeaders();
headersWithChunked.add(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
HttpHeaders headersWithContentLength = headersFactory.newHeaders();
headersWithContentLength.add(HttpHeaderNames.CONTENT_LENGTH, testContent.readableBytes());
fullRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/index", testContent,
headersWithContentLength, EmptyHttpHeaders.INSTANCE);
contentLengthRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/index",
headersWithContentLength);
chunkedRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/index", headersWithChunked);
lastContent = new DefaultLastHttpContent(testContent, headersFactory);
encoder = new HttpRequestEncoder();
context = new EmbeddedChannelWriteReleaseHandlerContext(pooledAllocator ? PooledByteBufAllocator.DEFAULT :
UnpooledByteBufAllocator.DEFAULT, encoder) {
@Override
protected void handleException(Throwable t) {
handleUnexpectedException(t);
}
};
if (typePollution) {
for (int i = 0; i < 20000; i++) {
differentTypes();
}
}
}
@TearDown(Level.Trial)
public void teardown() {
content.release();
content = null;
}
@Benchmark
public void fullMessage() throws Exception {
fullRequest.content().setIndex(0, contentBytes);
encoder.write(context, fullRequest, newPromise());
}
@Benchmark
public void contentLength() throws Exception {
encoder.write(context, contentLengthRequest, newPromise());
lastContent.content().setIndex(0, contentBytes);
encoder.write(context, lastContent, newPromise());
}
@Benchmark
public void chunked() throws Exception {
encoder.write(context, chunkedRequest, newPromise());
lastContent.content().setIndex(0, contentBytes);
encoder.write(context, lastContent, newPromise());
}
@Benchmark
public void differentTypes() throws Exception {
encoder.write(context, contentLengthRequest, newPromise());
lastContent.content().setIndex(0, contentBytes);
encoder.write(context, lastContent, newPromise());
content.setIndex(0, contentBytes);
fullRequest.content().setIndex(0, contentBytes);
encoder.write(context, fullRequest, newPromise());
encoder.write(context, chunkedRequest, newPromise());
lastContent.content().setIndex(0, contentBytes);
encoder.write(context, lastContent, newPromise());
}
private ChannelPromise newPromise() {
return voidPromise ? context.voidPromise() : context.newPromise();
}
}
| netty/netty | microbench/src/main/java/io/netty/microbench/http/HttpRequestEncoderBenchmark.java |
2,769 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you 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:
*
* https://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 io.netty.microbench.buffer;
import io.netty.buffer.AdaptiveByteBufAllocator;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.microbench.util.AbstractMicrobenchmark;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import java.util.Random;
/**
* This class benchmarks different allocators with different allocation sizes.
*/
@State(Scope.Benchmark)
public class ByteBufAllocatorBenchmark extends AbstractMicrobenchmark {
private static final ByteBufAllocator unpooledAllocator = new UnpooledByteBufAllocator(true);
private static final ByteBufAllocator pooledAllocator =
new PooledByteBufAllocator(true, 4, 4, 8192, 11, 0, 0, 0, true, 0); // Disable thread-local cache
private static final ByteBufAllocator adaptiveAllocator = new AdaptiveByteBufAllocator();
private static final int MAX_LIVE_BUFFERS = 8192;
private static final Random rand = new Random();
private static final ByteBuf[] unpooledHeapBuffers = new ByteBuf[MAX_LIVE_BUFFERS];
private static final ByteBuf[] unpooledDirectBuffers = new ByteBuf[MAX_LIVE_BUFFERS];
private static final ByteBuf[] pooledHeapBuffers = new ByteBuf[MAX_LIVE_BUFFERS];
private static final ByteBuf[] pooledDirectBuffers = new ByteBuf[MAX_LIVE_BUFFERS];
private static final ByteBuf[] defaultPooledHeapBuffers = new ByteBuf[MAX_LIVE_BUFFERS];
private static final ByteBuf[] defaultPooledDirectBuffers = new ByteBuf[MAX_LIVE_BUFFERS];
private static final ByteBuf[] adaptiveHeapBuffers = new ByteBuf[MAX_LIVE_BUFFERS];
private static final ByteBuf[] adaptiveDirectBuffers = new ByteBuf[MAX_LIVE_BUFFERS];
@Param({ "00000", "00256", "01024", "04096", "16384", "65536" })
public int size;
@Benchmark
public void unpooledHeapAllocAndFree() {
int idx = rand.nextInt(unpooledHeapBuffers.length);
ByteBuf oldBuf = unpooledHeapBuffers[idx];
if (oldBuf != null) {
oldBuf.release();
}
unpooledHeapBuffers[idx] = unpooledAllocator.heapBuffer(size);
}
@Benchmark
public void unpooledDirectAllocAndFree() {
int idx = rand.nextInt(unpooledDirectBuffers.length);
ByteBuf oldBuf = unpooledDirectBuffers[idx];
if (oldBuf != null) {
oldBuf.release();
}
unpooledDirectBuffers[idx] = unpooledAllocator.directBuffer(size);
}
@Benchmark
public void pooledHeapAllocAndFree() {
int idx = rand.nextInt(pooledHeapBuffers.length);
ByteBuf oldBuf = pooledHeapBuffers[idx];
if (oldBuf != null) {
oldBuf.release();
}
pooledHeapBuffers[idx] = pooledAllocator.heapBuffer(size);
}
@Benchmark
public void pooledDirectAllocAndFree() {
int idx = rand.nextInt(pooledDirectBuffers.length);
ByteBuf oldBuf = pooledDirectBuffers[idx];
if (oldBuf != null) {
oldBuf.release();
}
pooledDirectBuffers[idx] = pooledAllocator.directBuffer(size);
}
@Benchmark
public void defaultPooledHeapAllocAndFree() {
int idx = rand.nextInt(defaultPooledHeapBuffers.length);
ByteBuf oldBuf = defaultPooledHeapBuffers[idx];
if (oldBuf != null) {
oldBuf.release();
}
defaultPooledHeapBuffers[idx] = PooledByteBufAllocator.DEFAULT.heapBuffer(size);
}
@Benchmark
public void defaultPooledDirectAllocAndFree() {
int idx = rand.nextInt(defaultPooledDirectBuffers.length);
ByteBuf oldBuf = defaultPooledDirectBuffers[idx];
if (oldBuf != null) {
oldBuf.release();
}
defaultPooledDirectBuffers[idx] = PooledByteBufAllocator.DEFAULT.directBuffer(size);
}
@Benchmark
public void adaptiveHeapAllocAndFree() {
int idx = rand.nextInt(adaptiveHeapBuffers.length);
ByteBuf oldBuf = adaptiveHeapBuffers[idx];
if (oldBuf != null) {
oldBuf.release();
}
adaptiveHeapBuffers[idx] = adaptiveAllocator.heapBuffer(size);
}
@Benchmark
public void adaptiveDirectAllocAndFree() {
int idx = rand.nextInt(adaptiveDirectBuffers.length);
ByteBuf oldBuf = adaptiveDirectBuffers[idx];
if (oldBuf != null) {
oldBuf.release();
}
adaptiveDirectBuffers[idx] = adaptiveAllocator.directBuffer(size);
}
}
| netty/netty | microbench/src/main/java/io/netty/microbench/buffer/ByteBufAllocatorBenchmark.java |
2,770 | /*
* Copyright (C) 2012 The Guava Authors
*
* 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 com.google.common.testing;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.CharMatcher;
import com.google.common.base.Charsets;
import com.google.common.base.Defaults;
import com.google.common.base.Equivalence;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.base.Splitter;
import com.google.common.base.Stopwatch;
import com.google.common.base.Ticker;
import com.google.common.collect.BiMap;
import com.google.common.collect.ClassToInstanceMap;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableClassToInstanceMap;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableMultiset;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.ImmutableSortedMultiset;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.ImmutableTable;
import com.google.common.collect.Iterators;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.MapDifference;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Multiset;
import com.google.common.collect.Ordering;
import com.google.common.collect.PeekingIterator;
import com.google.common.collect.Range;
import com.google.common.collect.RowSortedTable;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.Sets;
import com.google.common.collect.SortedMapDifference;
import com.google.common.collect.SortedMultiset;
import com.google.common.collect.SortedSetMultimap;
import com.google.common.collect.Table;
import com.google.common.collect.Tables;
import com.google.common.collect.TreeBasedTable;
import com.google.common.collect.TreeMultimap;
import com.google.common.io.ByteSink;
import com.google.common.io.ByteSource;
import com.google.common.io.ByteStreams;
import com.google.common.io.CharSink;
import com.google.common.io.CharSource;
import com.google.common.primitives.Primitives;
import com.google.common.primitives.UnsignedInteger;
import com.google.common.primitives.UnsignedLong;
import com.google.errorprone.annotations.Keep;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Serializable;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.GenericDeclaration;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import java.nio.ShortBuffer;
import java.nio.charset.Charset;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Currency;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
import java.util.Map;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.OptionalLong;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.UUID;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Supplies an arbitrary "default" instance for a wide range of types, often useful in testing
* utilities.
*
* <p>Covers arrays, enums and common types defined in {@code java.lang}, {@code java.lang.reflect},
* {@code java.io}, {@code java.nio}, {@code java.math}, {@code java.util}, {@code
* java.util.concurrent}, {@code java.util.regex}, {@code com.google.common.base}, {@code
* com.google.common.collect} and {@code com.google.common.primitives}. In addition, if the type
* exposes at least one public static final constant of the same type, one of the constants will be
* used; or if the class exposes a public parameter-less constructor then it will be "new"d and
* returned.
*
* <p>All default instances returned by {@link #get} are generics-safe. Clients won't get type
* errors for using {@code get(Comparator.class)} as a {@code Comparator<Foo>}, for example.
* Immutable empty instances are returned for collection types; {@code ""} for string; {@code 0} for
* number types; reasonable default instance for other stateless types. For mutable types, a fresh
* instance is created each time {@code get()} is called.
*
* @author Kevin Bourrillion
* @author Ben Yu
* @since 12.0
*/
@GwtIncompatible
@J2ktIncompatible
@ElementTypesAreNonnullByDefault
public final class ArbitraryInstances {
private static final Ordering<Field> BY_FIELD_NAME =
new Ordering<Field>() {
@Override
public int compare(Field left, Field right) {
return left.getName().compareTo(right.getName());
}
};
/**
* Returns a new {@code MatchResult} that corresponds to a successful match. Apache Harmony (used
* in Android) requires a successful match in order to generate a {@code MatchResult}:
* http://goo.gl/5VQFmC
*/
private static MatchResult createMatchResult() {
Matcher matcher = Pattern.compile(".").matcher("X");
matcher.find();
return matcher.toMatchResult();
}
private static final ClassToInstanceMap<Object> DEFAULTS =
ImmutableClassToInstanceMap.builder()
// primitives
.put(Object.class, "")
.put(Number.class, 0)
.put(UnsignedInteger.class, UnsignedInteger.ZERO)
.put(UnsignedLong.class, UnsignedLong.ZERO)
.put(BigInteger.class, BigInteger.ZERO)
.put(BigDecimal.class, BigDecimal.ZERO)
.put(CharSequence.class, "")
.put(String.class, "")
.put(Pattern.class, Pattern.compile(""))
.put(MatchResult.class, createMatchResult())
.put(TimeUnit.class, TimeUnit.SECONDS)
.put(Charset.class, Charsets.UTF_8)
.put(Currency.class, Currency.getInstance(Locale.US))
.put(Locale.class, Locale.US)
.put(Optional.class, Optional.empty())
.put(OptionalInt.class, OptionalInt.empty())
.put(OptionalLong.class, OptionalLong.empty())
.put(OptionalDouble.class, OptionalDouble.empty())
.put(UUID.class, UUID.randomUUID())
// common.base
.put(CharMatcher.class, CharMatcher.none())
.put(Joiner.class, Joiner.on(','))
.put(Splitter.class, Splitter.on(','))
.put(com.google.common.base.Optional.class, com.google.common.base.Optional.absent())
.put(Predicate.class, Predicates.alwaysTrue())
.put(Equivalence.class, Equivalence.equals())
.put(Ticker.class, Ticker.systemTicker())
.put(Stopwatch.class, Stopwatch.createUnstarted())
// io types
.put(InputStream.class, new ByteArrayInputStream(new byte[0]))
.put(ByteArrayInputStream.class, new ByteArrayInputStream(new byte[0]))
.put(Readable.class, new StringReader(""))
.put(Reader.class, new StringReader(""))
.put(StringReader.class, new StringReader(""))
.put(Buffer.class, ByteBuffer.allocate(0))
.put(CharBuffer.class, CharBuffer.allocate(0))
.put(ByteBuffer.class, ByteBuffer.allocate(0))
.put(ShortBuffer.class, ShortBuffer.allocate(0))
.put(IntBuffer.class, IntBuffer.allocate(0))
.put(LongBuffer.class, LongBuffer.allocate(0))
.put(FloatBuffer.class, FloatBuffer.allocate(0))
.put(DoubleBuffer.class, DoubleBuffer.allocate(0))
.put(File.class, new File(""))
.put(ByteSource.class, ByteSource.empty())
.put(CharSource.class, CharSource.empty())
.put(ByteSink.class, NullByteSink.INSTANCE)
.put(CharSink.class, NullByteSink.INSTANCE.asCharSink(Charsets.UTF_8))
// All collections are immutable empty. So safe for any type parameter.
.put(Iterator.class, ImmutableSet.of().iterator())
.put(PeekingIterator.class, Iterators.peekingIterator(ImmutableSet.of().iterator()))
.put(ListIterator.class, ImmutableList.of().listIterator())
.put(Iterable.class, ImmutableSet.of())
.put(Collection.class, ImmutableList.of())
.put(ImmutableCollection.class, ImmutableList.of())
.put(List.class, ImmutableList.of())
.put(ImmutableList.class, ImmutableList.of())
.put(Set.class, ImmutableSet.of())
.put(ImmutableSet.class, ImmutableSet.of())
.put(SortedSet.class, ImmutableSortedSet.of())
.put(ImmutableSortedSet.class, ImmutableSortedSet.of())
.put(NavigableSet.class, Sets.unmodifiableNavigableSet(Sets.newTreeSet()))
.put(Map.class, ImmutableMap.of())
.put(ImmutableMap.class, ImmutableMap.of())
.put(SortedMap.class, ImmutableSortedMap.of())
.put(ImmutableSortedMap.class, ImmutableSortedMap.of())
.put(NavigableMap.class, Maps.unmodifiableNavigableMap(Maps.newTreeMap()))
.put(Multimap.class, ImmutableMultimap.of())
.put(ImmutableMultimap.class, ImmutableMultimap.of())
.put(ListMultimap.class, ImmutableListMultimap.of())
.put(ImmutableListMultimap.class, ImmutableListMultimap.of())
.put(SetMultimap.class, ImmutableSetMultimap.of())
.put(ImmutableSetMultimap.class, ImmutableSetMultimap.of())
.put(
SortedSetMultimap.class,
Multimaps.unmodifiableSortedSetMultimap(TreeMultimap.create()))
.put(Multiset.class, ImmutableMultiset.of())
.put(ImmutableMultiset.class, ImmutableMultiset.of())
.put(SortedMultiset.class, ImmutableSortedMultiset.of())
.put(ImmutableSortedMultiset.class, ImmutableSortedMultiset.of())
.put(BiMap.class, ImmutableBiMap.of())
.put(ImmutableBiMap.class, ImmutableBiMap.of())
.put(Table.class, ImmutableTable.of())
.put(ImmutableTable.class, ImmutableTable.of())
.put(RowSortedTable.class, Tables.unmodifiableRowSortedTable(TreeBasedTable.create()))
.put(ClassToInstanceMap.class, ImmutableClassToInstanceMap.builder().build())
.put(ImmutableClassToInstanceMap.class, ImmutableClassToInstanceMap.builder().build())
.put(Comparable.class, ByToString.INSTANCE)
.put(Comparator.class, AlwaysEqual.INSTANCE)
.put(Ordering.class, AlwaysEqual.INSTANCE)
.put(Range.class, Range.all())
.put(MapDifference.class, Maps.difference(ImmutableMap.of(), ImmutableMap.of()))
.put(
SortedMapDifference.class,
Maps.difference(ImmutableSortedMap.of(), ImmutableSortedMap.of()))
// reflect
.put(AnnotatedElement.class, Object.class)
.put(GenericDeclaration.class, Object.class)
.put(Type.class, Object.class)
.build();
/**
* type → implementation. Inherently mutable interfaces and abstract classes are mapped to their
* default implementations and are "new"d upon get().
*/
private static final ConcurrentMap<Class<?>, Class<?>> implementations = Maps.newConcurrentMap();
private static <T> void setImplementation(Class<T> type, Class<? extends T> implementation) {
checkArgument(type != implementation, "Don't register %s to itself!", type);
checkArgument(
!DEFAULTS.containsKey(type), "A default value was already registered for %s", type);
checkArgument(
implementations.put(type, implementation) == null,
"Implementation for %s was already registered",
type);
}
static {
setImplementation(Appendable.class, StringBuilder.class);
setImplementation(BlockingQueue.class, LinkedBlockingDeque.class);
setImplementation(BlockingDeque.class, LinkedBlockingDeque.class);
setImplementation(ConcurrentMap.class, ConcurrentHashMap.class);
setImplementation(ConcurrentNavigableMap.class, ConcurrentSkipListMap.class);
setImplementation(CountDownLatch.class, Dummies.DummyCountDownLatch.class);
setImplementation(Deque.class, ArrayDeque.class);
setImplementation(OutputStream.class, ByteArrayOutputStream.class);
setImplementation(PrintStream.class, Dummies.InMemoryPrintStream.class);
setImplementation(PrintWriter.class, Dummies.InMemoryPrintWriter.class);
setImplementation(Queue.class, ArrayDeque.class);
setImplementation(Random.class, Dummies.DeterministicRandom.class);
setImplementation(
ScheduledThreadPoolExecutor.class, Dummies.DummyScheduledThreadPoolExecutor.class);
setImplementation(ThreadPoolExecutor.class, Dummies.DummyScheduledThreadPoolExecutor.class);
setImplementation(Writer.class, StringWriter.class);
setImplementation(Runnable.class, Dummies.DummyRunnable.class);
setImplementation(ThreadFactory.class, Dummies.DummyThreadFactory.class);
setImplementation(Executor.class, Dummies.DummyExecutor.class);
}
@SuppressWarnings("unchecked") // it's a subtype map
private static <T> @Nullable Class<? extends T> getImplementation(Class<T> type) {
return (Class<? extends T>) implementations.get(type);
}
private static final Logger logger = Logger.getLogger(ArbitraryInstances.class.getName());
/**
* Returns an arbitrary instance for {@code type}, or {@code null} if no arbitrary instance can be
* determined.
*/
public static <T> @Nullable T get(Class<T> type) {
T defaultValue = DEFAULTS.getInstance(type);
if (defaultValue != null) {
return defaultValue;
}
Class<? extends T> implementation = getImplementation(type);
if (implementation != null) {
return get(implementation);
}
if (type == Stream.class) {
return type.cast(Stream.empty());
}
if (type.isEnum()) {
T[] enumConstants = type.getEnumConstants();
return (enumConstants == null || enumConstants.length == 0) ? null : enumConstants[0];
}
if (type.isArray()) {
return createEmptyArray(type);
}
T jvmDefault = Defaults.defaultValue(Primitives.unwrap(type));
if (jvmDefault != null) {
return jvmDefault;
}
if (Modifier.isAbstract(type.getModifiers()) || !Modifier.isPublic(type.getModifiers())) {
return arbitraryConstantInstanceOrNull(type);
}
final Constructor<T> constructor;
try {
constructor = type.getConstructor();
} catch (NoSuchMethodException e) {
return arbitraryConstantInstanceOrNull(type);
}
constructor.setAccessible(true); // accessibility check is too slow
try {
return constructor.newInstance();
} catch (InstantiationException | IllegalAccessException impossible) {
throw new AssertionError(impossible);
} catch (InvocationTargetException e) {
logger.log(Level.WARNING, "Exception while invoking default constructor.", e.getCause());
return arbitraryConstantInstanceOrNull(type);
}
}
private static <T> @Nullable T arbitraryConstantInstanceOrNull(Class<T> type) {
Field[] fields = type.getDeclaredFields();
Arrays.sort(fields, BY_FIELD_NAME);
for (Field field : fields) {
if (Modifier.isPublic(field.getModifiers())
&& Modifier.isStatic(field.getModifiers())
&& Modifier.isFinal(field.getModifiers())) {
if (field.getGenericType() == field.getType() && type.isAssignableFrom(field.getType())) {
field.setAccessible(true);
try {
T constant = type.cast(field.get(null));
if (constant != null) {
return constant;
}
} catch (IllegalAccessException impossible) {
throw new AssertionError(impossible);
}
}
}
}
return null;
}
private static <T> T createEmptyArray(Class<T> arrayType) {
// getComponentType() is non-null because we call createEmptyArray only with an array type.
return arrayType.cast(Array.newInstance(requireNonNull(arrayType.getComponentType()), 0));
}
// Internal implementations of some classes, with public default constructor that get() needs.
private static final class Dummies {
public static final class InMemoryPrintStream extends PrintStream {
public InMemoryPrintStream() {
super(new ByteArrayOutputStream());
}
}
public static final class InMemoryPrintWriter extends PrintWriter {
public InMemoryPrintWriter() {
super(new StringWriter());
}
}
public static final class DeterministicRandom extends Random {
@Keep
public DeterministicRandom() {
super(0);
}
}
public static final class DummyScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor {
public DummyScheduledThreadPoolExecutor() {
super(1);
}
}
public static final class DummyCountDownLatch extends CountDownLatch {
public DummyCountDownLatch() {
super(0);
}
}
public static final class DummyRunnable implements Runnable, Serializable {
@Override
public void run() {}
}
public static final class DummyThreadFactory implements ThreadFactory, Serializable {
@Override
public Thread newThread(Runnable r) {
return new Thread(r);
}
}
public static final class DummyExecutor implements Executor, Serializable {
@Override
public void execute(Runnable command) {}
}
}
private static final class NullByteSink extends ByteSink implements Serializable {
private static final NullByteSink INSTANCE = new NullByteSink();
@Override
public OutputStream openStream() {
return ByteStreams.nullOutputStream();
}
}
// Compare by toString() to satisfy 2 properties:
// 1. compareTo(null) should throw NullPointerException
// 2. the order is deterministic and easy to understand, for debugging purpose.
@SuppressWarnings("ComparableType")
private static final class ByToString implements Comparable<Object>, Serializable {
private static final ByToString INSTANCE = new ByToString();
@Override
public int compareTo(Object o) {
return toString().compareTo(o.toString());
}
@Override
public String toString() {
return "BY_TO_STRING";
}
private Object readResolve() {
return INSTANCE;
}
}
// Always equal is a valid total ordering. And it works for any Object.
private static final class AlwaysEqual extends Ordering<@Nullable Object>
implements Serializable {
private static final AlwaysEqual INSTANCE = new AlwaysEqual();
@Override
public int compare(@Nullable Object o1, @Nullable Object o2) {
return 0;
}
@Override
public String toString() {
return "ALWAYS_EQUAL";
}
private Object readResolve() {
return INSTANCE;
}
}
private ArbitraryInstances() {}
}
| google/guava | guava-testlib/src/com/google/common/testing/ArbitraryInstances.java |
2,771 | /* ###
* IP: Apache License 2.0 with LLVM Exceptions
*/
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (https://www.swig.org).
* Version 4.1.1
*
* Do not make changes to this file unless you know what you are doing - modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package SWIG;
public class lldbJNI {
public final static native long new_ByteArray(int jarg1);
public final static native void delete_ByteArray(long jarg1);
public final static native byte ByteArray_getitem(long jarg1, ByteArray jarg1_, int jarg2);
public final static native void ByteArray_setitem(long jarg1, ByteArray jarg1_, int jarg2, byte jarg3);
public final static native long ByteArray_cast(long jarg1, ByteArray jarg1_);
public final static native long ByteArray_frompointer(long jarg1);
public final static native int INT32_MAX_get();
public final static native long UINT32_MAX_get();
public final static native java.math.BigInteger UINT64_MAX_get();
public final static native long LLDB_GENERIC_ERROR_get();
public final static native int LLDB_INVALID_BREAK_ID_get();
public final static native int LLDB_DEFAULT_BREAK_SIZE_get();
public final static native int LLDB_INVALID_WATCH_ID_get();
public final static native long LLDB_WATCH_TYPE_READ_get();
public final static native long LLDB_WATCH_TYPE_WRITE_get();
public final static native int LLDB_REGNUM_GENERIC_PC_get();
public final static native int LLDB_REGNUM_GENERIC_SP_get();
public final static native int LLDB_REGNUM_GENERIC_FP_get();
public final static native int LLDB_REGNUM_GENERIC_RA_get();
public final static native int LLDB_REGNUM_GENERIC_FLAGS_get();
public final static native int LLDB_REGNUM_GENERIC_ARG1_get();
public final static native int LLDB_REGNUM_GENERIC_ARG2_get();
public final static native int LLDB_REGNUM_GENERIC_ARG3_get();
public final static native int LLDB_REGNUM_GENERIC_ARG4_get();
public final static native int LLDB_REGNUM_GENERIC_ARG5_get();
public final static native int LLDB_REGNUM_GENERIC_ARG6_get();
public final static native int LLDB_REGNUM_GENERIC_ARG7_get();
public final static native int LLDB_REGNUM_GENERIC_ARG8_get();
public final static native int LLDB_INVALID_STOP_ID_get();
public final static native java.math.BigInteger LLDB_INVALID_ADDRESS_get();
public final static native long LLDB_INVALID_INDEX32_get();
public final static native long LLDB_INVALID_IVAR_OFFSET_get();
public final static native long LLDB_INVALID_IMAGE_TOKEN_get();
public final static native long LLDB_INVALID_MODULE_VERSION_get();
public final static native long LLDB_INVALID_REGNUM_get();
public final static native java.math.BigInteger LLDB_INVALID_UID_get();
public final static native int LLDB_INVALID_PROCESS_ID_get();
public final static native int LLDB_INVALID_THREAD_ID_get();
public final static native long LLDB_INVALID_FRAME_ID_get();
public final static native int LLDB_INVALID_SIGNAL_NUMBER_get();
public final static native java.math.BigInteger LLDB_INVALID_OFFSET_get();
public final static native long LLDB_INVALID_LINE_NUMBER_get();
public final static native int LLDB_INVALID_COLUMN_NUMBER_get();
public final static native int LLDB_INVALID_QUEUE_ID_get();
public final static native long LLDB_INVALID_CPU_ID_get();
public final static native String LLDB_ARCH_DEFAULT_get();
public final static native String LLDB_ARCH_DEFAULT_32BIT_get();
public final static native String LLDB_ARCH_DEFAULT_64BIT_get();
public final static native long LLDB_INVALID_CPUTYPE_get();
public final static native int LLDB_MAX_NUM_OPTION_SETS_get();
public final static native long LLDB_OPT_SET_ALL_get();
public final static native long LLDB_OPT_SET_1_get();
public final static native long LLDB_OPT_SET_2_get();
public final static native long LLDB_OPT_SET_3_get();
public final static native long LLDB_OPT_SET_4_get();
public final static native long LLDB_OPT_SET_5_get();
public final static native long LLDB_OPT_SET_6_get();
public final static native long LLDB_OPT_SET_7_get();
public final static native long LLDB_OPT_SET_8_get();
public final static native long LLDB_OPT_SET_9_get();
public final static native long LLDB_OPT_SET_10_get();
public final static native long LLDB_OPT_SET_11_get();
public final static native long LLDB_OPT_SET_12_get();
public final static native int eStateInvalid_get();
public final static native int kLastStateType_get();
public final static native int eLaunchFlagNone_get();
public final static native int eLaunchFlagExec_get();
public final static native int eLaunchFlagDebug_get();
public final static native int eLaunchFlagStopAtEntry_get();
public final static native int eLaunchFlagDisableASLR_get();
public final static native int eLaunchFlagDisableSTDIO_get();
public final static native int eLaunchFlagLaunchInTTY_get();
public final static native int eLaunchFlagLaunchInShell_get();
public final static native int eLaunchFlagLaunchInSeparateProcessGroup_get();
public final static native int eLaunchFlagDontSetExitStatus_get();
public final static native int eLaunchFlagDetachOnError_get();
public final static native int eLaunchFlagShellExpandArguments_get();
public final static native int eLaunchFlagCloseTTYOnExit_get();
public final static native int eLaunchFlagInheritTCCFromParent_get();
public final static native int eByteOrderInvalid_get();
public final static native int eByteOrderBig_get();
public final static native int eByteOrderPDP_get();
public final static native int eByteOrderLittle_get();
public final static native int eEncodingInvalid_get();
public final static native int eFormatDefault_get();
public final static native int eFormatInvalid_get();
public final static native int eFormatComplexFloat_get();
public final static native int eDescriptionLevelBrief_get();
public final static native int eScriptLanguageNone_get();
public final static native int eScriptLanguageDefault_get();
public final static native int eRegisterKindEHFrame_get();
public final static native int eStopReasonInvalid_get();
public final static native int eExpressionCompleted_get();
public final static native int eSearchDepthInvalid_get();
public final static native int kLastSearchDepthKind_get();
public final static native int eValueTypeInvalid_get();
public final static native int eValueTypeVariableGlobal_get();
public final static native int eValueTypeVariableStatic_get();
public final static native int eValueTypeVariableArgument_get();
public final static native int eValueTypeVariableLocal_get();
public final static native int eValueTypeRegister_get();
public final static native int eValueTypeRegisterSet_get();
public final static native int eValueTypeConstResult_get();
public final static native int eValueTypeVariableThreadLocal_get();
public final static native int eInputReaderGranularityInvalid_get();
public final static native int eSymbolContextTarget_get();
public final static native int eSymbolContextModule_get();
public final static native int eSymbolContextCompUnit_get();
public final static native int eSymbolContextFunction_get();
public final static native int eSymbolContextBlock_get();
public final static native int eSymbolContextLineEntry_get();
public final static native int eSymbolContextSymbol_get();
public final static native int eSymbolContextEverything_get();
public final static native int eSymbolContextVariable_get();
public final static native int eSymbolContextLastItem_get();
public final static native int ePermissionsWritable_get();
public final static native int ePermissionsReadable_get();
public final static native int ePermissionsExecutable_get();
public final static native int eBreakpointEventTypeInvalidType_get();
public final static native int eBreakpointEventTypeAdded_get();
public final static native int eBreakpointEventTypeRemoved_get();
public final static native int eBreakpointEventTypeLocationsAdded_get();
public final static native int eBreakpointEventTypeLocationsRemoved_get();
public final static native int eBreakpointEventTypeLocationsResolved_get();
public final static native int eBreakpointEventTypeEnabled_get();
public final static native int eBreakpointEventTypeDisabled_get();
public final static native int eBreakpointEventTypeCommandChanged_get();
public final static native int eBreakpointEventTypeConditionChanged_get();
public final static native int eBreakpointEventTypeIgnoreChanged_get();
public final static native int eBreakpointEventTypeThreadChanged_get();
public final static native int eBreakpointEventTypeAutoContinueChanged_get();
public final static native int eWatchpointEventTypeInvalidType_get();
public final static native int eWatchpointEventTypeAdded_get();
public final static native int eWatchpointEventTypeRemoved_get();
public final static native int eWatchpointEventTypeEnabled_get();
public final static native int eWatchpointEventTypeDisabled_get();
public final static native int eWatchpointEventTypeCommandChanged_get();
public final static native int eWatchpointEventTypeConditionChanged_get();
public final static native int eWatchpointEventTypeIgnoreChanged_get();
public final static native int eWatchpointEventTypeThreadChanged_get();
public final static native int eWatchpointEventTypeTypeChanged_get();
public final static native int eLanguageTypeUnknown_get();
public final static native int eLanguageTypeC89_get();
public final static native int eLanguageTypeC_get();
public final static native int eLanguageTypeAda83_get();
public final static native int eLanguageTypeC_plus_plus_get();
public final static native int eLanguageTypeCobol74_get();
public final static native int eLanguageTypeCobol85_get();
public final static native int eLanguageTypeFortran77_get();
public final static native int eLanguageTypeFortran90_get();
public final static native int eLanguageTypePascal83_get();
public final static native int eLanguageTypeModula2_get();
public final static native int eLanguageTypeJava_get();
public final static native int eLanguageTypeC99_get();
public final static native int eLanguageTypeAda95_get();
public final static native int eLanguageTypeFortran95_get();
public final static native int eLanguageTypePLI_get();
public final static native int eLanguageTypeObjC_get();
public final static native int eLanguageTypeObjC_plus_plus_get();
public final static native int eLanguageTypeUPC_get();
public final static native int eLanguageTypeD_get();
public final static native int eLanguageTypePython_get();
public final static native int eLanguageTypeOpenCL_get();
public final static native int eLanguageTypeGo_get();
public final static native int eLanguageTypeModula3_get();
public final static native int eLanguageTypeHaskell_get();
public final static native int eLanguageTypeC_plus_plus_03_get();
public final static native int eLanguageTypeC_plus_plus_11_get();
public final static native int eLanguageTypeOCaml_get();
public final static native int eLanguageTypeRust_get();
public final static native int eLanguageTypeC11_get();
public final static native int eLanguageTypeSwift_get();
public final static native int eLanguageTypeJulia_get();
public final static native int eLanguageTypeDylan_get();
public final static native int eLanguageTypeC_plus_plus_14_get();
public final static native int eLanguageTypeFortran03_get();
public final static native int eLanguageTypeFortran08_get();
public final static native int eLanguageTypeRenderScript_get();
public final static native int eLanguageTypeBLISS_get();
public final static native int eLanguageTypeKotlin_get();
public final static native int eLanguageTypeZig_get();
public final static native int eLanguageTypeCrystal_get();
public final static native int eLanguageTypeC_plus_plus_17_get();
public final static native int eLanguageTypeC_plus_plus_20_get();
public final static native int eLanguageTypeC17_get();
public final static native int eLanguageTypeFortran18_get();
public final static native int eLanguageTypeAda2005_get();
public final static native int eLanguageTypeAda2012_get();
public final static native int eLanguageTypeHIP_get();
public final static native int eLanguageTypeAssembly_get();
public final static native int eLanguageTypeC_sharp_get();
public final static native int eLanguageTypeMojo_get();
public final static native int eInstrumentationRuntimeTypeAddressSanitizer_get();
public final static native int eInstrumentationRuntimeTypeThreadSanitizer_get();
public final static native int eInstrumentationRuntimeTypeUndefinedBehaviorSanitizer_get();
public final static native int eInstrumentationRuntimeTypeMainThreadChecker_get();
public final static native int eInstrumentationRuntimeTypeSwiftRuntimeReporting_get();
public final static native int eNoDynamicValues_get();
public final static native int eDynamicCanRunTarget_get();
public final static native int eDynamicDontRunTarget_get();
public final static native int eStopShowColumnAnsiOrCaret_get();
public final static native int eStopShowColumnAnsi_get();
public final static native int eStopShowColumnCaret_get();
public final static native int eStopShowColumnNone_get();
public final static native int eArgTypeAddress_get();
public final static native int eSymbolTypeAny_get();
public final static native int eSymbolTypeInvalid_get();
public final static native int eEmulateInstructionOptionNone_get();
public final static native int eEmulateInstructionOptionAutoAdvancePC_get();
public final static native int eEmulateInstructionOptionIgnoreConditions_get();
public final static native int eFunctionNameTypeNone_get();
public final static native int eFunctionNameTypeAuto_get();
public final static native int eFunctionNameTypeFull_get();
public final static native int eFunctionNameTypeBase_get();
public final static native int eFunctionNameTypeMethod_get();
public final static native int eFunctionNameTypeSelector_get();
public final static native int eFunctionNameTypeAny_get();
public final static native int eBasicTypeInvalid_get();
public final static native int eBasicTypeVoid_get();
public final static native int eTraceTypeNone_get();
public final static native int eStructuredDataTypeInvalid_get();
public final static native int eStructuredDataTypeNull_get();
public final static native int eStructuredDataTypeUnsignedInteger_get();
public final static native int eTypeClassInvalid_get();
public final static native int eTypeClassArray_get();
public final static native int eTypeClassBlockPointer_get();
public final static native int eTypeClassBuiltin_get();
public final static native int eTypeClassClass_get();
public final static native int eTypeClassComplexFloat_get();
public final static native int eTypeClassComplexInteger_get();
public final static native int eTypeClassEnumeration_get();
public final static native int eTypeClassFunction_get();
public final static native int eTypeClassMemberPointer_get();
public final static native int eTypeClassObjCObject_get();
public final static native int eTypeClassObjCInterface_get();
public final static native int eTypeClassObjCObjectPointer_get();
public final static native int eTypeClassPointer_get();
public final static native int eTypeClassReference_get();
public final static native int eTypeClassStruct_get();
public final static native int eTypeClassTypedef_get();
public final static native int eTypeClassUnion_get();
public final static native int eTypeClassVector_get();
public final static native int eTypeClassOther_get();
public final static native int eTypeClassAny_get();
public final static native int eTemplateArgumentKindNull_get();
public final static native int eLastFormatterMatchType_get();
public final static native int eTypeOptionNone_get();
public final static native int eTypeOptionCascade_get();
public final static native int eTypeOptionSkipPointers_get();
public final static native int eTypeOptionSkipReferences_get();
public final static native int eTypeOptionHideChildren_get();
public final static native int eTypeOptionHideValue_get();
public final static native int eTypeOptionShowOneLiner_get();
public final static native int eTypeOptionHideNames_get();
public final static native int eTypeOptionNonCacheable_get();
public final static native int eTypeOptionHideEmptyAggregates_get();
public final static native int eTypeOptionFrontEndWantsDereference_get();
public final static native int eFilePermissionsUserRead_get();
public final static native int eFilePermissionsUserWrite_get();
public final static native int eFilePermissionsUserExecute_get();
public final static native int eFilePermissionsGroupRead_get();
public final static native int eFilePermissionsGroupWrite_get();
public final static native int eFilePermissionsGroupExecute_get();
public final static native int eFilePermissionsWorldRead_get();
public final static native int eFilePermissionsWorldWrite_get();
public final static native int eFilePermissionsWorldExecute_get();
public final static native int eFilePermissionsUserRW_get();
public final static native int eFileFilePermissionsUserRX_get();
public final static native int eFilePermissionsUserRWX_get();
public final static native int eFilePermissionsGroupRW_get();
public final static native int eFilePermissionsGroupRX_get();
public final static native int eFilePermissionsGroupRWX_get();
public final static native int eFilePermissionsWorldRW_get();
public final static native int eFilePermissionsWorldRX_get();
public final static native int eFilePermissionsWorldRWX_get();
public final static native int eFilePermissionsEveryoneR_get();
public final static native int eFilePermissionsEveryoneW_get();
public final static native int eFilePermissionsEveryoneX_get();
public final static native int eFilePermissionsEveryoneRW_get();
public final static native int eFilePermissionsEveryoneRX_get();
public final static native int eFilePermissionsEveryoneRWX_get();
public final static native int eFilePermissionsFileDefault_get();
public final static native int eFilePermissionsDirectoryDefault_get();
public final static native int eQueueItemKindUnknown_get();
public final static native int eQueueKindUnknown_get();
public final static native int eExpressionEvaluationParse_get();
public final static native int eInstructionControlFlowKindUnknown_get();
public final static native int eWatchpointKindWrite_get();
public final static native int eWatchpointKindRead_get();
public final static native int eGdbSignalBadAccess_get();
public final static native int eGdbSignalBadInstruction_get();
public final static native int eGdbSignalArithmetic_get();
public final static native int eGdbSignalEmulation_get();
public final static native int eGdbSignalSoftware_get();
public final static native int eGdbSignalBreakpoint_get();
public final static native int eMemberFunctionKindUnknown_get();
public final static native int eTypeHasChildren_get();
public final static native int eTypeHasValue_get();
public final static native int eTypeIsArray_get();
public final static native int eTypeIsBlock_get();
public final static native int eTypeIsBuiltIn_get();
public final static native int eTypeIsClass_get();
public final static native int eTypeIsCPlusPlus_get();
public final static native int eTypeIsEnumeration_get();
public final static native int eTypeIsFuncPrototype_get();
public final static native int eTypeIsMember_get();
public final static native int eTypeIsObjC_get();
public final static native int eTypeIsPointer_get();
public final static native int eTypeIsReference_get();
public final static native int eTypeIsStructUnion_get();
public final static native int eTypeIsTemplate_get();
public final static native int eTypeIsTypedef_get();
public final static native int eTypeIsVector_get();
public final static native int eTypeIsScalar_get();
public final static native int eTypeIsInteger_get();
public final static native int eTypeIsFloat_get();
public final static native int eTypeIsComplex_get();
public final static native int eTypeIsSigned_get();
public final static native int eTypeInstanceIsPointer_get();
public final static native int eCommandRequiresTarget_get();
public final static native int eCommandRequiresProcess_get();
public final static native int eCommandRequiresThread_get();
public final static native int eCommandRequiresFrame_get();
public final static native int eCommandRequiresRegContext_get();
public final static native int eCommandTryTargetAPILock_get();
public final static native int eCommandProcessMustBeLaunched_get();
public final static native int eCommandProcessMustBePaused_get();
public final static native int eCommandProcessMustBeTraced_get();
public final static native int eTypeSummaryCapped_get();
public final static native int eTypeSummaryUncapped_get();
public final static native int eSaveCoreUnspecified_get();
public final static native int eSaveCoreFull_get();
public final static native int eSaveCoreDirtyOnly_get();
public final static native int eSaveCoreStackOnly_get();
public final static native int eTraceItemKindError_get();
public final static native int eTraceCursorSeekTypeBeginning_get();
public final static native int eWatchPointValueKindInvalid_get();
public final static native int eWatchPointValueKindVariable_get();
public final static native int eWatchPointValueKindExpression_get();
public final static native int eNoCompletion_get();
public final static native int eSourceFileCompletion_get();
public final static native int eDiskFileCompletion_get();
public final static native int eDiskDirectoryCompletion_get();
public final static native int eSymbolCompletion_get();
public final static native int eModuleCompletion_get();
public final static native int eSettingsNameCompletion_get();
public final static native int ePlatformPluginCompletion_get();
public final static native int eArchitectureCompletion_get();
public final static native int eVariablePathCompletion_get();
public final static native int eRegisterCompletion_get();
public final static native int eBreakpointCompletion_get();
public final static native int eProcessPluginCompletion_get();
public final static native int eDisassemblyFlavorCompletion_get();
public final static native int eTypeLanguageCompletion_get();
public final static native int eFrameIndexCompletion_get();
public final static native int eModuleUUIDCompletion_get();
public final static native int eStopHookIDCompletion_get();
public final static native int eThreadIndexCompletion_get();
public final static native int eWatchpointIDCompletion_get();
public final static native int eBreakpointNameCompletion_get();
public final static native int eProcessIDCompletion_get();
public final static native int eProcessNameCompletion_get();
public final static native int eRemoteDiskFileCompletion_get();
public final static native int eRemoteDiskDirectoryCompletion_get();
public final static native int eTypeCategoryNameCompletion_get();
public final static native int eCustomCompletion_get();
public final static native long new_SBAddress__SWIG_0();
public final static native long new_SBAddress__SWIG_1(long jarg1, SBAddress jarg1_);
public final static native long new_SBAddress__SWIG_2(long jarg1, SBSection jarg1_, java.math.BigInteger jarg2);
public final static native long new_SBAddress__SWIG_3(java.math.BigInteger jarg1, long jarg2, SBTarget jarg2_);
public final static native void delete_SBAddress(long jarg1);
public final static native boolean SBAddress_IsValid(long jarg1, SBAddress jarg1_);
public final static native void SBAddress_Clear(long jarg1, SBAddress jarg1_);
public final static native java.math.BigInteger SBAddress_GetFileAddress(long jarg1, SBAddress jarg1_);
public final static native java.math.BigInteger SBAddress_GetLoadAddress(long jarg1, SBAddress jarg1_, long jarg2, SBTarget jarg2_);
public final static native void SBAddress_SetAddress(long jarg1, SBAddress jarg1_, long jarg2, SBSection jarg2_, java.math.BigInteger jarg3);
public final static native void SBAddress_SetLoadAddress(long jarg1, SBAddress jarg1_, java.math.BigInteger jarg2, long jarg3, SBTarget jarg3_);
public final static native boolean SBAddress_OffsetAddress(long jarg1, SBAddress jarg1_, java.math.BigInteger jarg2);
public final static native boolean SBAddress_GetDescription(long jarg1, SBAddress jarg1_, long jarg2, SBStream jarg2_);
public final static native long SBAddress_GetSymbolContext(long jarg1, SBAddress jarg1_, long jarg2);
public final static native long SBAddress_GetSection(long jarg1, SBAddress jarg1_);
public final static native java.math.BigInteger SBAddress_GetOffset(long jarg1, SBAddress jarg1_);
public final static native long SBAddress_GetModule(long jarg1, SBAddress jarg1_);
public final static native long SBAddress_GetCompileUnit(long jarg1, SBAddress jarg1_);
public final static native long SBAddress_GetFunction(long jarg1, SBAddress jarg1_);
public final static native long SBAddress_GetBlock(long jarg1, SBAddress jarg1_);
public final static native long SBAddress_GetSymbol(long jarg1, SBAddress jarg1_);
public final static native long SBAddress_GetLineEntry(long jarg1, SBAddress jarg1_);
public final static native String SBAddress___repr__(long jarg1, SBAddress jarg1_);
public final static native long new_SBAttachInfo__SWIG_0();
public final static native long new_SBAttachInfo__SWIG_1(java.math.BigInteger jarg1);
public final static native long new_SBAttachInfo__SWIG_2(String jarg1, boolean jarg2);
public final static native long new_SBAttachInfo__SWIG_3(String jarg1, boolean jarg2, boolean jarg3);
public final static native long new_SBAttachInfo__SWIG_4(long jarg1, SBAttachInfo jarg1_);
public final static native void delete_SBAttachInfo(long jarg1);
public final static native java.math.BigInteger SBAttachInfo_GetProcessID(long jarg1, SBAttachInfo jarg1_);
public final static native void SBAttachInfo_SetProcessID(long jarg1, SBAttachInfo jarg1_, java.math.BigInteger jarg2);
public final static native void SBAttachInfo_SetExecutable__SWIG_0(long jarg1, SBAttachInfo jarg1_, String jarg2);
public final static native void SBAttachInfo_SetExecutable__SWIG_1(long jarg1, SBAttachInfo jarg1_, long jarg2, SBFileSpec jarg2_);
public final static native boolean SBAttachInfo_GetWaitForLaunch(long jarg1, SBAttachInfo jarg1_);
public final static native void SBAttachInfo_SetWaitForLaunch__SWIG_0(long jarg1, SBAttachInfo jarg1_, boolean jarg2);
public final static native void SBAttachInfo_SetWaitForLaunch__SWIG_1(long jarg1, SBAttachInfo jarg1_, boolean jarg2, boolean jarg3);
public final static native boolean SBAttachInfo_GetIgnoreExisting(long jarg1, SBAttachInfo jarg1_);
public final static native void SBAttachInfo_SetIgnoreExisting(long jarg1, SBAttachInfo jarg1_, boolean jarg2);
public final static native long SBAttachInfo_GetResumeCount(long jarg1, SBAttachInfo jarg1_);
public final static native void SBAttachInfo_SetResumeCount(long jarg1, SBAttachInfo jarg1_, long jarg2);
public final static native String SBAttachInfo_GetProcessPluginName(long jarg1, SBAttachInfo jarg1_);
public final static native void SBAttachInfo_SetProcessPluginName(long jarg1, SBAttachInfo jarg1_, String jarg2);
public final static native long SBAttachInfo_GetUserID(long jarg1, SBAttachInfo jarg1_);
public final static native long SBAttachInfo_GetGroupID(long jarg1, SBAttachInfo jarg1_);
public final static native boolean SBAttachInfo_UserIDIsValid(long jarg1, SBAttachInfo jarg1_);
public final static native boolean SBAttachInfo_GroupIDIsValid(long jarg1, SBAttachInfo jarg1_);
public final static native void SBAttachInfo_SetUserID(long jarg1, SBAttachInfo jarg1_, long jarg2);
public final static native void SBAttachInfo_SetGroupID(long jarg1, SBAttachInfo jarg1_, long jarg2);
public final static native long SBAttachInfo_GetEffectiveUserID(long jarg1, SBAttachInfo jarg1_);
public final static native long SBAttachInfo_GetEffectiveGroupID(long jarg1, SBAttachInfo jarg1_);
public final static native boolean SBAttachInfo_EffectiveUserIDIsValid(long jarg1, SBAttachInfo jarg1_);
public final static native boolean SBAttachInfo_EffectiveGroupIDIsValid(long jarg1, SBAttachInfo jarg1_);
public final static native void SBAttachInfo_SetEffectiveUserID(long jarg1, SBAttachInfo jarg1_, long jarg2);
public final static native void SBAttachInfo_SetEffectiveGroupID(long jarg1, SBAttachInfo jarg1_, long jarg2);
public final static native java.math.BigInteger SBAttachInfo_GetParentProcessID(long jarg1, SBAttachInfo jarg1_);
public final static native void SBAttachInfo_SetParentProcessID(long jarg1, SBAttachInfo jarg1_, java.math.BigInteger jarg2);
public final static native boolean SBAttachInfo_ParentProcessIDIsValid(long jarg1, SBAttachInfo jarg1_);
public final static native long SBAttachInfo_GetListener(long jarg1, SBAttachInfo jarg1_);
public final static native void SBAttachInfo_SetListener(long jarg1, SBAttachInfo jarg1_, long jarg2, SBListener jarg2_);
public final static native long SBAttachInfo_GetShadowListener(long jarg1, SBAttachInfo jarg1_);
public final static native void SBAttachInfo_SetShadowListener(long jarg1, SBAttachInfo jarg1_, long jarg2, SBListener jarg2_);
public final static native String SBAttachInfo_GetScriptedProcessClassName(long jarg1, SBAttachInfo jarg1_);
public final static native void SBAttachInfo_SetScriptedProcessClassName(long jarg1, SBAttachInfo jarg1_, String jarg2);
public final static native long SBAttachInfo_GetScriptedProcessDictionary(long jarg1, SBAttachInfo jarg1_);
public final static native void SBAttachInfo_SetScriptedProcessDictionary(long jarg1, SBAttachInfo jarg1_, long jarg2, SBStructuredData jarg2_);
public final static native long new_SBBlock__SWIG_0();
public final static native long new_SBBlock__SWIG_1(long jarg1, SBBlock jarg1_);
public final static native void delete_SBBlock(long jarg1);
public final static native boolean SBBlock_IsInlined(long jarg1, SBBlock jarg1_);
public final static native boolean SBBlock_IsValid(long jarg1, SBBlock jarg1_);
public final static native String SBBlock_GetInlinedName(long jarg1, SBBlock jarg1_);
public final static native long SBBlock_GetInlinedCallSiteFile(long jarg1, SBBlock jarg1_);
public final static native long SBBlock_GetInlinedCallSiteLine(long jarg1, SBBlock jarg1_);
public final static native long SBBlock_GetInlinedCallSiteColumn(long jarg1, SBBlock jarg1_);
public final static native long SBBlock_GetParent(long jarg1, SBBlock jarg1_);
public final static native long SBBlock_GetSibling(long jarg1, SBBlock jarg1_);
public final static native long SBBlock_GetFirstChild(long jarg1, SBBlock jarg1_);
public final static native long SBBlock_GetNumRanges(long jarg1, SBBlock jarg1_);
public final static native long SBBlock_GetRangeStartAddress(long jarg1, SBBlock jarg1_, long jarg2);
public final static native long SBBlock_GetRangeEndAddress(long jarg1, SBBlock jarg1_, long jarg2);
public final static native long SBBlock_GetRangeIndexForBlockAddress(long jarg1, SBBlock jarg1_, long jarg2, SBAddress jarg2_);
public final static native long SBBlock_GetVariables__SWIG_0(long jarg1, SBBlock jarg1_, long jarg2, SBFrame jarg2_, boolean jarg3, boolean jarg4, boolean jarg5, int jarg6);
public final static native long SBBlock_GetVariables__SWIG_1(long jarg1, SBBlock jarg1_, long jarg2, SBTarget jarg2_, boolean jarg3, boolean jarg4, boolean jarg5);
public final static native long SBBlock_GetContainingInlinedBlock(long jarg1, SBBlock jarg1_);
public final static native boolean SBBlock_GetDescription(long jarg1, SBBlock jarg1_, long jarg2, SBStream jarg2_);
public final static native String SBBlock___repr__(long jarg1, SBBlock jarg1_);
public final static native long new_SBBreakpoint__SWIG_0();
public final static native long new_SBBreakpoint__SWIG_1(long jarg1, SBBreakpoint jarg1_);
public final static native void delete_SBBreakpoint(long jarg1);
public final static native int SBBreakpoint_GetID(long jarg1, SBBreakpoint jarg1_);
public final static native boolean SBBreakpoint_IsValid(long jarg1, SBBreakpoint jarg1_);
public final static native void SBBreakpoint_ClearAllBreakpointSites(long jarg1, SBBreakpoint jarg1_);
public final static native long SBBreakpoint_GetTarget(long jarg1, SBBreakpoint jarg1_);
public final static native long SBBreakpoint_FindLocationByAddress(long jarg1, SBBreakpoint jarg1_, java.math.BigInteger jarg2);
public final static native int SBBreakpoint_FindLocationIDByAddress(long jarg1, SBBreakpoint jarg1_, java.math.BigInteger jarg2);
public final static native long SBBreakpoint_FindLocationByID(long jarg1, SBBreakpoint jarg1_, int jarg2);
public final static native long SBBreakpoint_GetLocationAtIndex(long jarg1, SBBreakpoint jarg1_, long jarg2);
public final static native void SBBreakpoint_SetEnabled(long jarg1, SBBreakpoint jarg1_, boolean jarg2);
public final static native boolean SBBreakpoint_IsEnabled(long jarg1, SBBreakpoint jarg1_);
public final static native void SBBreakpoint_SetOneShot(long jarg1, SBBreakpoint jarg1_, boolean jarg2);
public final static native boolean SBBreakpoint_IsOneShot(long jarg1, SBBreakpoint jarg1_);
public final static native boolean SBBreakpoint_IsInternal(long jarg1, SBBreakpoint jarg1_);
public final static native long SBBreakpoint_GetHitCount(long jarg1, SBBreakpoint jarg1_);
public final static native void SBBreakpoint_SetIgnoreCount(long jarg1, SBBreakpoint jarg1_, long jarg2);
public final static native long SBBreakpoint_GetIgnoreCount(long jarg1, SBBreakpoint jarg1_);
public final static native void SBBreakpoint_SetCondition(long jarg1, SBBreakpoint jarg1_, String jarg2);
public final static native String SBBreakpoint_GetCondition(long jarg1, SBBreakpoint jarg1_);
public final static native void SBBreakpoint_SetAutoContinue(long jarg1, SBBreakpoint jarg1_, boolean jarg2);
public final static native boolean SBBreakpoint_GetAutoContinue(long jarg1, SBBreakpoint jarg1_);
public final static native void SBBreakpoint_SetThreadID(long jarg1, SBBreakpoint jarg1_, java.math.BigInteger jarg2);
public final static native java.math.BigInteger SBBreakpoint_GetThreadID(long jarg1, SBBreakpoint jarg1_);
public final static native void SBBreakpoint_SetThreadIndex(long jarg1, SBBreakpoint jarg1_, long jarg2);
public final static native long SBBreakpoint_GetThreadIndex(long jarg1, SBBreakpoint jarg1_);
public final static native void SBBreakpoint_SetThreadName(long jarg1, SBBreakpoint jarg1_, String jarg2);
public final static native String SBBreakpoint_GetThreadName(long jarg1, SBBreakpoint jarg1_);
public final static native void SBBreakpoint_SetQueueName(long jarg1, SBBreakpoint jarg1_, String jarg2);
public final static native String SBBreakpoint_GetQueueName(long jarg1, SBBreakpoint jarg1_);
public final static native void SBBreakpoint_SetScriptCallbackFunction__SWIG_0(long jarg1, SBBreakpoint jarg1_, String jarg2);
public final static native long SBBreakpoint_SetScriptCallbackFunction__SWIG_1(long jarg1, SBBreakpoint jarg1_, String jarg2, long jarg3, SBStructuredData jarg3_);
public final static native void SBBreakpoint_SetCommandLineCommands(long jarg1, SBBreakpoint jarg1_, long jarg2, SBStringList jarg2_);
public final static native boolean SBBreakpoint_GetCommandLineCommands(long jarg1, SBBreakpoint jarg1_, long jarg2, SBStringList jarg2_);
public final static native long SBBreakpoint_SetScriptCallbackBody(long jarg1, SBBreakpoint jarg1_, String jarg2);
public final static native boolean SBBreakpoint_AddName(long jarg1, SBBreakpoint jarg1_, String jarg2);
public final static native long SBBreakpoint_AddNameWithErrorHandling(long jarg1, SBBreakpoint jarg1_, String jarg2);
public final static native void SBBreakpoint_RemoveName(long jarg1, SBBreakpoint jarg1_, String jarg2);
public final static native boolean SBBreakpoint_MatchesName(long jarg1, SBBreakpoint jarg1_, String jarg2);
public final static native void SBBreakpoint_GetNames(long jarg1, SBBreakpoint jarg1_, long jarg2, SBStringList jarg2_);
public final static native long SBBreakpoint_GetNumResolvedLocations(long jarg1, SBBreakpoint jarg1_);
public final static native long SBBreakpoint_GetNumLocations(long jarg1, SBBreakpoint jarg1_);
public final static native boolean SBBreakpoint_GetDescription__SWIG_0(long jarg1, SBBreakpoint jarg1_, long jarg2, SBStream jarg2_);
public final static native boolean SBBreakpoint_GetDescription__SWIG_1(long jarg1, SBBreakpoint jarg1_, long jarg2, SBStream jarg2_, boolean jarg3);
public final static native boolean SBBreakpoint_EventIsBreakpointEvent(long jarg1, SBEvent jarg1_);
public final static native int SBBreakpoint_GetBreakpointEventTypeFromEvent(long jarg1, SBEvent jarg1_);
public final static native long SBBreakpoint_GetBreakpointFromEvent(long jarg1, SBEvent jarg1_);
public final static native long SBBreakpoint_GetBreakpointLocationAtIndexFromEvent(long jarg1, SBEvent jarg1_, long jarg2);
public final static native long SBBreakpoint_GetNumBreakpointLocationsFromEvent(long jarg1, SBEvent jarg1_);
public final static native boolean SBBreakpoint_IsHardware(long jarg1, SBBreakpoint jarg1_);
public final static native long SBBreakpoint_AddLocation(long jarg1, SBBreakpoint jarg1_, long jarg2, SBAddress jarg2_);
public final static native long SBBreakpoint_SerializeToStructuredData(long jarg1, SBBreakpoint jarg1_);
public final static native String SBBreakpoint___repr__(long jarg1, SBBreakpoint jarg1_);
public final static native long new_SBBreakpointList(long jarg1, SBTarget jarg1_);
public final static native void delete_SBBreakpointList(long jarg1);
public final static native long SBBreakpointList_GetSize(long jarg1, SBBreakpointList jarg1_);
public final static native long SBBreakpointList_GetBreakpointAtIndex(long jarg1, SBBreakpointList jarg1_, long jarg2);
public final static native long SBBreakpointList_FindBreakpointByID(long jarg1, SBBreakpointList jarg1_, int jarg2);
public final static native void SBBreakpointList_Append(long jarg1, SBBreakpointList jarg1_, long jarg2, SBBreakpoint jarg2_);
public final static native boolean SBBreakpointList_AppendIfUnique(long jarg1, SBBreakpointList jarg1_, long jarg2, SBBreakpoint jarg2_);
public final static native void SBBreakpointList_AppendByID(long jarg1, SBBreakpointList jarg1_, int jarg2);
public final static native void SBBreakpointList_Clear(long jarg1, SBBreakpointList jarg1_);
public final static native long new_SBBreakpointLocation__SWIG_0();
public final static native long new_SBBreakpointLocation__SWIG_1(long jarg1, SBBreakpointLocation jarg1_);
public final static native void delete_SBBreakpointLocation(long jarg1);
public final static native int SBBreakpointLocation_GetID(long jarg1, SBBreakpointLocation jarg1_);
public final static native boolean SBBreakpointLocation_IsValid(long jarg1, SBBreakpointLocation jarg1_);
public final static native long SBBreakpointLocation_GetAddress(long jarg1, SBBreakpointLocation jarg1_);
public final static native java.math.BigInteger SBBreakpointLocation_GetLoadAddress(long jarg1, SBBreakpointLocation jarg1_);
public final static native void SBBreakpointLocation_SetEnabled(long jarg1, SBBreakpointLocation jarg1_, boolean jarg2);
public final static native boolean SBBreakpointLocation_IsEnabled(long jarg1, SBBreakpointLocation jarg1_);
public final static native long SBBreakpointLocation_GetHitCount(long jarg1, SBBreakpointLocation jarg1_);
public final static native long SBBreakpointLocation_GetIgnoreCount(long jarg1, SBBreakpointLocation jarg1_);
public final static native void SBBreakpointLocation_SetIgnoreCount(long jarg1, SBBreakpointLocation jarg1_, long jarg2);
public final static native void SBBreakpointLocation_SetCondition(long jarg1, SBBreakpointLocation jarg1_, String jarg2);
public final static native String SBBreakpointLocation_GetCondition(long jarg1, SBBreakpointLocation jarg1_);
public final static native void SBBreakpointLocation_SetAutoContinue(long jarg1, SBBreakpointLocation jarg1_, boolean jarg2);
public final static native boolean SBBreakpointLocation_GetAutoContinue(long jarg1, SBBreakpointLocation jarg1_);
public final static native void SBBreakpointLocation_SetScriptCallbackFunction__SWIG_0(long jarg1, SBBreakpointLocation jarg1_, String jarg2);
public final static native long SBBreakpointLocation_SetScriptCallbackFunction__SWIG_1(long jarg1, SBBreakpointLocation jarg1_, String jarg2, long jarg3, SBStructuredData jarg3_);
public final static native long SBBreakpointLocation_SetScriptCallbackBody(long jarg1, SBBreakpointLocation jarg1_, String jarg2);
public final static native void SBBreakpointLocation_SetCommandLineCommands(long jarg1, SBBreakpointLocation jarg1_, long jarg2, SBStringList jarg2_);
public final static native boolean SBBreakpointLocation_GetCommandLineCommands(long jarg1, SBBreakpointLocation jarg1_, long jarg2, SBStringList jarg2_);
public final static native void SBBreakpointLocation_SetThreadID(long jarg1, SBBreakpointLocation jarg1_, java.math.BigInteger jarg2);
public final static native java.math.BigInteger SBBreakpointLocation_GetThreadID(long jarg1, SBBreakpointLocation jarg1_);
public final static native void SBBreakpointLocation_SetThreadIndex(long jarg1, SBBreakpointLocation jarg1_, long jarg2);
public final static native long SBBreakpointLocation_GetThreadIndex(long jarg1, SBBreakpointLocation jarg1_);
public final static native void SBBreakpointLocation_SetThreadName(long jarg1, SBBreakpointLocation jarg1_, String jarg2);
public final static native String SBBreakpointLocation_GetThreadName(long jarg1, SBBreakpointLocation jarg1_);
public final static native void SBBreakpointLocation_SetQueueName(long jarg1, SBBreakpointLocation jarg1_, String jarg2);
public final static native String SBBreakpointLocation_GetQueueName(long jarg1, SBBreakpointLocation jarg1_);
public final static native boolean SBBreakpointLocation_IsResolved(long jarg1, SBBreakpointLocation jarg1_);
public final static native boolean SBBreakpointLocation_GetDescription(long jarg1, SBBreakpointLocation jarg1_, long jarg2, SBStream jarg2_, int jarg3);
public final static native long SBBreakpointLocation_GetBreakpoint(long jarg1, SBBreakpointLocation jarg1_);
public final static native String SBBreakpointLocation___repr__(long jarg1, SBBreakpointLocation jarg1_);
public final static native long new_SBBreakpointName__SWIG_0();
public final static native long new_SBBreakpointName__SWIG_1(long jarg1, SBTarget jarg1_, String jarg2);
public final static native long new_SBBreakpointName__SWIG_2(long jarg1, SBBreakpoint jarg1_, String jarg2);
public final static native long new_SBBreakpointName__SWIG_3(long jarg1, SBBreakpointName jarg1_);
public final static native void delete_SBBreakpointName(long jarg1);
public final static native boolean SBBreakpointName_IsValid(long jarg1, SBBreakpointName jarg1_);
public final static native String SBBreakpointName_GetName(long jarg1, SBBreakpointName jarg1_);
public final static native void SBBreakpointName_SetEnabled(long jarg1, SBBreakpointName jarg1_, boolean jarg2);
public final static native boolean SBBreakpointName_IsEnabled(long jarg1, SBBreakpointName jarg1_);
public final static native void SBBreakpointName_SetOneShot(long jarg1, SBBreakpointName jarg1_, boolean jarg2);
public final static native boolean SBBreakpointName_IsOneShot(long jarg1, SBBreakpointName jarg1_);
public final static native void SBBreakpointName_SetIgnoreCount(long jarg1, SBBreakpointName jarg1_, long jarg2);
public final static native long SBBreakpointName_GetIgnoreCount(long jarg1, SBBreakpointName jarg1_);
public final static native void SBBreakpointName_SetCondition(long jarg1, SBBreakpointName jarg1_, String jarg2);
public final static native String SBBreakpointName_GetCondition(long jarg1, SBBreakpointName jarg1_);
public final static native void SBBreakpointName_SetAutoContinue(long jarg1, SBBreakpointName jarg1_, boolean jarg2);
public final static native boolean SBBreakpointName_GetAutoContinue(long jarg1, SBBreakpointName jarg1_);
public final static native void SBBreakpointName_SetThreadID(long jarg1, SBBreakpointName jarg1_, java.math.BigInteger jarg2);
public final static native java.math.BigInteger SBBreakpointName_GetThreadID(long jarg1, SBBreakpointName jarg1_);
public final static native void SBBreakpointName_SetThreadIndex(long jarg1, SBBreakpointName jarg1_, long jarg2);
public final static native long SBBreakpointName_GetThreadIndex(long jarg1, SBBreakpointName jarg1_);
public final static native void SBBreakpointName_SetThreadName(long jarg1, SBBreakpointName jarg1_, String jarg2);
public final static native String SBBreakpointName_GetThreadName(long jarg1, SBBreakpointName jarg1_);
public final static native void SBBreakpointName_SetQueueName(long jarg1, SBBreakpointName jarg1_, String jarg2);
public final static native String SBBreakpointName_GetQueueName(long jarg1, SBBreakpointName jarg1_);
public final static native void SBBreakpointName_SetScriptCallbackFunction__SWIG_0(long jarg1, SBBreakpointName jarg1_, String jarg2);
public final static native long SBBreakpointName_SetScriptCallbackFunction__SWIG_1(long jarg1, SBBreakpointName jarg1_, String jarg2, long jarg3, SBStructuredData jarg3_);
public final static native void SBBreakpointName_SetCommandLineCommands(long jarg1, SBBreakpointName jarg1_, long jarg2, SBStringList jarg2_);
public final static native boolean SBBreakpointName_GetCommandLineCommands(long jarg1, SBBreakpointName jarg1_, long jarg2, SBStringList jarg2_);
public final static native long SBBreakpointName_SetScriptCallbackBody(long jarg1, SBBreakpointName jarg1_, String jarg2);
public final static native String SBBreakpointName_GetHelpString(long jarg1, SBBreakpointName jarg1_);
public final static native void SBBreakpointName_SetHelpString(long jarg1, SBBreakpointName jarg1_, String jarg2);
public final static native boolean SBBreakpointName_GetAllowList(long jarg1, SBBreakpointName jarg1_);
public final static native void SBBreakpointName_SetAllowList(long jarg1, SBBreakpointName jarg1_, boolean jarg2);
public final static native boolean SBBreakpointName_GetAllowDelete(long jarg1, SBBreakpointName jarg1_);
public final static native void SBBreakpointName_SetAllowDelete(long jarg1, SBBreakpointName jarg1_, boolean jarg2);
public final static native boolean SBBreakpointName_GetAllowDisable(long jarg1, SBBreakpointName jarg1_);
public final static native void SBBreakpointName_SetAllowDisable(long jarg1, SBBreakpointName jarg1_, boolean jarg2);
public final static native boolean SBBreakpointName_GetDescription(long jarg1, SBBreakpointName jarg1_, long jarg2, SBStream jarg2_);
public final static native String SBBreakpointName___repr__(long jarg1, SBBreakpointName jarg1_);
public final static native long new_SBBroadcaster__SWIG_0();
public final static native long new_SBBroadcaster__SWIG_1(String jarg1);
public final static native long new_SBBroadcaster__SWIG_2(long jarg1, SBBroadcaster jarg1_);
public final static native void delete_SBBroadcaster(long jarg1);
public final static native boolean SBBroadcaster_IsValid(long jarg1, SBBroadcaster jarg1_);
public final static native void SBBroadcaster_Clear(long jarg1, SBBroadcaster jarg1_);
public final static native void SBBroadcaster_BroadcastEventByType__SWIG_0(long jarg1, SBBroadcaster jarg1_, long jarg2, boolean jarg3);
public final static native void SBBroadcaster_BroadcastEventByType__SWIG_1(long jarg1, SBBroadcaster jarg1_, long jarg2);
public final static native void SBBroadcaster_BroadcastEvent__SWIG_0(long jarg1, SBBroadcaster jarg1_, long jarg2, SBEvent jarg2_, boolean jarg3);
public final static native void SBBroadcaster_BroadcastEvent__SWIG_1(long jarg1, SBBroadcaster jarg1_, long jarg2, SBEvent jarg2_);
public final static native void SBBroadcaster_AddInitialEventsToListener(long jarg1, SBBroadcaster jarg1_, long jarg2, SBListener jarg2_, long jarg3);
public final static native long SBBroadcaster_AddListener(long jarg1, SBBroadcaster jarg1_, long jarg2, SBListener jarg2_, long jarg3);
public final static native String SBBroadcaster_GetName(long jarg1, SBBroadcaster jarg1_);
public final static native boolean SBBroadcaster_EventTypeHasListeners(long jarg1, SBBroadcaster jarg1_, long jarg2);
public final static native boolean SBBroadcaster_RemoveListener__SWIG_0(long jarg1, SBBroadcaster jarg1_, long jarg2, SBListener jarg2_, long jarg3);
public final static native boolean SBBroadcaster_RemoveListener__SWIG_1(long jarg1, SBBroadcaster jarg1_, long jarg2, SBListener jarg2_);
public final static native int SBCommandInterpreter_eBroadcastBitThreadShouldExit_get();
public final static native int SBCommandInterpreter_eBroadcastBitResetPrompt_get();
public final static native int SBCommandInterpreter_eBroadcastBitQuitCommandReceived_get();
public final static native int SBCommandInterpreter_eBroadcastBitAsynchronousOutputData_get();
public final static native int SBCommandInterpreter_eBroadcastBitAsynchronousErrorData_get();
public final static native long new_SBCommandInterpreter(long jarg1, SBCommandInterpreter jarg1_);
public final static native void delete_SBCommandInterpreter(long jarg1);
public final static native String SBCommandInterpreter_GetArgumentTypeAsCString(int jarg1);
public final static native String SBCommandInterpreter_GetArgumentDescriptionAsCString(int jarg1);
public final static native boolean SBCommandInterpreter_EventIsCommandInterpreterEvent(long jarg1, SBEvent jarg1_);
public final static native boolean SBCommandInterpreter_IsValid(long jarg1, SBCommandInterpreter jarg1_);
public final static native boolean SBCommandInterpreter_CommandExists(long jarg1, SBCommandInterpreter jarg1_, String jarg2);
public final static native boolean SBCommandInterpreter_UserCommandExists(long jarg1, SBCommandInterpreter jarg1_, String jarg2);
public final static native boolean SBCommandInterpreter_AliasExists(long jarg1, SBCommandInterpreter jarg1_, String jarg2);
public final static native long SBCommandInterpreter_GetBroadcaster(long jarg1, SBCommandInterpreter jarg1_);
public final static native String SBCommandInterpreter_GetBroadcasterClass();
public final static native boolean SBCommandInterpreter_HasCommands(long jarg1, SBCommandInterpreter jarg1_);
public final static native boolean SBCommandInterpreter_HasAliases(long jarg1, SBCommandInterpreter jarg1_);
public final static native boolean SBCommandInterpreter_HasAliasOptions(long jarg1, SBCommandInterpreter jarg1_);
public final static native boolean SBCommandInterpreter_IsInteractive(long jarg1, SBCommandInterpreter jarg1_);
public final static native long SBCommandInterpreter_GetProcess(long jarg1, SBCommandInterpreter jarg1_);
public final static native long SBCommandInterpreter_GetDebugger(long jarg1, SBCommandInterpreter jarg1_);
public final static native void SBCommandInterpreter_SourceInitFileInHomeDirectory__SWIG_0(long jarg1, SBCommandInterpreter jarg1_, long jarg2, SBCommandReturnObject jarg2_);
public final static native void SBCommandInterpreter_SourceInitFileInHomeDirectory__SWIG_1(long jarg1, SBCommandInterpreter jarg1_, long jarg2, SBCommandReturnObject jarg2_, boolean jarg3);
public final static native void SBCommandInterpreter_SourceInitFileInCurrentWorkingDirectory(long jarg1, SBCommandInterpreter jarg1_, long jarg2, SBCommandReturnObject jarg2_);
public final static native int SBCommandInterpreter_HandleCommand__SWIG_0(long jarg1, SBCommandInterpreter jarg1_, String jarg2, long jarg3, SBCommandReturnObject jarg3_, boolean jarg4);
public final static native int SBCommandInterpreter_HandleCommand__SWIG_1(long jarg1, SBCommandInterpreter jarg1_, String jarg2, long jarg3, SBCommandReturnObject jarg3_);
public final static native int SBCommandInterpreter_HandleCommand__SWIG_2(long jarg1, SBCommandInterpreter jarg1_, String jarg2, long jarg3, SBExecutionContext jarg3_, long jarg4, SBCommandReturnObject jarg4_, boolean jarg5);
public final static native int SBCommandInterpreter_HandleCommand__SWIG_3(long jarg1, SBCommandInterpreter jarg1_, String jarg2, long jarg3, SBExecutionContext jarg3_, long jarg4, SBCommandReturnObject jarg4_);
public final static native void SBCommandInterpreter_HandleCommandsFromFile(long jarg1, SBCommandInterpreter jarg1_, long jarg2, SBFileSpec jarg2_, long jarg3, SBExecutionContext jarg3_, long jarg4, SBCommandInterpreterRunOptions jarg4_, long jarg5, SBCommandReturnObject jarg5_);
public final static native int SBCommandInterpreter_HandleCompletion(long jarg1, SBCommandInterpreter jarg1_, String jarg2, long jarg3, int jarg4, int jarg5, long jarg6, SBStringList jarg6_);
public final static native int SBCommandInterpreter_HandleCompletionWithDescriptions(long jarg1, SBCommandInterpreter jarg1_, String jarg2, long jarg3, int jarg4, int jarg5, long jarg6, SBStringList jarg6_, long jarg7, SBStringList jarg7_);
public final static native boolean SBCommandInterpreter_WasInterrupted(long jarg1, SBCommandInterpreter jarg1_);
public final static native boolean SBCommandInterpreter_InterruptCommand(long jarg1, SBCommandInterpreter jarg1_);
public final static native boolean SBCommandInterpreter_IsActive(long jarg1, SBCommandInterpreter jarg1_);
public final static native String SBCommandInterpreter_GetIOHandlerControlSequence(long jarg1, SBCommandInterpreter jarg1_, char jarg2);
public final static native boolean SBCommandInterpreter_GetPromptOnQuit(long jarg1, SBCommandInterpreter jarg1_);
public final static native void SBCommandInterpreter_SetPromptOnQuit(long jarg1, SBCommandInterpreter jarg1_, boolean jarg2);
public final static native void SBCommandInterpreter_AllowExitCodeOnQuit(long jarg1, SBCommandInterpreter jarg1_, boolean jarg2);
public final static native boolean SBCommandInterpreter_HasCustomQuitExitCode(long jarg1, SBCommandInterpreter jarg1_);
public final static native int SBCommandInterpreter_GetQuitStatus(long jarg1, SBCommandInterpreter jarg1_);
public final static native void SBCommandInterpreter_ResolveCommand(long jarg1, SBCommandInterpreter jarg1_, String jarg2, long jarg3, SBCommandReturnObject jarg3_);
public final static native long new_SBCommandInterpreterRunOptions__SWIG_0();
public final static native long new_SBCommandInterpreterRunOptions__SWIG_1(long jarg1, SBCommandInterpreterRunOptions jarg1_);
public final static native void delete_SBCommandInterpreterRunOptions(long jarg1);
public final static native boolean SBCommandInterpreterRunOptions_GetStopOnContinue(long jarg1, SBCommandInterpreterRunOptions jarg1_);
public final static native void SBCommandInterpreterRunOptions_SetStopOnContinue(long jarg1, SBCommandInterpreterRunOptions jarg1_, boolean jarg2);
public final static native boolean SBCommandInterpreterRunOptions_GetStopOnError(long jarg1, SBCommandInterpreterRunOptions jarg1_);
public final static native void SBCommandInterpreterRunOptions_SetStopOnError(long jarg1, SBCommandInterpreterRunOptions jarg1_, boolean jarg2);
public final static native boolean SBCommandInterpreterRunOptions_GetStopOnCrash(long jarg1, SBCommandInterpreterRunOptions jarg1_);
public final static native void SBCommandInterpreterRunOptions_SetStopOnCrash(long jarg1, SBCommandInterpreterRunOptions jarg1_, boolean jarg2);
public final static native boolean SBCommandInterpreterRunOptions_GetEchoCommands(long jarg1, SBCommandInterpreterRunOptions jarg1_);
public final static native void SBCommandInterpreterRunOptions_SetEchoCommands(long jarg1, SBCommandInterpreterRunOptions jarg1_, boolean jarg2);
public final static native boolean SBCommandInterpreterRunOptions_GetEchoCommentCommands(long jarg1, SBCommandInterpreterRunOptions jarg1_);
public final static native void SBCommandInterpreterRunOptions_SetEchoCommentCommands(long jarg1, SBCommandInterpreterRunOptions jarg1_, boolean jarg2);
public final static native boolean SBCommandInterpreterRunOptions_GetPrintResults(long jarg1, SBCommandInterpreterRunOptions jarg1_);
public final static native void SBCommandInterpreterRunOptions_SetPrintResults(long jarg1, SBCommandInterpreterRunOptions jarg1_, boolean jarg2);
public final static native boolean SBCommandInterpreterRunOptions_GetPrintErrors(long jarg1, SBCommandInterpreterRunOptions jarg1_);
public final static native void SBCommandInterpreterRunOptions_SetPrintErrors(long jarg1, SBCommandInterpreterRunOptions jarg1_, boolean jarg2);
public final static native boolean SBCommandInterpreterRunOptions_GetAddToHistory(long jarg1, SBCommandInterpreterRunOptions jarg1_);
public final static native void SBCommandInterpreterRunOptions_SetAddToHistory(long jarg1, SBCommandInterpreterRunOptions jarg1_, boolean jarg2);
public final static native boolean SBCommandInterpreterRunOptions_GetAutoHandleEvents(long jarg1, SBCommandInterpreterRunOptions jarg1_);
public final static native void SBCommandInterpreterRunOptions_SetAutoHandleEvents(long jarg1, SBCommandInterpreterRunOptions jarg1_, boolean jarg2);
public final static native boolean SBCommandInterpreterRunOptions_GetSpawnThread(long jarg1, SBCommandInterpreterRunOptions jarg1_);
public final static native void SBCommandInterpreterRunOptions_SetSpawnThread(long jarg1, SBCommandInterpreterRunOptions jarg1_, boolean jarg2);
public final static native long new_SBCommandReturnObject__SWIG_0();
public final static native long new_SBCommandReturnObject__SWIG_1(long jarg1, SBCommandReturnObject jarg1_);
public final static native void delete_SBCommandReturnObject(long jarg1);
public final static native boolean SBCommandReturnObject_IsValid(long jarg1, SBCommandReturnObject jarg1_);
public final static native String SBCommandReturnObject_GetOutput__SWIG_0(long jarg1, SBCommandReturnObject jarg1_);
public final static native String SBCommandReturnObject_GetError__SWIG_0(long jarg1, SBCommandReturnObject jarg1_);
public final static native long SBCommandReturnObject_PutOutput__SWIG_0(long jarg1, SBCommandReturnObject jarg1_, long jarg2, SBFile jarg2_);
public final static native long SBCommandReturnObject_PutOutput__SWIG_1(long jarg1, SBCommandReturnObject jarg1_, long jarg2);
public final static native long SBCommandReturnObject_GetOutputSize(long jarg1, SBCommandReturnObject jarg1_);
public final static native long SBCommandReturnObject_GetErrorSize(long jarg1, SBCommandReturnObject jarg1_);
public final static native long SBCommandReturnObject_PutError__SWIG_0(long jarg1, SBCommandReturnObject jarg1_, long jarg2, SBFile jarg2_);
public final static native long SBCommandReturnObject_PutError__SWIG_1(long jarg1, SBCommandReturnObject jarg1_, long jarg2);
public final static native void SBCommandReturnObject_Clear(long jarg1, SBCommandReturnObject jarg1_);
public final static native int SBCommandReturnObject_GetStatus(long jarg1, SBCommandReturnObject jarg1_);
public final static native void SBCommandReturnObject_SetStatus(long jarg1, SBCommandReturnObject jarg1_, int jarg2);
public final static native boolean SBCommandReturnObject_Succeeded(long jarg1, SBCommandReturnObject jarg1_);
public final static native boolean SBCommandReturnObject_HasResult(long jarg1, SBCommandReturnObject jarg1_);
public final static native void SBCommandReturnObject_AppendMessage(long jarg1, SBCommandReturnObject jarg1_, String jarg2);
public final static native void SBCommandReturnObject_AppendWarning(long jarg1, SBCommandReturnObject jarg1_, String jarg2);
public final static native boolean SBCommandReturnObject_GetDescription(long jarg1, SBCommandReturnObject jarg1_, long jarg2, SBStream jarg2_);
public final static native void SBCommandReturnObject_SetImmediateOutputFile__SWIG_0(long jarg1, SBCommandReturnObject jarg1_, long jarg2, SBFile jarg2_);
public final static native void SBCommandReturnObject_SetImmediateErrorFile__SWIG_0(long jarg1, SBCommandReturnObject jarg1_, long jarg2, SBFile jarg2_);
public final static native void SBCommandReturnObject_SetImmediateOutputFile__SWIG_1(long jarg1, SBCommandReturnObject jarg1_, long jarg2);
public final static native void SBCommandReturnObject_SetImmediateErrorFile__SWIG_1(long jarg1, SBCommandReturnObject jarg1_, long jarg2);
public final static native void SBCommandReturnObject_PutCString__SWIG_0(long jarg1, SBCommandReturnObject jarg1_, String jarg2, int jarg3);
public final static native void SBCommandReturnObject_PutCString__SWIG_1(long jarg1, SBCommandReturnObject jarg1_, String jarg2);
public final static native String SBCommandReturnObject_GetOutput__SWIG_1(long jarg1, SBCommandReturnObject jarg1_, boolean jarg2);
public final static native String SBCommandReturnObject_GetError__SWIG_1(long jarg1, SBCommandReturnObject jarg1_, boolean jarg2);
public final static native void SBCommandReturnObject_SetError__SWIG_0(long jarg1, SBCommandReturnObject jarg1_, long jarg2, SBError jarg2_, String jarg3);
public final static native void SBCommandReturnObject_SetError__SWIG_1(long jarg1, SBCommandReturnObject jarg1_, long jarg2, SBError jarg2_);
public final static native void SBCommandReturnObject_SetError__SWIG_2(long jarg1, SBCommandReturnObject jarg1_, String jarg2);
public final static native String SBCommandReturnObject___repr__(long jarg1, SBCommandReturnObject jarg1_);
public final static native void SBCommandReturnObject_SetImmediateOutputFile__SWIG_2(long jarg1, SBCommandReturnObject jarg1_, long jarg2, boolean jarg3);
public final static native void SBCommandReturnObject_SetImmediateErrorFile__SWIG_2(long jarg1, SBCommandReturnObject jarg1_, long jarg2, boolean jarg3);
public final static native void SBCommandReturnObject_Print(long jarg1, SBCommandReturnObject jarg1_, String jarg2);
public final static native int SBCommunication_eBroadcastBitDisconnected_get();
public final static native int SBCommunication_eBroadcastBitReadThreadGotBytes_get();
public final static native int SBCommunication_eBroadcastBitReadThreadDidExit_get();
public final static native int SBCommunication_eBroadcastBitReadThreadShouldExit_get();
public final static native int SBCommunication_eBroadcastBitPacketAvailable_get();
public final static native int SBCommunication_eAllEventBits_get();
public final static native long new_SBCommunication__SWIG_0();
public final static native long new_SBCommunication__SWIG_1(String jarg1);
public final static native void delete_SBCommunication(long jarg1);
public final static native boolean SBCommunication_IsValid(long jarg1, SBCommunication jarg1_);
public final static native long SBCommunication_GetBroadcaster(long jarg1, SBCommunication jarg1_);
public final static native String SBCommunication_GetBroadcasterClass();
public final static native int SBCommunication_AdoptFileDesriptor(long jarg1, SBCommunication jarg1_, int jarg2, boolean jarg3);
public final static native int SBCommunication_Connect(long jarg1, SBCommunication jarg1_, String jarg2);
public final static native int SBCommunication_Disconnect(long jarg1, SBCommunication jarg1_);
public final static native boolean SBCommunication_IsConnected(long jarg1, SBCommunication jarg1_);
public final static native boolean SBCommunication_GetCloseOnEOF(long jarg1, SBCommunication jarg1_);
public final static native void SBCommunication_SetCloseOnEOF(long jarg1, SBCommunication jarg1_, boolean jarg2);
public final static native long SBCommunication_Read(long jarg1, SBCommunication jarg1_, long jarg2, long jarg3, long jarg4, long jarg5);
public final static native long SBCommunication_Write(long jarg1, SBCommunication jarg1_, long jarg2, long jarg3, long jarg4);
public final static native boolean SBCommunication_ReadThreadStart(long jarg1, SBCommunication jarg1_);
public final static native boolean SBCommunication_ReadThreadStop(long jarg1, SBCommunication jarg1_);
public final static native boolean SBCommunication_ReadThreadIsRunning(long jarg1, SBCommunication jarg1_);
public final static native boolean SBCommunication_SetReadThreadBytesReceivedCallback(long jarg1, SBCommunication jarg1_, long jarg2, long jarg3);
public final static native long new_SBCompileUnit__SWIG_0();
public final static native long new_SBCompileUnit__SWIG_1(long jarg1, SBCompileUnit jarg1_);
public final static native void delete_SBCompileUnit(long jarg1);
public final static native boolean SBCompileUnit_IsValid(long jarg1, SBCompileUnit jarg1_);
public final static native long SBCompileUnit_GetFileSpec(long jarg1, SBCompileUnit jarg1_);
public final static native long SBCompileUnit_GetNumLineEntries(long jarg1, SBCompileUnit jarg1_);
public final static native long SBCompileUnit_GetLineEntryAtIndex(long jarg1, SBCompileUnit jarg1_, long jarg2);
public final static native long SBCompileUnit_FindLineEntryIndex__SWIG_0(long jarg1, SBCompileUnit jarg1_, long jarg2, SBLineEntry jarg2_, boolean jarg3);
public final static native long SBCompileUnit_FindLineEntryIndex__SWIG_1(long jarg1, SBCompileUnit jarg1_, long jarg2, SBLineEntry jarg2_);
public final static native long SBCompileUnit_FindLineEntryIndex__SWIG_2(long jarg1, SBCompileUnit jarg1_, long jarg2, long jarg3, long jarg4, SBFileSpec jarg4_);
public final static native long SBCompileUnit_FindLineEntryIndex__SWIG_3(long jarg1, SBCompileUnit jarg1_, long jarg2, long jarg3, long jarg4, SBFileSpec jarg4_, boolean jarg5);
public final static native long SBCompileUnit_GetSupportFileAtIndex(long jarg1, SBCompileUnit jarg1_, long jarg2);
public final static native long SBCompileUnit_GetNumSupportFiles(long jarg1, SBCompileUnit jarg1_);
public final static native long SBCompileUnit_FindSupportFileIndex(long jarg1, SBCompileUnit jarg1_, long jarg2, long jarg3, SBFileSpec jarg3_, boolean jarg4);
public final static native long SBCompileUnit_GetTypes__SWIG_0(long jarg1, SBCompileUnit jarg1_, long jarg2);
public final static native long SBCompileUnit_GetTypes__SWIG_1(long jarg1, SBCompileUnit jarg1_);
public final static native int SBCompileUnit_GetLanguage(long jarg1, SBCompileUnit jarg1_);
public final static native boolean SBCompileUnit_GetDescription(long jarg1, SBCompileUnit jarg1_, long jarg2, SBStream jarg2_);
public final static native String SBCompileUnit___repr__(long jarg1, SBCompileUnit jarg1_);
public final static native long new_SBData__SWIG_0();
public final static native long new_SBData__SWIG_1(long jarg1, SBData jarg1_);
public final static native void delete_SBData(long jarg1);
public final static native short SBData_GetAddressByteSize(long jarg1, SBData jarg1_);
public final static native void SBData_SetAddressByteSize(long jarg1, SBData jarg1_, short jarg2);
public final static native void SBData_Clear(long jarg1, SBData jarg1_);
public final static native boolean SBData_IsValid(long jarg1, SBData jarg1_);
public final static native long SBData_GetByteSize(long jarg1, SBData jarg1_);
public final static native int SBData_GetByteOrder(long jarg1, SBData jarg1_);
public final static native void SBData_SetByteOrder(long jarg1, SBData jarg1_, int jarg2);
public final static native float SBData_GetFloat(long jarg1, SBData jarg1_, long jarg2, SBError jarg2_, java.math.BigInteger jarg3);
public final static native double SBData_GetDouble(long jarg1, SBData jarg1_, long jarg2, SBError jarg2_, java.math.BigInteger jarg3);
public final static native long SBData_GetLongDouble(long jarg1, SBData jarg1_, long jarg2, SBError jarg2_, java.math.BigInteger jarg3);
public final static native java.math.BigInteger SBData_GetAddress(long jarg1, SBData jarg1_, long jarg2, SBError jarg2_, java.math.BigInteger jarg3);
public final static native short SBData_GetUnsignedInt8(long jarg1, SBData jarg1_, long jarg2, SBError jarg2_, java.math.BigInteger jarg3);
public final static native int SBData_GetUnsignedInt16(long jarg1, SBData jarg1_, long jarg2, SBError jarg2_, java.math.BigInteger jarg3);
public final static native long SBData_GetUnsignedInt32(long jarg1, SBData jarg1_, long jarg2, SBError jarg2_, java.math.BigInteger jarg3);
public final static native java.math.BigInteger SBData_GetUnsignedInt64(long jarg1, SBData jarg1_, long jarg2, SBError jarg2_, java.math.BigInteger jarg3);
public final static native byte SBData_GetSignedInt8(long jarg1, SBData jarg1_, long jarg2, SBError jarg2_, java.math.BigInteger jarg3);
public final static native short SBData_GetSignedInt16(long jarg1, SBData jarg1_, long jarg2, SBError jarg2_, java.math.BigInteger jarg3);
public final static native int SBData_GetSignedInt32(long jarg1, SBData jarg1_, long jarg2, SBError jarg2_, java.math.BigInteger jarg3);
public final static native long SBData_GetSignedInt64(long jarg1, SBData jarg1_, long jarg2, SBError jarg2_, java.math.BigInteger jarg3);
public final static native String SBData_GetString(long jarg1, SBData jarg1_, long jarg2, SBError jarg2_, java.math.BigInteger jarg3);
public final static native long SBData_ReadRawData(long jarg1, SBData jarg1_, long jarg2, SBError jarg2_, java.math.BigInteger jarg3, long jarg4, long jarg5);
public final static native boolean SBData_GetDescription__SWIG_0(long jarg1, SBData jarg1_, long jarg2, SBStream jarg2_, java.math.BigInteger jarg3);
public final static native boolean SBData_GetDescription__SWIG_1(long jarg1, SBData jarg1_, long jarg2, SBStream jarg2_);
public final static native void SBData_SetData(long jarg1, SBData jarg1_, long jarg2, SBError jarg2_, long jarg3, long jarg4, int jarg5, short jarg6);
public final static native void SBData_SetDataWithOwnership(long jarg1, SBData jarg1_, long jarg2, SBError jarg2_, long jarg3, long jarg4, int jarg5, short jarg6);
public final static native boolean SBData_Append(long jarg1, SBData jarg1_, long jarg2, SBData jarg2_);
public final static native long SBData_CreateDataFromCString(int jarg1, long jarg2, String jarg3);
public final static native long SBData_CreateDataFromUInt64Array(int jarg1, long jarg2, long jarg3, long jarg4);
public final static native long SBData_CreateDataFromUInt32Array(int jarg1, long jarg2, long jarg3, long jarg4);
public final static native long SBData_CreateDataFromSInt64Array(int jarg1, long jarg2, long jarg3, long jarg4);
public final static native long SBData_CreateDataFromSInt32Array(int jarg1, long jarg2, long jarg3, long jarg4);
public final static native long SBData_CreateDataFromDoubleArray(int jarg1, long jarg2, long jarg3, long jarg4);
public final static native boolean SBData_SetDataFromCString(long jarg1, SBData jarg1_, String jarg2);
public final static native boolean SBData_SetDataFromUInt64Array(long jarg1, SBData jarg1_, long jarg2, long jarg3);
public final static native boolean SBData_SetDataFromUInt32Array(long jarg1, SBData jarg1_, long jarg2, long jarg3);
public final static native boolean SBData_SetDataFromSInt64Array(long jarg1, SBData jarg1_, long jarg2, long jarg3);
public final static native boolean SBData_SetDataFromSInt32Array(long jarg1, SBData jarg1_, long jarg2, long jarg3);
public final static native boolean SBData_SetDataFromDoubleArray(long jarg1, SBData jarg1_, long jarg2, long jarg3);
public final static native String SBData___repr__(long jarg1, SBData jarg1_);
public final static native int SBDebugger_eBroadcastBitProgress_get();
public final static native int SBDebugger_eBroadcastBitWarning_get();
public final static native int SBDebugger_eBroadcastBitError_get();
public final static native long new_SBDebugger__SWIG_0();
public final static native long new_SBDebugger__SWIG_1(long jarg1, SBDebugger jarg1_);
public final static native void delete_SBDebugger(long jarg1);
public final static native String SBDebugger_GetBroadcasterClass();
public final static native long SBDebugger_GetBroadcaster(long jarg1, SBDebugger jarg1_);
public final static native String SBDebugger_GetProgressFromEvent(long jarg1, SBEvent jarg1_, java.math.BigInteger[] jarg2, java.math.BigInteger[] jarg3, java.math.BigInteger[] jarg4, boolean[] jarg5);
public final static native long SBDebugger_GetProgressDataFromEvent(long jarg1, SBEvent jarg1_);
public final static native long SBDebugger_GetDiagnosticFromEvent(long jarg1, SBEvent jarg1_);
public final static native void SBDebugger_Initialize();
public final static native long SBDebugger_InitializeWithErrorHandling();
public final static native void SBDebugger_PrintStackTraceOnError();
public final static native void SBDebugger_PrintDiagnosticsOnError();
public final static native void SBDebugger_Terminate();
public final static native long SBDebugger_Create__SWIG_0();
public final static native long SBDebugger_Create__SWIG_1(boolean jarg1);
public final static native long SBDebugger_Create__SWIG_2(boolean jarg1, long jarg2, long jarg3);
public final static native void SBDebugger_Destroy(long jarg1, SBDebugger jarg1_);
public final static native void SBDebugger_MemoryPressureDetected();
public final static native boolean SBDebugger_IsValid(long jarg1, SBDebugger jarg1_);
public final static native void SBDebugger_Clear(long jarg1, SBDebugger jarg1_);
public final static native long SBDebugger_GetSetting__SWIG_0(long jarg1, SBDebugger jarg1_, String jarg2);
public final static native long SBDebugger_GetSetting__SWIG_1(long jarg1, SBDebugger jarg1_);
public final static native void SBDebugger_SetAsync(long jarg1, SBDebugger jarg1_, boolean jarg2);
public final static native boolean SBDebugger_GetAsync(long jarg1, SBDebugger jarg1_);
public final static native void SBDebugger_SkipLLDBInitFiles(long jarg1, SBDebugger jarg1_, boolean jarg2);
public final static native void SBDebugger_SkipAppInitFiles(long jarg1, SBDebugger jarg1_, boolean jarg2);
public final static native long SBDebugger_SetInputString(long jarg1, SBDebugger jarg1_, String jarg2);
public final static native long SBDebugger_SetInputFile__SWIG_0(long jarg1, SBDebugger jarg1_, long jarg2, SBFile jarg2_);
public final static native long SBDebugger_SetOutputFile__SWIG_0(long jarg1, SBDebugger jarg1_, long jarg2, SBFile jarg2_);
public final static native long SBDebugger_SetErrorFile__SWIG_0(long jarg1, SBDebugger jarg1_, long jarg2, SBFile jarg2_);
public final static native long SBDebugger_SetInputFile__SWIG_1(long jarg1, SBDebugger jarg1_, long jarg2);
public final static native long SBDebugger_SetOutputFile__SWIG_1(long jarg1, SBDebugger jarg1_, long jarg2);
public final static native long SBDebugger_SetErrorFile__SWIG_1(long jarg1, SBDebugger jarg1_, long jarg2);
public final static native long SBDebugger_GetInputFile(long jarg1, SBDebugger jarg1_);
public final static native long SBDebugger_GetOutputFile(long jarg1, SBDebugger jarg1_);
public final static native long SBDebugger_GetErrorFile(long jarg1, SBDebugger jarg1_);
public final static native void SBDebugger_SaveInputTerminalState(long jarg1, SBDebugger jarg1_);
public final static native void SBDebugger_RestoreInputTerminalState(long jarg1, SBDebugger jarg1_);
public final static native long SBDebugger_GetCommandInterpreter(long jarg1, SBDebugger jarg1_);
public final static native void SBDebugger_HandleCommand(long jarg1, SBDebugger jarg1_, String jarg2);
public final static native void SBDebugger_RequestInterrupt(long jarg1, SBDebugger jarg1_);
public final static native void SBDebugger_CancelInterruptRequest(long jarg1, SBDebugger jarg1_);
public final static native boolean SBDebugger_InterruptRequested(long jarg1, SBDebugger jarg1_);
public final static native long SBDebugger_GetListener(long jarg1, SBDebugger jarg1_);
public final static native void SBDebugger_HandleProcessEvent__SWIG_0(long jarg1, SBDebugger jarg1_, long jarg2, SBProcess jarg2_, long jarg3, SBEvent jarg3_, long jarg4, SBFile jarg4_, long jarg5, SBFile jarg5_);
public final static native void SBDebugger_HandleProcessEvent__SWIG_1(long jarg1, SBDebugger jarg1_, long jarg2, SBProcess jarg2_, long jarg3, SBEvent jarg3_, long jarg4, long jarg5);
public final static native long SBDebugger_CreateTarget__SWIG_0(long jarg1, SBDebugger jarg1_, String jarg2, String jarg3, String jarg4, boolean jarg5, long jarg6, SBError jarg6_);
public final static native long SBDebugger_CreateTargetWithFileAndTargetTriple(long jarg1, SBDebugger jarg1_, String jarg2, String jarg3);
public final static native long SBDebugger_CreateTargetWithFileAndArch(long jarg1, SBDebugger jarg1_, String jarg2, String jarg3);
public final static native long SBDebugger_CreateTarget__SWIG_1(long jarg1, SBDebugger jarg1_, String jarg2);
public final static native long SBDebugger_GetDummyTarget(long jarg1, SBDebugger jarg1_);
public final static native boolean SBDebugger_DeleteTarget(long jarg1, SBDebugger jarg1_, long jarg2, SBTarget jarg2_);
public final static native long SBDebugger_GetTargetAtIndex(long jarg1, SBDebugger jarg1_, long jarg2);
public final static native long SBDebugger_GetIndexOfTarget(long jarg1, SBDebugger jarg1_, long jarg2, SBTarget jarg2_);
public final static native long SBDebugger_FindTargetWithProcessID(long jarg1, SBDebugger jarg1_, java.math.BigInteger jarg2);
public final static native long SBDebugger_FindTargetWithFileAndArch(long jarg1, SBDebugger jarg1_, String jarg2, String jarg3);
public final static native long SBDebugger_GetNumTargets(long jarg1, SBDebugger jarg1_);
public final static native long SBDebugger_GetSelectedTarget(long jarg1, SBDebugger jarg1_);
public final static native void SBDebugger_SetSelectedTarget(long jarg1, SBDebugger jarg1_, long jarg2, SBTarget jarg2_);
public final static native long SBDebugger_GetSelectedPlatform(long jarg1, SBDebugger jarg1_);
public final static native void SBDebugger_SetSelectedPlatform(long jarg1, SBDebugger jarg1_, long jarg2, SBPlatform jarg2_);
public final static native long SBDebugger_GetNumPlatforms(long jarg1, SBDebugger jarg1_);
public final static native long SBDebugger_GetPlatformAtIndex(long jarg1, SBDebugger jarg1_, long jarg2);
public final static native long SBDebugger_GetNumAvailablePlatforms(long jarg1, SBDebugger jarg1_);
public final static native long SBDebugger_GetAvailablePlatformInfoAtIndex(long jarg1, SBDebugger jarg1_, long jarg2);
public final static native long SBDebugger_GetSourceManager(long jarg1, SBDebugger jarg1_);
public final static native long SBDebugger_SetCurrentPlatform(long jarg1, SBDebugger jarg1_, String jarg2);
public final static native boolean SBDebugger_SetCurrentPlatformSDKRoot(long jarg1, SBDebugger jarg1_, String jarg2);
public final static native boolean SBDebugger_SetUseExternalEditor(long jarg1, SBDebugger jarg1_, boolean jarg2);
public final static native boolean SBDebugger_GetUseExternalEditor(long jarg1, SBDebugger jarg1_);
public final static native boolean SBDebugger_SetUseColor(long jarg1, SBDebugger jarg1_, boolean jarg2);
public final static native boolean SBDebugger_GetUseColor(long jarg1, SBDebugger jarg1_);
public final static native boolean SBDebugger_SetUseSourceCache(long jarg1, SBDebugger jarg1_, boolean jarg2);
public final static native boolean SBDebugger_GetUseSourceCache(long jarg1, SBDebugger jarg1_);
public final static native boolean SBDebugger_GetDefaultArchitecture(String jarg1, long jarg2);
public final static native boolean SBDebugger_SetDefaultArchitecture(String jarg1);
public final static native int SBDebugger_GetScriptingLanguage(long jarg1, SBDebugger jarg1_, String jarg2);
public final static native long SBDebugger_GetScriptInterpreterInfo(long jarg1, SBDebugger jarg1_, int jarg2);
public final static native String SBDebugger_GetVersionString();
public final static native String SBDebugger_StateAsCString(int jarg1);
public final static native long SBDebugger_GetBuildConfiguration();
public final static native boolean SBDebugger_StateIsRunningState(int jarg1);
public final static native boolean SBDebugger_StateIsStoppedState(int jarg1);
public final static native boolean SBDebugger_EnableLog(long jarg1, SBDebugger jarg1_, String jarg2, String[] jarg3);
public final static native void SBDebugger_SetLoggingCallback(long jarg1, SBDebugger jarg1_, long jarg2, long jarg3);
public final static native void SBDebugger_SetDestroyCallback(long jarg1, SBDebugger jarg1_, long jarg2, long jarg3);
public final static native void SBDebugger_DispatchInput(long jarg1, SBDebugger jarg1_, long jarg2, long jarg3);
public final static native void SBDebugger_DispatchInputInterrupt(long jarg1, SBDebugger jarg1_);
public final static native void SBDebugger_DispatchInputEndOfFile(long jarg1, SBDebugger jarg1_);
public final static native String SBDebugger_GetInstanceName(long jarg1, SBDebugger jarg1_);
public final static native long SBDebugger_FindDebuggerWithID(int jarg1);
public final static native long SBDebugger_SetInternalVariable(String jarg1, String jarg2, String jarg3);
public final static native long SBDebugger_GetInternalVariableValue(String jarg1, String jarg2);
public final static native boolean SBDebugger_GetDescription(long jarg1, SBDebugger jarg1_, long jarg2, SBStream jarg2_);
public final static native long SBDebugger_GetTerminalWidth(long jarg1, SBDebugger jarg1_);
public final static native void SBDebugger_SetTerminalWidth(long jarg1, SBDebugger jarg1_, long jarg2);
public final static native java.math.BigInteger SBDebugger_GetID(long jarg1, SBDebugger jarg1_);
public final static native String SBDebugger_GetPrompt(long jarg1, SBDebugger jarg1_);
public final static native void SBDebugger_SetPrompt(long jarg1, SBDebugger jarg1_, String jarg2);
public final static native String SBDebugger_GetReproducerPath(long jarg1, SBDebugger jarg1_);
public final static native int SBDebugger_GetScriptLanguage(long jarg1, SBDebugger jarg1_);
public final static native void SBDebugger_SetScriptLanguage(long jarg1, SBDebugger jarg1_, int jarg2);
public final static native int SBDebugger_GetREPLLanguage(long jarg1, SBDebugger jarg1_);
public final static native void SBDebugger_SetREPLLanguage(long jarg1, SBDebugger jarg1_, int jarg2);
public final static native boolean SBDebugger_GetCloseInputOnEOF(long jarg1, SBDebugger jarg1_);
public final static native void SBDebugger_SetCloseInputOnEOF(long jarg1, SBDebugger jarg1_, boolean jarg2);
public final static native long SBDebugger_GetCategory__SWIG_0(long jarg1, SBDebugger jarg1_, String jarg2);
public final static native long SBDebugger_GetCategory__SWIG_1(long jarg1, SBDebugger jarg1_, int jarg2);
public final static native long SBDebugger_CreateCategory(long jarg1, SBDebugger jarg1_, String jarg2);
public final static native boolean SBDebugger_DeleteCategory(long jarg1, SBDebugger jarg1_, String jarg2);
public final static native long SBDebugger_GetNumCategories(long jarg1, SBDebugger jarg1_);
public final static native long SBDebugger_GetCategoryAtIndex(long jarg1, SBDebugger jarg1_, long jarg2);
public final static native long SBDebugger_GetDefaultCategory(long jarg1, SBDebugger jarg1_);
public final static native long SBDebugger_GetFormatForType(long jarg1, SBDebugger jarg1_, long jarg2, SBTypeNameSpecifier jarg2_);
public final static native long SBDebugger_GetSummaryForType(long jarg1, SBDebugger jarg1_, long jarg2, SBTypeNameSpecifier jarg2_);
public final static native long SBDebugger_GetFilterForType(long jarg1, SBDebugger jarg1_, long jarg2, SBTypeNameSpecifier jarg2_);
public final static native long SBDebugger_GetSyntheticForType(long jarg1, SBDebugger jarg1_, long jarg2, SBTypeNameSpecifier jarg2_);
public final static native void SBDebugger_RunCommandInterpreter(long jarg1, SBDebugger jarg1_, boolean jarg2, boolean jarg3, long jarg4, SBCommandInterpreterRunOptions jarg4_, int[] jarg5, boolean[] jarg6, boolean[] jarg7);
public final static native long SBDebugger_RunREPL(long jarg1, SBDebugger jarg1_, int jarg2, String jarg3);
public final static native long SBDebugger_LoadTraceFromFile(long jarg1, SBDebugger jarg1_, long jarg2, SBError jarg2_, long jarg3, SBFileSpec jarg3_);
public final static native String SBDebugger___repr__(long jarg1, SBDebugger jarg1_);
public final static native long SBDebugger_GetInputFileHandle(long jarg1, SBDebugger jarg1_);
public final static native long SBDebugger_GetOutputFileHandle(long jarg1, SBDebugger jarg1_);
public final static native long SBDebugger_GetErrorFileHandle(long jarg1, SBDebugger jarg1_);
public final static native long new_SBDeclaration__SWIG_0();
public final static native long new_SBDeclaration__SWIG_1(long jarg1, SBDeclaration jarg1_);
public final static native void delete_SBDeclaration(long jarg1);
public final static native boolean SBDeclaration_IsValid(long jarg1, SBDeclaration jarg1_);
public final static native long SBDeclaration_GetFileSpec(long jarg1, SBDeclaration jarg1_);
public final static native long SBDeclaration_GetLine(long jarg1, SBDeclaration jarg1_);
public final static native long SBDeclaration_GetColumn(long jarg1, SBDeclaration jarg1_);
public final static native void SBDeclaration_SetFileSpec(long jarg1, SBDeclaration jarg1_, long jarg2, SBFileSpec jarg2_);
public final static native void SBDeclaration_SetLine(long jarg1, SBDeclaration jarg1_, long jarg2);
public final static native void SBDeclaration_SetColumn(long jarg1, SBDeclaration jarg1_, long jarg2);
public final static native boolean SBDeclaration_GetDescription(long jarg1, SBDeclaration jarg1_, long jarg2, SBStream jarg2_);
public final static native String SBDeclaration___repr__(long jarg1, SBDeclaration jarg1_);
public final static native long new_SBError__SWIG_0();
public final static native long new_SBError__SWIG_1(long jarg1, SBError jarg1_);
public final static native long new_SBError__SWIG_2(String jarg1);
public final static native void delete_SBError(long jarg1);
public final static native String SBError_GetCString(long jarg1, SBError jarg1_);
public final static native void SBError_Clear(long jarg1, SBError jarg1_);
public final static native boolean SBError_Fail(long jarg1, SBError jarg1_);
public final static native boolean SBError_Success(long jarg1, SBError jarg1_);
public final static native long SBError_GetError(long jarg1, SBError jarg1_);
public final static native int SBError_GetType(long jarg1, SBError jarg1_);
public final static native void SBError_SetError(long jarg1, SBError jarg1_, long jarg2, int jarg3);
public final static native void SBError_SetErrorToErrno(long jarg1, SBError jarg1_);
public final static native void SBError_SetErrorToGenericError(long jarg1, SBError jarg1_);
public final static native void SBError_SetErrorString(long jarg1, SBError jarg1_, String jarg2);
public final static native int SBError_SetErrorStringWithFormat__SWIG_0(long jarg1, SBError jarg1_, String jarg2, String jarg3, String jarg4, String jarg5);
public final static native int SBError_SetErrorStringWithFormat__SWIG_1(long jarg1, SBError jarg1_, String jarg2, String jarg3, String jarg4);
public final static native int SBError_SetErrorStringWithFormat__SWIG_2(long jarg1, SBError jarg1_, String jarg2, String jarg3);
public final static native int SBError_SetErrorStringWithFormat__SWIG_3(long jarg1, SBError jarg1_, String jarg2);
public final static native boolean SBError_IsValid(long jarg1, SBError jarg1_);
public final static native boolean SBError_GetDescription(long jarg1, SBError jarg1_, long jarg2, SBStream jarg2_);
public final static native String SBError___repr__(long jarg1, SBError jarg1_);
public final static native long new_SBEnvironment__SWIG_0();
public final static native long new_SBEnvironment__SWIG_1(long jarg1, SBEnvironment jarg1_);
public final static native void delete_SBEnvironment(long jarg1);
public final static native String SBEnvironment_Get(long jarg1, SBEnvironment jarg1_, String jarg2);
public final static native long SBEnvironment_GetNumValues(long jarg1, SBEnvironment jarg1_);
public final static native String SBEnvironment_GetNameAtIndex(long jarg1, SBEnvironment jarg1_, long jarg2);
public final static native String SBEnvironment_GetValueAtIndex(long jarg1, SBEnvironment jarg1_, long jarg2);
public final static native long SBEnvironment_GetEntries(long jarg1, SBEnvironment jarg1_);
public final static native void SBEnvironment_PutEntry(long jarg1, SBEnvironment jarg1_, String jarg2);
public final static native void SBEnvironment_SetEntries(long jarg1, SBEnvironment jarg1_, long jarg2, SBStringList jarg2_, boolean jarg3);
public final static native boolean SBEnvironment_Set(long jarg1, SBEnvironment jarg1_, String jarg2, String jarg3, boolean jarg4);
public final static native boolean SBEnvironment_Unset(long jarg1, SBEnvironment jarg1_, String jarg2);
public final static native void SBEnvironment_Clear(long jarg1, SBEnvironment jarg1_);
public final static native long new_SBEvent__SWIG_0();
public final static native long new_SBEvent__SWIG_1(long jarg1, SBEvent jarg1_);
public final static native long new_SBEvent__SWIG_2(long jarg1, String jarg2, long jarg3);
public final static native void delete_SBEvent(long jarg1);
public final static native boolean SBEvent_IsValid(long jarg1, SBEvent jarg1_);
public final static native String SBEvent_GetDataFlavor(long jarg1, SBEvent jarg1_);
public final static native long SBEvent_GetType(long jarg1, SBEvent jarg1_);
public final static native long SBEvent_GetBroadcaster(long jarg1, SBEvent jarg1_);
public final static native String SBEvent_GetBroadcasterClass(long jarg1, SBEvent jarg1_);
public final static native boolean SBEvent_BroadcasterMatchesRef(long jarg1, SBEvent jarg1_, long jarg2, SBBroadcaster jarg2_);
public final static native void SBEvent_Clear(long jarg1, SBEvent jarg1_);
public final static native String SBEvent_GetCStringFromEvent(long jarg1, SBEvent jarg1_);
public final static native boolean SBEvent_GetDescription__SWIG_0(long jarg1, SBEvent jarg1_, long jarg2, SBStream jarg2_);
public final static native long new_SBExecutionContext__SWIG_0();
public final static native long new_SBExecutionContext__SWIG_1(long jarg1, SBExecutionContext jarg1_);
public final static native long new_SBExecutionContext__SWIG_2(long jarg1, SBTarget jarg1_);
public final static native long new_SBExecutionContext__SWIG_3(long jarg1, SBProcess jarg1_);
public final static native long new_SBExecutionContext__SWIG_4(long jarg1, SBThread jarg1_);
public final static native long new_SBExecutionContext__SWIG_5(long jarg1, SBFrame jarg1_);
public final static native void delete_SBExecutionContext(long jarg1);
public final static native long SBExecutionContext_GetTarget(long jarg1, SBExecutionContext jarg1_);
public final static native long SBExecutionContext_GetProcess(long jarg1, SBExecutionContext jarg1_);
public final static native long SBExecutionContext_GetThread(long jarg1, SBExecutionContext jarg1_);
public final static native long SBExecutionContext_GetFrame(long jarg1, SBExecutionContext jarg1_);
public final static native long new_SBExpressionOptions__SWIG_0();
public final static native long new_SBExpressionOptions__SWIG_1(long jarg1, SBExpressionOptions jarg1_);
public final static native void delete_SBExpressionOptions(long jarg1);
public final static native boolean SBExpressionOptions_GetCoerceResultToId(long jarg1, SBExpressionOptions jarg1_);
public final static native void SBExpressionOptions_SetCoerceResultToId__SWIG_0(long jarg1, SBExpressionOptions jarg1_, boolean jarg2);
public final static native void SBExpressionOptions_SetCoerceResultToId__SWIG_1(long jarg1, SBExpressionOptions jarg1_);
public final static native boolean SBExpressionOptions_GetUnwindOnError(long jarg1, SBExpressionOptions jarg1_);
public final static native void SBExpressionOptions_SetUnwindOnError__SWIG_0(long jarg1, SBExpressionOptions jarg1_, boolean jarg2);
public final static native void SBExpressionOptions_SetUnwindOnError__SWIG_1(long jarg1, SBExpressionOptions jarg1_);
public final static native boolean SBExpressionOptions_GetIgnoreBreakpoints(long jarg1, SBExpressionOptions jarg1_);
public final static native void SBExpressionOptions_SetIgnoreBreakpoints__SWIG_0(long jarg1, SBExpressionOptions jarg1_, boolean jarg2);
public final static native void SBExpressionOptions_SetIgnoreBreakpoints__SWIG_1(long jarg1, SBExpressionOptions jarg1_);
public final static native int SBExpressionOptions_GetFetchDynamicValue(long jarg1, SBExpressionOptions jarg1_);
public final static native void SBExpressionOptions_SetFetchDynamicValue__SWIG_0(long jarg1, SBExpressionOptions jarg1_, int jarg2);
public final static native void SBExpressionOptions_SetFetchDynamicValue__SWIG_1(long jarg1, SBExpressionOptions jarg1_);
public final static native long SBExpressionOptions_GetTimeoutInMicroSeconds(long jarg1, SBExpressionOptions jarg1_);
public final static native void SBExpressionOptions_SetTimeoutInMicroSeconds__SWIG_0(long jarg1, SBExpressionOptions jarg1_, long jarg2);
public final static native void SBExpressionOptions_SetTimeoutInMicroSeconds__SWIG_1(long jarg1, SBExpressionOptions jarg1_);
public final static native long SBExpressionOptions_GetOneThreadTimeoutInMicroSeconds(long jarg1, SBExpressionOptions jarg1_);
public final static native void SBExpressionOptions_SetOneThreadTimeoutInMicroSeconds__SWIG_0(long jarg1, SBExpressionOptions jarg1_, long jarg2);
public final static native void SBExpressionOptions_SetOneThreadTimeoutInMicroSeconds__SWIG_1(long jarg1, SBExpressionOptions jarg1_);
public final static native boolean SBExpressionOptions_GetTryAllThreads(long jarg1, SBExpressionOptions jarg1_);
public final static native void SBExpressionOptions_SetTryAllThreads__SWIG_0(long jarg1, SBExpressionOptions jarg1_, boolean jarg2);
public final static native void SBExpressionOptions_SetTryAllThreads__SWIG_1(long jarg1, SBExpressionOptions jarg1_);
public final static native boolean SBExpressionOptions_GetStopOthers(long jarg1, SBExpressionOptions jarg1_);
public final static native void SBExpressionOptions_SetStopOthers__SWIG_0(long jarg1, SBExpressionOptions jarg1_, boolean jarg2);
public final static native void SBExpressionOptions_SetStopOthers__SWIG_1(long jarg1, SBExpressionOptions jarg1_);
public final static native boolean SBExpressionOptions_GetTrapExceptions(long jarg1, SBExpressionOptions jarg1_);
public final static native void SBExpressionOptions_SetTrapExceptions__SWIG_0(long jarg1, SBExpressionOptions jarg1_, boolean jarg2);
public final static native void SBExpressionOptions_SetTrapExceptions__SWIG_1(long jarg1, SBExpressionOptions jarg1_);
public final static native void SBExpressionOptions_SetLanguage(long jarg1, SBExpressionOptions jarg1_, int jarg2);
public final static native boolean SBExpressionOptions_GetGenerateDebugInfo(long jarg1, SBExpressionOptions jarg1_);
public final static native void SBExpressionOptions_SetGenerateDebugInfo__SWIG_0(long jarg1, SBExpressionOptions jarg1_, boolean jarg2);
public final static native void SBExpressionOptions_SetGenerateDebugInfo__SWIG_1(long jarg1, SBExpressionOptions jarg1_);
public final static native boolean SBExpressionOptions_GetSuppressPersistentResult(long jarg1, SBExpressionOptions jarg1_);
public final static native void SBExpressionOptions_SetSuppressPersistentResult__SWIG_0(long jarg1, SBExpressionOptions jarg1_, boolean jarg2);
public final static native void SBExpressionOptions_SetSuppressPersistentResult__SWIG_1(long jarg1, SBExpressionOptions jarg1_);
public final static native String SBExpressionOptions_GetPrefix(long jarg1, SBExpressionOptions jarg1_);
public final static native void SBExpressionOptions_SetPrefix(long jarg1, SBExpressionOptions jarg1_, String jarg2);
public final static native void SBExpressionOptions_SetAutoApplyFixIts__SWIG_0(long jarg1, SBExpressionOptions jarg1_, boolean jarg2);
public final static native void SBExpressionOptions_SetAutoApplyFixIts__SWIG_1(long jarg1, SBExpressionOptions jarg1_);
public final static native boolean SBExpressionOptions_GetAutoApplyFixIts(long jarg1, SBExpressionOptions jarg1_);
public final static native void SBExpressionOptions_SetRetriesWithFixIts(long jarg1, SBExpressionOptions jarg1_, java.math.BigInteger jarg2);
public final static native java.math.BigInteger SBExpressionOptions_GetRetriesWithFixIts(long jarg1, SBExpressionOptions jarg1_);
public final static native boolean SBExpressionOptions_GetTopLevel(long jarg1, SBExpressionOptions jarg1_);
public final static native void SBExpressionOptions_SetTopLevel__SWIG_0(long jarg1, SBExpressionOptions jarg1_, boolean jarg2);
public final static native void SBExpressionOptions_SetTopLevel__SWIG_1(long jarg1, SBExpressionOptions jarg1_);
public final static native boolean SBExpressionOptions_GetAllowJIT(long jarg1, SBExpressionOptions jarg1_);
public final static native void SBExpressionOptions_SetAllowJIT(long jarg1, SBExpressionOptions jarg1_, boolean jarg2);
public final static native long new_SBFile__SWIG_0();
public final static native long new_SBFile__SWIG_1(long jarg1);
public final static native long new_SBFile__SWIG_2(int jarg1, String jarg2, boolean jarg3);
public final static native void delete_SBFile(long jarg1);
public final static native long SBFile_Read(long jarg1, SBFile jarg1_, long jarg2, long jarg3, long jarg4);
public final static native long SBFile_Write(long jarg1, SBFile jarg1_, long jarg2, long jarg3, long jarg4);
public final static native long SBFile_Flush(long jarg1, SBFile jarg1_);
public final static native boolean SBFile_IsValid(long jarg1, SBFile jarg1_);
public final static native long SBFile_Close(long jarg1, SBFile jarg1_);
public final static native long SBFile_GetFile(long jarg1, SBFile jarg1_);
public final static native long SBFile_MakeBorrowed(long jarg1);
public final static native long SBFile_MakeForcingIOMethods(long jarg1);
public final static native long SBFile_MakeBorrowedForcingIOMethods(long jarg1);
public final static native long new_SBFileSpec__SWIG_0();
public final static native long new_SBFileSpec__SWIG_1(long jarg1, SBFileSpec jarg1_);
public final static native long new_SBFileSpec__SWIG_2(String jarg1);
public final static native long new_SBFileSpec__SWIG_3(String jarg1, boolean jarg2);
public final static native void delete_SBFileSpec(long jarg1);
public final static native boolean SBFileSpec_IsValid(long jarg1, SBFileSpec jarg1_);
public final static native boolean SBFileSpec_Exists(long jarg1, SBFileSpec jarg1_);
public final static native boolean SBFileSpec_ResolveExecutableLocation(long jarg1, SBFileSpec jarg1_);
public final static native String SBFileSpec_GetFilename(long jarg1, SBFileSpec jarg1_);
public final static native String SBFileSpec_GetDirectory(long jarg1, SBFileSpec jarg1_);
public final static native void SBFileSpec_SetFilename(long jarg1, SBFileSpec jarg1_, String jarg2);
public final static native void SBFileSpec_SetDirectory(long jarg1, SBFileSpec jarg1_, String jarg2);
public final static native long SBFileSpec_GetPath(long jarg1, SBFileSpec jarg1_, String jarg2, long jarg3);
public final static native int SBFileSpec_ResolvePath(String jarg1, String jarg2, long jarg3);
public final static native boolean SBFileSpec_GetDescription(long jarg1, SBFileSpec jarg1_, long jarg2, SBStream jarg2_);
public final static native void SBFileSpec_AppendPathComponent(long jarg1, SBFileSpec jarg1_, String jarg2);
public final static native String SBFileSpec___repr__(long jarg1, SBFileSpec jarg1_);
public final static native long new_SBFileSpecList__SWIG_0();
public final static native long new_SBFileSpecList__SWIG_1(long jarg1, SBFileSpecList jarg1_);
public final static native void delete_SBFileSpecList(long jarg1);
public final static native long SBFileSpecList_GetSize(long jarg1, SBFileSpecList jarg1_);
public final static native boolean SBFileSpecList_GetDescription(long jarg1, SBFileSpecList jarg1_, long jarg2, SBStream jarg2_);
public final static native void SBFileSpecList_Append(long jarg1, SBFileSpecList jarg1_, long jarg2, SBFileSpec jarg2_);
public final static native boolean SBFileSpecList_AppendIfUnique(long jarg1, SBFileSpecList jarg1_, long jarg2, SBFileSpec jarg2_);
public final static native void SBFileSpecList_Clear(long jarg1, SBFileSpecList jarg1_);
public final static native long SBFileSpecList_FindFileIndex(long jarg1, SBFileSpecList jarg1_, long jarg2, long jarg3, SBFileSpec jarg3_, boolean jarg4);
public final static native long SBFileSpecList_GetFileSpecAtIndex(long jarg1, SBFileSpecList jarg1_, long jarg2);
public final static native long new_SBFrame__SWIG_0();
public final static native long new_SBFrame__SWIG_1(long jarg1, SBFrame jarg1_);
public final static native void delete_SBFrame(long jarg1);
public final static native boolean SBFrame_IsEqual(long jarg1, SBFrame jarg1_, long jarg2, SBFrame jarg2_);
public final static native boolean SBFrame_IsValid(long jarg1, SBFrame jarg1_);
public final static native long SBFrame_GetFrameID(long jarg1, SBFrame jarg1_);
public final static native java.math.BigInteger SBFrame_GetCFA(long jarg1, SBFrame jarg1_);
public final static native java.math.BigInteger SBFrame_GetPC(long jarg1, SBFrame jarg1_);
public final static native boolean SBFrame_SetPC(long jarg1, SBFrame jarg1_, java.math.BigInteger jarg2);
public final static native java.math.BigInteger SBFrame_GetSP(long jarg1, SBFrame jarg1_);
public final static native java.math.BigInteger SBFrame_GetFP(long jarg1, SBFrame jarg1_);
public final static native long SBFrame_GetPCAddress(long jarg1, SBFrame jarg1_);
public final static native long SBFrame_GetSymbolContext(long jarg1, SBFrame jarg1_, long jarg2);
public final static native long SBFrame_GetModule(long jarg1, SBFrame jarg1_);
public final static native long SBFrame_GetCompileUnit(long jarg1, SBFrame jarg1_);
public final static native long SBFrame_GetFunction(long jarg1, SBFrame jarg1_);
public final static native long SBFrame_GetSymbol(long jarg1, SBFrame jarg1_);
public final static native long SBFrame_GetBlock(long jarg1, SBFrame jarg1_);
public final static native String SBFrame_GetFunctionName__SWIG_0(long jarg1, SBFrame jarg1_);
public final static native String SBFrame_GetDisplayFunctionName(long jarg1, SBFrame jarg1_);
public final static native int SBFrame_GuessLanguage(long jarg1, SBFrame jarg1_);
public final static native boolean SBFrame_IsInlined__SWIG_0(long jarg1, SBFrame jarg1_);
public final static native boolean SBFrame_IsArtificial__SWIG_0(long jarg1, SBFrame jarg1_);
public final static native long SBFrame_EvaluateExpression__SWIG_0(long jarg1, SBFrame jarg1_, String jarg2);
public final static native long SBFrame_EvaluateExpression__SWIG_1(long jarg1, SBFrame jarg1_, String jarg2, int jarg3);
public final static native long SBFrame_EvaluateExpression__SWIG_2(long jarg1, SBFrame jarg1_, String jarg2, int jarg3, boolean jarg4);
public final static native long SBFrame_EvaluateExpression__SWIG_3(long jarg1, SBFrame jarg1_, String jarg2, long jarg3, SBExpressionOptions jarg3_);
public final static native long SBFrame_GetFrameBlock(long jarg1, SBFrame jarg1_);
public final static native long SBFrame_GetLineEntry(long jarg1, SBFrame jarg1_);
public final static native long SBFrame_GetThread(long jarg1, SBFrame jarg1_);
public final static native String SBFrame_Disassemble(long jarg1, SBFrame jarg1_);
public final static native void SBFrame_Clear(long jarg1, SBFrame jarg1_);
public final static native long SBFrame_GetVariables__SWIG_0(long jarg1, SBFrame jarg1_, boolean jarg2, boolean jarg3, boolean jarg4, boolean jarg5);
public final static native long SBFrame_GetVariables__SWIG_1(long jarg1, SBFrame jarg1_, boolean jarg2, boolean jarg3, boolean jarg4, boolean jarg5, int jarg6);
public final static native long SBFrame_GetVariables__SWIG_2(long jarg1, SBFrame jarg1_, long jarg2, SBVariablesOptions jarg2_);
public final static native long SBFrame_GetRegisters(long jarg1, SBFrame jarg1_);
public final static native long SBFrame_FindRegister(long jarg1, SBFrame jarg1_, String jarg2);
public final static native long SBFrame_FindVariable__SWIG_0(long jarg1, SBFrame jarg1_, String jarg2);
public final static native long SBFrame_FindVariable__SWIG_1(long jarg1, SBFrame jarg1_, String jarg2, int jarg3);
public final static native long SBFrame_GetValueForVariablePath__SWIG_0(long jarg1, SBFrame jarg1_, String jarg2, int jarg3);
public final static native long SBFrame_GetValueForVariablePath__SWIG_1(long jarg1, SBFrame jarg1_, String jarg2);
public final static native long SBFrame_FindValue__SWIG_0(long jarg1, SBFrame jarg1_, String jarg2, int jarg3);
public final static native long SBFrame_FindValue__SWIG_1(long jarg1, SBFrame jarg1_, String jarg2, int jarg3, int jarg4);
public final static native boolean SBFrame_GetDescription(long jarg1, SBFrame jarg1_, long jarg2, SBStream jarg2_);
public final static native String SBFrame___repr__(long jarg1, SBFrame jarg1_);
public final static native long new_SBFunction__SWIG_0();
public final static native long new_SBFunction__SWIG_1(long jarg1, SBFunction jarg1_);
public final static native void delete_SBFunction(long jarg1);
public final static native boolean SBFunction_IsValid(long jarg1, SBFunction jarg1_);
public final static native String SBFunction_GetName(long jarg1, SBFunction jarg1_);
public final static native String SBFunction_GetDisplayName(long jarg1, SBFunction jarg1_);
public final static native String SBFunction_GetMangledName(long jarg1, SBFunction jarg1_);
public final static native long SBFunction_GetInstructions__SWIG_0(long jarg1, SBFunction jarg1_, long jarg2, SBTarget jarg2_);
public final static native long SBFunction_GetInstructions__SWIG_1(long jarg1, SBFunction jarg1_, long jarg2, SBTarget jarg2_, String jarg3);
public final static native long SBFunction_GetStartAddress(long jarg1, SBFunction jarg1_);
public final static native long SBFunction_GetEndAddress(long jarg1, SBFunction jarg1_);
public final static native String SBFunction_GetArgumentName(long jarg1, SBFunction jarg1_, long jarg2);
public final static native long SBFunction_GetPrologueByteSize(long jarg1, SBFunction jarg1_);
public final static native long SBFunction_GetType(long jarg1, SBFunction jarg1_);
public final static native long SBFunction_GetBlock(long jarg1, SBFunction jarg1_);
public final static native int SBFunction_GetLanguage(long jarg1, SBFunction jarg1_);
public final static native boolean SBFunction_GetIsOptimized(long jarg1, SBFunction jarg1_);
public final static native boolean SBFunction_GetDescription(long jarg1, SBFunction jarg1_, long jarg2, SBStream jarg2_);
public final static native String SBFunction___repr__(long jarg1, SBFunction jarg1_);
public final static native long SBHostOS_GetProgramFileSpec();
public final static native long SBHostOS_GetLLDBPythonPath();
public final static native long SBHostOS_GetLLDBPath(int jarg1);
public final static native long SBHostOS_GetUserHomeDirectory();
public final static native void SBHostOS_ThreadCreated(String jarg1);
public final static native long SBHostOS_ThreadCreate(String jarg1, long jarg2, long jarg3, long jarg4, SBError jarg4_);
public final static native boolean SBHostOS_ThreadCancel(long jarg1, long jarg2, SBError jarg2_);
public final static native boolean SBHostOS_ThreadDetach(long jarg1, long jarg2, SBError jarg2_);
public final static native boolean SBHostOS_ThreadJoin(long jarg1, long jarg2, long jarg3, SBError jarg3_);
public final static native long new_SBHostOS();
public final static native void delete_SBHostOS(long jarg1);
public final static native long new_SBInstruction__SWIG_0();
public final static native long new_SBInstruction__SWIG_1(long jarg1, SBInstruction jarg1_);
public final static native void delete_SBInstruction(long jarg1);
public final static native boolean SBInstruction_IsValid(long jarg1, SBInstruction jarg1_);
public final static native long SBInstruction_GetAddress(long jarg1, SBInstruction jarg1_);
public final static native String SBInstruction_GetMnemonic(long jarg1, SBInstruction jarg1_, long jarg2, SBTarget jarg2_);
public final static native String SBInstruction_GetOperands(long jarg1, SBInstruction jarg1_, long jarg2, SBTarget jarg2_);
public final static native String SBInstruction_GetComment(long jarg1, SBInstruction jarg1_, long jarg2, SBTarget jarg2_);
public final static native int SBInstruction_GetControlFlowKind(long jarg1, SBInstruction jarg1_, long jarg2, SBTarget jarg2_);
public final static native long SBInstruction_GetData(long jarg1, SBInstruction jarg1_, long jarg2, SBTarget jarg2_);
public final static native long SBInstruction_GetByteSize(long jarg1, SBInstruction jarg1_);
public final static native boolean SBInstruction_DoesBranch(long jarg1, SBInstruction jarg1_);
public final static native boolean SBInstruction_HasDelaySlot(long jarg1, SBInstruction jarg1_);
public final static native boolean SBInstruction_CanSetBreakpoint(long jarg1, SBInstruction jarg1_);
public final static native void SBInstruction_Print__SWIG_0(long jarg1, SBInstruction jarg1_, long jarg2, SBFile jarg2_);
public final static native void SBInstruction_Print__SWIG_1(long jarg1, SBInstruction jarg1_, long jarg2);
public final static native boolean SBInstruction_GetDescription(long jarg1, SBInstruction jarg1_, long jarg2, SBStream jarg2_);
public final static native boolean SBInstruction_EmulateWithFrame(long jarg1, SBInstruction jarg1_, long jarg2, SBFrame jarg2_, long jarg3);
public final static native boolean SBInstruction_DumpEmulation(long jarg1, SBInstruction jarg1_, String jarg2);
public final static native boolean SBInstruction_TestEmulation(long jarg1, SBInstruction jarg1_, long jarg2, SBStream jarg2_, String jarg3);
public final static native String SBInstruction___repr__(long jarg1, SBInstruction jarg1_);
public final static native long new_SBInstructionList__SWIG_0();
public final static native long new_SBInstructionList__SWIG_1(long jarg1, SBInstructionList jarg1_);
public final static native void delete_SBInstructionList(long jarg1);
public final static native boolean SBInstructionList_IsValid(long jarg1, SBInstructionList jarg1_);
public final static native long SBInstructionList_GetSize(long jarg1, SBInstructionList jarg1_);
public final static native long SBInstructionList_GetInstructionAtIndex(long jarg1, SBInstructionList jarg1_, long jarg2);
public final static native long SBInstructionList_GetInstructionsCount__SWIG_0(long jarg1, SBInstructionList jarg1_, long jarg2, SBAddress jarg2_, long jarg3, SBAddress jarg3_, boolean jarg4);
public final static native long SBInstructionList_GetInstructionsCount__SWIG_1(long jarg1, SBInstructionList jarg1_, long jarg2, SBAddress jarg2_, long jarg3, SBAddress jarg3_);
public final static native void SBInstructionList_Clear(long jarg1, SBInstructionList jarg1_);
public final static native void SBInstructionList_AppendInstruction(long jarg1, SBInstructionList jarg1_, long jarg2, SBInstruction jarg2_);
public final static native void SBInstructionList_Print__SWIG_0(long jarg1, SBInstructionList jarg1_, long jarg2, SBFile jarg2_);
public final static native void SBInstructionList_Print__SWIG_1(long jarg1, SBInstructionList jarg1_, long jarg2);
public final static native boolean SBInstructionList_GetDescription(long jarg1, SBInstructionList jarg1_, long jarg2, SBStream jarg2_);
public final static native boolean SBInstructionList_DumpEmulationForAllInstructions(long jarg1, SBInstructionList jarg1_, String jarg2);
public final static native String SBInstructionList___repr__(long jarg1, SBInstructionList jarg1_);
public final static native int SBLanguageRuntime_GetLanguageTypeFromString(String jarg1);
public final static native String SBLanguageRuntime_GetNameForLanguageType(int jarg1);
public final static native long new_SBLanguageRuntime();
public final static native void delete_SBLanguageRuntime(long jarg1);
public final static native long new_SBLaunchInfo(String[] jarg1);
public final static native void delete_SBLaunchInfo(long jarg1);
public final static native java.math.BigInteger SBLaunchInfo_GetProcessID(long jarg1, SBLaunchInfo jarg1_);
public final static native long SBLaunchInfo_GetUserID(long jarg1, SBLaunchInfo jarg1_);
public final static native long SBLaunchInfo_GetGroupID(long jarg1, SBLaunchInfo jarg1_);
public final static native boolean SBLaunchInfo_UserIDIsValid(long jarg1, SBLaunchInfo jarg1_);
public final static native boolean SBLaunchInfo_GroupIDIsValid(long jarg1, SBLaunchInfo jarg1_);
public final static native void SBLaunchInfo_SetUserID(long jarg1, SBLaunchInfo jarg1_, long jarg2);
public final static native void SBLaunchInfo_SetGroupID(long jarg1, SBLaunchInfo jarg1_, long jarg2);
public final static native long SBLaunchInfo_GetExecutableFile(long jarg1, SBLaunchInfo jarg1_);
public final static native void SBLaunchInfo_SetExecutableFile(long jarg1, SBLaunchInfo jarg1_, long jarg2, SBFileSpec jarg2_, boolean jarg3);
public final static native long SBLaunchInfo_GetListener(long jarg1, SBLaunchInfo jarg1_);
public final static native void SBLaunchInfo_SetListener(long jarg1, SBLaunchInfo jarg1_, long jarg2, SBListener jarg2_);
public final static native long SBLaunchInfo_GetShadowListener(long jarg1, SBLaunchInfo jarg1_);
public final static native void SBLaunchInfo_SetShadowListener(long jarg1, SBLaunchInfo jarg1_, long jarg2, SBListener jarg2_);
public final static native long SBLaunchInfo_GetNumArguments(long jarg1, SBLaunchInfo jarg1_);
public final static native String SBLaunchInfo_GetArgumentAtIndex(long jarg1, SBLaunchInfo jarg1_, long jarg2);
public final static native void SBLaunchInfo_SetArguments(long jarg1, SBLaunchInfo jarg1_, String[] jarg2, boolean jarg3);
public final static native long SBLaunchInfo_GetNumEnvironmentEntries(long jarg1, SBLaunchInfo jarg1_);
public final static native String SBLaunchInfo_GetEnvironmentEntryAtIndex(long jarg1, SBLaunchInfo jarg1_, long jarg2);
public final static native void SBLaunchInfo_SetEnvironmentEntries(long jarg1, SBLaunchInfo jarg1_, String[] jarg2, boolean jarg3);
public final static native void SBLaunchInfo_SetEnvironment(long jarg1, SBLaunchInfo jarg1_, long jarg2, SBEnvironment jarg2_, boolean jarg3);
public final static native long SBLaunchInfo_GetEnvironment(long jarg1, SBLaunchInfo jarg1_);
public final static native void SBLaunchInfo_Clear(long jarg1, SBLaunchInfo jarg1_);
public final static native String SBLaunchInfo_GetWorkingDirectory(long jarg1, SBLaunchInfo jarg1_);
public final static native void SBLaunchInfo_SetWorkingDirectory(long jarg1, SBLaunchInfo jarg1_, String jarg2);
public final static native long SBLaunchInfo_GetLaunchFlags(long jarg1, SBLaunchInfo jarg1_);
public final static native void SBLaunchInfo_SetLaunchFlags(long jarg1, SBLaunchInfo jarg1_, long jarg2);
public final static native String SBLaunchInfo_GetProcessPluginName(long jarg1, SBLaunchInfo jarg1_);
public final static native void SBLaunchInfo_SetProcessPluginName(long jarg1, SBLaunchInfo jarg1_, String jarg2);
public final static native String SBLaunchInfo_GetShell(long jarg1, SBLaunchInfo jarg1_);
public final static native void SBLaunchInfo_SetShell(long jarg1, SBLaunchInfo jarg1_, String jarg2);
public final static native boolean SBLaunchInfo_GetShellExpandArguments(long jarg1, SBLaunchInfo jarg1_);
public final static native void SBLaunchInfo_SetShellExpandArguments(long jarg1, SBLaunchInfo jarg1_, boolean jarg2);
public final static native long SBLaunchInfo_GetResumeCount(long jarg1, SBLaunchInfo jarg1_);
public final static native void SBLaunchInfo_SetResumeCount(long jarg1, SBLaunchInfo jarg1_, long jarg2);
public final static native boolean SBLaunchInfo_AddCloseFileAction(long jarg1, SBLaunchInfo jarg1_, int jarg2);
public final static native boolean SBLaunchInfo_AddDuplicateFileAction(long jarg1, SBLaunchInfo jarg1_, int jarg2, int jarg3);
public final static native boolean SBLaunchInfo_AddOpenFileAction(long jarg1, SBLaunchInfo jarg1_, int jarg2, String jarg3, boolean jarg4, boolean jarg5);
public final static native boolean SBLaunchInfo_AddSuppressFileAction(long jarg1, SBLaunchInfo jarg1_, int jarg2, boolean jarg3, boolean jarg4);
public final static native void SBLaunchInfo_SetLaunchEventData(long jarg1, SBLaunchInfo jarg1_, String jarg2);
public final static native String SBLaunchInfo_GetLaunchEventData(long jarg1, SBLaunchInfo jarg1_);
public final static native boolean SBLaunchInfo_GetDetachOnError(long jarg1, SBLaunchInfo jarg1_);
public final static native void SBLaunchInfo_SetDetachOnError(long jarg1, SBLaunchInfo jarg1_, boolean jarg2);
public final static native String SBLaunchInfo_GetScriptedProcessClassName(long jarg1, SBLaunchInfo jarg1_);
public final static native void SBLaunchInfo_SetScriptedProcessClassName(long jarg1, SBLaunchInfo jarg1_, String jarg2);
public final static native long SBLaunchInfo_GetScriptedProcessDictionary(long jarg1, SBLaunchInfo jarg1_);
public final static native void SBLaunchInfo_SetScriptedProcessDictionary(long jarg1, SBLaunchInfo jarg1_, long jarg2, SBStructuredData jarg2_);
public final static native long new_SBLineEntry__SWIG_0();
public final static native long new_SBLineEntry__SWIG_1(long jarg1, SBLineEntry jarg1_);
public final static native void delete_SBLineEntry(long jarg1);
public final static native long SBLineEntry_GetStartAddress(long jarg1, SBLineEntry jarg1_);
public final static native long SBLineEntry_GetEndAddress(long jarg1, SBLineEntry jarg1_);
public final static native boolean SBLineEntry_IsValid(long jarg1, SBLineEntry jarg1_);
public final static native long SBLineEntry_GetFileSpec(long jarg1, SBLineEntry jarg1_);
public final static native long SBLineEntry_GetLine(long jarg1, SBLineEntry jarg1_);
public final static native long SBLineEntry_GetColumn(long jarg1, SBLineEntry jarg1_);
public final static native void SBLineEntry_SetFileSpec(long jarg1, SBLineEntry jarg1_, long jarg2, SBFileSpec jarg2_);
public final static native void SBLineEntry_SetLine(long jarg1, SBLineEntry jarg1_, long jarg2);
public final static native void SBLineEntry_SetColumn(long jarg1, SBLineEntry jarg1_, long jarg2);
public final static native boolean SBLineEntry_GetDescription(long jarg1, SBLineEntry jarg1_, long jarg2, SBStream jarg2_);
public final static native String SBLineEntry___repr__(long jarg1, SBLineEntry jarg1_);
public final static native long new_SBListener__SWIG_0();
public final static native long new_SBListener__SWIG_1(String jarg1);
public final static native long new_SBListener__SWIG_2(long jarg1, SBListener jarg1_);
public final static native void delete_SBListener(long jarg1);
public final static native void SBListener_AddEvent(long jarg1, SBListener jarg1_, long jarg2, SBEvent jarg2_);
public final static native void SBListener_Clear(long jarg1, SBListener jarg1_);
public final static native boolean SBListener_IsValid(long jarg1, SBListener jarg1_);
public final static native long SBListener_StartListeningForEventClass(long jarg1, SBListener jarg1_, long jarg2, SBDebugger jarg2_, String jarg3, long jarg4);
public final static native boolean SBListener_StopListeningForEventClass(long jarg1, SBListener jarg1_, long jarg2, SBDebugger jarg2_, String jarg3, long jarg4);
public final static native long SBListener_StartListeningForEvents(long jarg1, SBListener jarg1_, long jarg2, SBBroadcaster jarg2_, long jarg3);
public final static native boolean SBListener_StopListeningForEvents(long jarg1, SBListener jarg1_, long jarg2, SBBroadcaster jarg2_, long jarg3);
public final static native boolean SBListener_WaitForEvent(long jarg1, SBListener jarg1_, long jarg2, long jarg3, SBEvent jarg3_);
public final static native boolean SBListener_WaitForEventForBroadcaster(long jarg1, SBListener jarg1_, long jarg2, long jarg3, SBBroadcaster jarg3_, long jarg4, SBEvent jarg4_);
public final static native boolean SBListener_WaitForEventForBroadcasterWithType(long jarg1, SBListener jarg1_, long jarg2, long jarg3, SBBroadcaster jarg3_, long jarg4, long jarg5, SBEvent jarg5_);
public final static native boolean SBListener_PeekAtNextEvent(long jarg1, SBListener jarg1_, long jarg2, SBEvent jarg2_);
public final static native boolean SBListener_PeekAtNextEventForBroadcaster(long jarg1, SBListener jarg1_, long jarg2, SBBroadcaster jarg2_, long jarg3, SBEvent jarg3_);
public final static native boolean SBListener_PeekAtNextEventForBroadcasterWithType(long jarg1, SBListener jarg1_, long jarg2, SBBroadcaster jarg2_, long jarg3, long jarg4, SBEvent jarg4_);
public final static native boolean SBListener_GetNextEvent(long jarg1, SBListener jarg1_, long jarg2, SBEvent jarg2_);
public final static native boolean SBListener_GetNextEventForBroadcaster(long jarg1, SBListener jarg1_, long jarg2, SBBroadcaster jarg2_, long jarg3, SBEvent jarg3_);
public final static native boolean SBListener_GetNextEventForBroadcasterWithType(long jarg1, SBListener jarg1_, long jarg2, SBBroadcaster jarg2_, long jarg3, long jarg4, SBEvent jarg4_);
public final static native boolean SBListener_HandleBroadcastEvent(long jarg1, SBListener jarg1_, long jarg2, SBEvent jarg2_);
public final static native long new_SBMemoryRegionInfo__SWIG_0();
public final static native long new_SBMemoryRegionInfo__SWIG_1(long jarg1, SBMemoryRegionInfo jarg1_);
public final static native long new_SBMemoryRegionInfo__SWIG_2(String jarg1, java.math.BigInteger jarg2, java.math.BigInteger jarg3, long jarg4, boolean jarg5, boolean jarg6);
public final static native long new_SBMemoryRegionInfo__SWIG_3(String jarg1, java.math.BigInteger jarg2, java.math.BigInteger jarg3, long jarg4, boolean jarg5);
public final static native void delete_SBMemoryRegionInfo(long jarg1);
public final static native void SBMemoryRegionInfo_Clear(long jarg1, SBMemoryRegionInfo jarg1_);
public final static native java.math.BigInteger SBMemoryRegionInfo_GetRegionBase(long jarg1, SBMemoryRegionInfo jarg1_);
public final static native java.math.BigInteger SBMemoryRegionInfo_GetRegionEnd(long jarg1, SBMemoryRegionInfo jarg1_);
public final static native boolean SBMemoryRegionInfo_IsReadable(long jarg1, SBMemoryRegionInfo jarg1_);
public final static native boolean SBMemoryRegionInfo_IsWritable(long jarg1, SBMemoryRegionInfo jarg1_);
public final static native boolean SBMemoryRegionInfo_IsExecutable(long jarg1, SBMemoryRegionInfo jarg1_);
public final static native boolean SBMemoryRegionInfo_IsMapped(long jarg1, SBMemoryRegionInfo jarg1_);
public final static native String SBMemoryRegionInfo_GetName(long jarg1, SBMemoryRegionInfo jarg1_);
public final static native boolean SBMemoryRegionInfo_HasDirtyMemoryPageList(long jarg1, SBMemoryRegionInfo jarg1_);
public final static native long SBMemoryRegionInfo_GetNumDirtyPages(long jarg1, SBMemoryRegionInfo jarg1_);
public final static native java.math.BigInteger SBMemoryRegionInfo_GetDirtyPageAddressAtIndex(long jarg1, SBMemoryRegionInfo jarg1_, long jarg2);
public final static native int SBMemoryRegionInfo_GetPageSize(long jarg1, SBMemoryRegionInfo jarg1_);
public final static native boolean SBMemoryRegionInfo_GetDescription(long jarg1, SBMemoryRegionInfo jarg1_, long jarg2, SBStream jarg2_);
public final static native String SBMemoryRegionInfo___repr__(long jarg1, SBMemoryRegionInfo jarg1_);
public final static native long new_SBMemoryRegionInfoList__SWIG_0();
public final static native long new_SBMemoryRegionInfoList__SWIG_1(long jarg1, SBMemoryRegionInfoList jarg1_);
public final static native void delete_SBMemoryRegionInfoList(long jarg1);
public final static native long SBMemoryRegionInfoList_GetSize(long jarg1, SBMemoryRegionInfoList jarg1_);
public final static native boolean SBMemoryRegionInfoList_GetMemoryRegionContainingAddress(long jarg1, SBMemoryRegionInfoList jarg1_, java.math.BigInteger jarg2, long jarg3, SBMemoryRegionInfo jarg3_);
public final static native boolean SBMemoryRegionInfoList_GetMemoryRegionAtIndex(long jarg1, SBMemoryRegionInfoList jarg1_, long jarg2, long jarg3, SBMemoryRegionInfo jarg3_);
public final static native void SBMemoryRegionInfoList_Append__SWIG_0(long jarg1, SBMemoryRegionInfoList jarg1_, long jarg2, SBMemoryRegionInfo jarg2_);
public final static native void SBMemoryRegionInfoList_Append__SWIG_1(long jarg1, SBMemoryRegionInfoList jarg1_, long jarg2, SBMemoryRegionInfoList jarg2_);
public final static native void SBMemoryRegionInfoList_Clear(long jarg1, SBMemoryRegionInfoList jarg1_);
public final static native long new_SBModule__SWIG_0();
public final static native long new_SBModule__SWIG_1(long jarg1, SBModule jarg1_);
public final static native long new_SBModule__SWIG_2(long jarg1, SBModuleSpec jarg1_);
public final static native long new_SBModule__SWIG_3(long jarg1, SBProcess jarg1_, java.math.BigInteger jarg2);
public final static native void delete_SBModule(long jarg1);
public final static native boolean SBModule_IsValid(long jarg1, SBModule jarg1_);
public final static native void SBModule_Clear(long jarg1, SBModule jarg1_);
public final static native boolean SBModule_IsFileBacked(long jarg1, SBModule jarg1_);
public final static native long SBModule_GetFileSpec(long jarg1, SBModule jarg1_);
public final static native long SBModule_GetPlatformFileSpec(long jarg1, SBModule jarg1_);
public final static native boolean SBModule_SetPlatformFileSpec(long jarg1, SBModule jarg1_, long jarg2, SBFileSpec jarg2_);
public final static native long SBModule_GetRemoteInstallFileSpec(long jarg1, SBModule jarg1_);
public final static native boolean SBModule_SetRemoteInstallFileSpec(long jarg1, SBModule jarg1_, long jarg2, SBFileSpec jarg2_);
public final static native int SBModule_GetByteOrder(long jarg1, SBModule jarg1_);
public final static native long SBModule_GetAddressByteSize(long jarg1, SBModule jarg1_);
public final static native String SBModule_GetTriple(long jarg1, SBModule jarg1_);
public final static native long SBModule_GetUUIDBytes(long jarg1, SBModule jarg1_);
public final static native String SBModule_GetUUIDString(long jarg1, SBModule jarg1_);
public final static native long SBModule_FindSection(long jarg1, SBModule jarg1_, String jarg2);
public final static native long SBModule_ResolveFileAddress(long jarg1, SBModule jarg1_, java.math.BigInteger jarg2);
public final static native long SBModule_ResolveSymbolContextForAddress(long jarg1, SBModule jarg1_, long jarg2, SBAddress jarg2_, long jarg3);
public final static native boolean SBModule_GetDescription(long jarg1, SBModule jarg1_, long jarg2, SBStream jarg2_);
public final static native long SBModule_GetNumCompileUnits(long jarg1, SBModule jarg1_);
public final static native long SBModule_GetCompileUnitAtIndex(long jarg1, SBModule jarg1_, long jarg2);
public final static native long SBModule_FindCompileUnits(long jarg1, SBModule jarg1_, long jarg2, SBFileSpec jarg2_);
public final static native long SBModule_GetNumSymbols(long jarg1, SBModule jarg1_);
public final static native long SBModule_GetSymbolAtIndex(long jarg1, SBModule jarg1_, long jarg2);
public final static native long SBModule_FindSymbol__SWIG_0(long jarg1, SBModule jarg1_, String jarg2, int jarg3);
public final static native long SBModule_FindSymbol__SWIG_1(long jarg1, SBModule jarg1_, String jarg2);
public final static native long SBModule_FindSymbols__SWIG_0(long jarg1, SBModule jarg1_, String jarg2, int jarg3);
public final static native long SBModule_FindSymbols__SWIG_1(long jarg1, SBModule jarg1_, String jarg2);
public final static native long SBModule_GetNumSections(long jarg1, SBModule jarg1_);
public final static native long SBModule_GetSectionAtIndex(long jarg1, SBModule jarg1_, long jarg2);
public final static native long SBModule_FindFunctions__SWIG_0(long jarg1, SBModule jarg1_, String jarg2, long jarg3);
public final static native long SBModule_FindFunctions__SWIG_1(long jarg1, SBModule jarg1_, String jarg2);
public final static native long SBModule_FindGlobalVariables(long jarg1, SBModule jarg1_, long jarg2, SBTarget jarg2_, String jarg3, long jarg4);
public final static native long SBModule_FindFirstGlobalVariable(long jarg1, SBModule jarg1_, long jarg2, SBTarget jarg2_, String jarg3);
public final static native long SBModule_FindFirstType(long jarg1, SBModule jarg1_, String jarg2);
public final static native long SBModule_FindTypes(long jarg1, SBModule jarg1_, String jarg2);
public final static native long SBModule_GetTypeByID(long jarg1, SBModule jarg1_, java.math.BigInteger jarg2);
public final static native long SBModule_GetBasicType(long jarg1, SBModule jarg1_, int jarg2);
public final static native long SBModule_GetTypes__SWIG_0(long jarg1, SBModule jarg1_, long jarg2);
public final static native long SBModule_GetTypes__SWIG_1(long jarg1, SBModule jarg1_);
public final static native long SBModule_GetVersion(long jarg1, SBModule jarg1_, long jarg2, long jarg3);
public final static native long SBModule_GetSymbolFileSpec(long jarg1, SBModule jarg1_);
public final static native long SBModule_GetObjectFileHeaderAddress(long jarg1, SBModule jarg1_);
public final static native long SBModule_GetObjectFileEntryPointAddress(long jarg1, SBModule jarg1_);
public final static native long SBModule_GetNumberAllocatedModules();
public final static native void SBModule_GarbageCollectAllocatedModules();
public final static native String SBModule___repr__(long jarg1, SBModule jarg1_);
public final static native long new_SBModuleSpec__SWIG_0();
public final static native long new_SBModuleSpec__SWIG_1(long jarg1, SBModuleSpec jarg1_);
public final static native void delete_SBModuleSpec(long jarg1);
public final static native boolean SBModuleSpec_IsValid(long jarg1, SBModuleSpec jarg1_);
public final static native void SBModuleSpec_Clear(long jarg1, SBModuleSpec jarg1_);
public final static native long SBModuleSpec_GetFileSpec(long jarg1, SBModuleSpec jarg1_);
public final static native void SBModuleSpec_SetFileSpec(long jarg1, SBModuleSpec jarg1_, long jarg2, SBFileSpec jarg2_);
public final static native long SBModuleSpec_GetPlatformFileSpec(long jarg1, SBModuleSpec jarg1_);
public final static native void SBModuleSpec_SetPlatformFileSpec(long jarg1, SBModuleSpec jarg1_, long jarg2, SBFileSpec jarg2_);
public final static native long SBModuleSpec_GetSymbolFileSpec(long jarg1, SBModuleSpec jarg1_);
public final static native void SBModuleSpec_SetSymbolFileSpec(long jarg1, SBModuleSpec jarg1_, long jarg2, SBFileSpec jarg2_);
public final static native String SBModuleSpec_GetObjectName(long jarg1, SBModuleSpec jarg1_);
public final static native void SBModuleSpec_SetObjectName(long jarg1, SBModuleSpec jarg1_, String jarg2);
public final static native String SBModuleSpec_GetTriple(long jarg1, SBModuleSpec jarg1_);
public final static native void SBModuleSpec_SetTriple(long jarg1, SBModuleSpec jarg1_, String jarg2);
public final static native long SBModuleSpec_GetUUIDBytes(long jarg1, SBModuleSpec jarg1_);
public final static native long SBModuleSpec_GetUUIDLength(long jarg1, SBModuleSpec jarg1_);
public final static native boolean SBModuleSpec_SetUUIDBytes(long jarg1, SBModuleSpec jarg1_, long jarg2, long jarg3);
public final static native java.math.BigInteger SBModuleSpec_GetObjectOffset(long jarg1, SBModuleSpec jarg1_);
public final static native void SBModuleSpec_SetObjectOffset(long jarg1, SBModuleSpec jarg1_, java.math.BigInteger jarg2);
public final static native java.math.BigInteger SBModuleSpec_GetObjectSize(long jarg1, SBModuleSpec jarg1_);
public final static native void SBModuleSpec_SetObjectSize(long jarg1, SBModuleSpec jarg1_, java.math.BigInteger jarg2);
public final static native boolean SBModuleSpec_GetDescription(long jarg1, SBModuleSpec jarg1_, long jarg2, SBStream jarg2_);
public final static native String SBModuleSpec___repr__(long jarg1, SBModuleSpec jarg1_);
public final static native long new_SBModuleSpecList__SWIG_0();
public final static native long new_SBModuleSpecList__SWIG_1(long jarg1, SBModuleSpecList jarg1_);
public final static native void delete_SBModuleSpecList(long jarg1);
public final static native long SBModuleSpecList_GetModuleSpecifications(String jarg1);
public final static native void SBModuleSpecList_Append__SWIG_0(long jarg1, SBModuleSpecList jarg1_, long jarg2, SBModuleSpec jarg2_);
public final static native void SBModuleSpecList_Append__SWIG_1(long jarg1, SBModuleSpecList jarg1_, long jarg2, SBModuleSpecList jarg2_);
public final static native long SBModuleSpecList_FindFirstMatchingSpec(long jarg1, SBModuleSpecList jarg1_, long jarg2, SBModuleSpec jarg2_);
public final static native long SBModuleSpecList_FindMatchingSpecs(long jarg1, SBModuleSpecList jarg1_, long jarg2, SBModuleSpec jarg2_);
public final static native long SBModuleSpecList_GetSize(long jarg1, SBModuleSpecList jarg1_);
public final static native long SBModuleSpecList_GetSpecAtIndex(long jarg1, SBModuleSpecList jarg1_, long jarg2);
public final static native boolean SBModuleSpecList_GetDescription(long jarg1, SBModuleSpecList jarg1_, long jarg2, SBStream jarg2_);
public final static native String SBModuleSpecList___repr__(long jarg1, SBModuleSpecList jarg1_);
public final static native long new_SBPlatformConnectOptions__SWIG_0(String jarg1);
public final static native long new_SBPlatformConnectOptions__SWIG_1(long jarg1, SBPlatformConnectOptions jarg1_);
public final static native void delete_SBPlatformConnectOptions(long jarg1);
public final static native String SBPlatformConnectOptions_GetURL(long jarg1, SBPlatformConnectOptions jarg1_);
public final static native void SBPlatformConnectOptions_SetURL(long jarg1, SBPlatformConnectOptions jarg1_, String jarg2);
public final static native boolean SBPlatformConnectOptions_GetRsyncEnabled(long jarg1, SBPlatformConnectOptions jarg1_);
public final static native void SBPlatformConnectOptions_EnableRsync(long jarg1, SBPlatformConnectOptions jarg1_, String jarg2, String jarg3, boolean jarg4);
public final static native void SBPlatformConnectOptions_DisableRsync(long jarg1, SBPlatformConnectOptions jarg1_);
public final static native String SBPlatformConnectOptions_GetLocalCacheDirectory(long jarg1, SBPlatformConnectOptions jarg1_);
public final static native void SBPlatformConnectOptions_SetLocalCacheDirectory(long jarg1, SBPlatformConnectOptions jarg1_, String jarg2);
public final static native long new_SBPlatformShellCommand__SWIG_0(String jarg1, String jarg2);
public final static native long new_SBPlatformShellCommand__SWIG_1(String jarg1);
public final static native long new_SBPlatformShellCommand__SWIG_2(long jarg1, SBPlatformShellCommand jarg1_);
public final static native void delete_SBPlatformShellCommand(long jarg1);
public final static native void SBPlatformShellCommand_Clear(long jarg1, SBPlatformShellCommand jarg1_);
public final static native String SBPlatformShellCommand_GetShell(long jarg1, SBPlatformShellCommand jarg1_);
public final static native void SBPlatformShellCommand_SetShell(long jarg1, SBPlatformShellCommand jarg1_, String jarg2);
public final static native String SBPlatformShellCommand_GetCommand(long jarg1, SBPlatformShellCommand jarg1_);
public final static native void SBPlatformShellCommand_SetCommand(long jarg1, SBPlatformShellCommand jarg1_, String jarg2);
public final static native String SBPlatformShellCommand_GetWorkingDirectory(long jarg1, SBPlatformShellCommand jarg1_);
public final static native void SBPlatformShellCommand_SetWorkingDirectory(long jarg1, SBPlatformShellCommand jarg1_, String jarg2);
public final static native long SBPlatformShellCommand_GetTimeoutSeconds(long jarg1, SBPlatformShellCommand jarg1_);
public final static native void SBPlatformShellCommand_SetTimeoutSeconds(long jarg1, SBPlatformShellCommand jarg1_, long jarg2);
public final static native int SBPlatformShellCommand_GetSignal(long jarg1, SBPlatformShellCommand jarg1_);
public final static native int SBPlatformShellCommand_GetStatus(long jarg1, SBPlatformShellCommand jarg1_);
public final static native String SBPlatformShellCommand_GetOutput(long jarg1, SBPlatformShellCommand jarg1_);
public final static native long new_SBPlatform__SWIG_0();
public final static native long new_SBPlatform__SWIG_1(String jarg1);
public final static native long new_SBPlatform__SWIG_2(long jarg1, SBPlatform jarg1_);
public final static native void delete_SBPlatform(long jarg1);
public final static native long SBPlatform_GetHostPlatform();
public final static native boolean SBPlatform_IsValid(long jarg1, SBPlatform jarg1_);
public final static native void SBPlatform_Clear(long jarg1, SBPlatform jarg1_);
public final static native String SBPlatform_GetWorkingDirectory(long jarg1, SBPlatform jarg1_);
public final static native boolean SBPlatform_SetWorkingDirectory(long jarg1, SBPlatform jarg1_, String jarg2);
public final static native String SBPlatform_GetName(long jarg1, SBPlatform jarg1_);
public final static native long SBPlatform_ConnectRemote(long jarg1, SBPlatform jarg1_, long jarg2, SBPlatformConnectOptions jarg2_);
public final static native void SBPlatform_DisconnectRemote(long jarg1, SBPlatform jarg1_);
public final static native boolean SBPlatform_IsConnected(long jarg1, SBPlatform jarg1_);
public final static native String SBPlatform_GetTriple(long jarg1, SBPlatform jarg1_);
public final static native String SBPlatform_GetHostname(long jarg1, SBPlatform jarg1_);
public final static native String SBPlatform_GetOSBuild(long jarg1, SBPlatform jarg1_);
public final static native String SBPlatform_GetOSDescription(long jarg1, SBPlatform jarg1_);
public final static native long SBPlatform_GetOSMajorVersion(long jarg1, SBPlatform jarg1_);
public final static native long SBPlatform_GetOSMinorVersion(long jarg1, SBPlatform jarg1_);
public final static native long SBPlatform_GetOSUpdateVersion(long jarg1, SBPlatform jarg1_);
public final static native void SBPlatform_SetSDKRoot(long jarg1, SBPlatform jarg1_, String jarg2);
public final static native long SBPlatform_Put(long jarg1, SBPlatform jarg1_, long jarg2, SBFileSpec jarg2_, long jarg3, SBFileSpec jarg3_);
public final static native long SBPlatform_Get(long jarg1, SBPlatform jarg1_, long jarg2, SBFileSpec jarg2_, long jarg3, SBFileSpec jarg3_);
public final static native long SBPlatform_Install(long jarg1, SBPlatform jarg1_, long jarg2, SBFileSpec jarg2_, long jarg3, SBFileSpec jarg3_);
public final static native long SBPlatform_Run(long jarg1, SBPlatform jarg1_, long jarg2, SBPlatformShellCommand jarg2_);
public final static native long SBPlatform_Launch(long jarg1, SBPlatform jarg1_, long jarg2, SBLaunchInfo jarg2_);
public final static native long SBPlatform_Kill(long jarg1, SBPlatform jarg1_, java.math.BigInteger jarg2);
public final static native long SBPlatform_MakeDirectory__SWIG_0(long jarg1, SBPlatform jarg1_, String jarg2, long jarg3);
public final static native long SBPlatform_MakeDirectory__SWIG_1(long jarg1, SBPlatform jarg1_, String jarg2);
public final static native long SBPlatform_GetFilePermissions(long jarg1, SBPlatform jarg1_, String jarg2);
public final static native long SBPlatform_SetFilePermissions(long jarg1, SBPlatform jarg1_, String jarg2, long jarg3);
public final static native long SBPlatform_GetUnixSignals(long jarg1, SBPlatform jarg1_);
public final static native long SBPlatform_GetEnvironment(long jarg1, SBPlatform jarg1_);
public final static native long SBPlatform_SetLocateModuleCallback(long jarg1, SBPlatform jarg1_, long jarg2, long jarg3);
public final static native int SBProcess_eBroadcastBitStateChanged_get();
public final static native int SBProcess_eBroadcastBitInterrupt_get();
public final static native int SBProcess_eBroadcastBitSTDOUT_get();
public final static native int SBProcess_eBroadcastBitSTDERR_get();
public final static native int SBProcess_eBroadcastBitProfileData_get();
public final static native int SBProcess_eBroadcastBitStructuredData_get();
public final static native long new_SBProcess__SWIG_0();
public final static native long new_SBProcess__SWIG_1(long jarg1, SBProcess jarg1_);
public final static native void delete_SBProcess(long jarg1);
public final static native String SBProcess_GetBroadcasterClassName();
public final static native String SBProcess_GetPluginName(long jarg1, SBProcess jarg1_);
public final static native String SBProcess_GetShortPluginName(long jarg1, SBProcess jarg1_);
public final static native void SBProcess_Clear(long jarg1, SBProcess jarg1_);
public final static native boolean SBProcess_IsValid(long jarg1, SBProcess jarg1_);
public final static native long SBProcess_GetTarget(long jarg1, SBProcess jarg1_);
public final static native int SBProcess_GetByteOrder(long jarg1, SBProcess jarg1_);
public final static native long SBProcess_PutSTDIN(long jarg1, SBProcess jarg1_, String jarg2, long jarg3);
public final static native long SBProcess_GetSTDOUT(long jarg1, SBProcess jarg1_, String jarg2, long jarg3);
public final static native long SBProcess_GetSTDERR(long jarg1, SBProcess jarg1_, String jarg2, long jarg3);
public final static native long SBProcess_GetAsyncProfileData(long jarg1, SBProcess jarg1_, String jarg2, long jarg3);
public final static native void SBProcess_ReportEventState__SWIG_0(long jarg1, SBProcess jarg1_, long jarg2, SBEvent jarg2_, long jarg3, SBFile jarg3_);
public final static native void SBProcess_ReportEventState__SWIG_1(long jarg1, SBProcess jarg1_, long jarg2, SBEvent jarg2_, long jarg3);
public final static native void SBProcess_AppendEventStateReport(long jarg1, SBProcess jarg1_, long jarg2, SBEvent jarg2_, long jarg3, SBCommandReturnObject jarg3_);
public final static native boolean SBProcess_RemoteAttachToProcessWithID(long jarg1, SBProcess jarg1_, java.math.BigInteger jarg2, long jarg3, SBError jarg3_);
public final static native boolean SBProcess_RemoteLaunch(long jarg1, SBProcess jarg1_, String[] jarg2, String[] jarg3, String jarg4, String jarg5, String jarg6, String jarg7, long jarg8, boolean jarg9, long jarg10, SBError jarg10_);
public final static native long SBProcess_GetNumThreads(long jarg1, SBProcess jarg1_);
public final static native long SBProcess_GetThreadAtIndex(long jarg1, SBProcess jarg1_, long jarg2);
public final static native long SBProcess_GetThreadByID(long jarg1, SBProcess jarg1_, java.math.BigInteger jarg2);
public final static native long SBProcess_GetThreadByIndexID(long jarg1, SBProcess jarg1_, long jarg2);
public final static native long SBProcess_GetSelectedThread(long jarg1, SBProcess jarg1_);
public final static native long SBProcess_CreateOSPluginThread(long jarg1, SBProcess jarg1_, java.math.BigInteger jarg2, java.math.BigInteger jarg3);
public final static native boolean SBProcess_SetSelectedThread(long jarg1, SBProcess jarg1_, long jarg2, SBThread jarg2_);
public final static native boolean SBProcess_SetSelectedThreadByID(long jarg1, SBProcess jarg1_, java.math.BigInteger jarg2);
public final static native boolean SBProcess_SetSelectedThreadByIndexID(long jarg1, SBProcess jarg1_, long jarg2);
public final static native long SBProcess_GetNumQueues(long jarg1, SBProcess jarg1_);
public final static native long SBProcess_GetQueueAtIndex(long jarg1, SBProcess jarg1_, long jarg2);
public final static native int SBProcess_GetState(long jarg1, SBProcess jarg1_);
public final static native int SBProcess_GetExitStatus(long jarg1, SBProcess jarg1_);
public final static native String SBProcess_GetExitDescription(long jarg1, SBProcess jarg1_);
public final static native java.math.BigInteger SBProcess_GetProcessID(long jarg1, SBProcess jarg1_);
public final static native long SBProcess_GetUniqueID(long jarg1, SBProcess jarg1_);
public final static native long SBProcess_GetAddressByteSize(long jarg1, SBProcess jarg1_);
public final static native long SBProcess_Destroy(long jarg1, SBProcess jarg1_);
public final static native long SBProcess_Continue(long jarg1, SBProcess jarg1_);
public final static native long SBProcess_Stop(long jarg1, SBProcess jarg1_);
public final static native long SBProcess_Kill(long jarg1, SBProcess jarg1_);
public final static native long SBProcess_Detach__SWIG_0(long jarg1, SBProcess jarg1_);
public final static native long SBProcess_Detach__SWIG_1(long jarg1, SBProcess jarg1_, boolean jarg2);
public final static native long SBProcess_Signal(long jarg1, SBProcess jarg1_, int jarg2);
public final static native long SBProcess_GetUnixSignals(long jarg1, SBProcess jarg1_);
public final static native void SBProcess_SendAsyncInterrupt(long jarg1, SBProcess jarg1_);
public final static native long SBProcess_GetStopID__SWIG_0(long jarg1, SBProcess jarg1_, boolean jarg2);
public final static native long SBProcess_GetStopID__SWIG_1(long jarg1, SBProcess jarg1_);
public final static native long SBProcess_GetStopEventForStopID(long jarg1, SBProcess jarg1_, long jarg2);
public final static native void SBProcess_ForceScriptedState(long jarg1, SBProcess jarg1_, int jarg2);
public final static native long SBProcess_ReadMemory(long jarg1, SBProcess jarg1_, java.math.BigInteger jarg2, long jarg3, long jarg4, long jarg5, SBError jarg5_);
public final static native long SBProcess_WriteMemory(long jarg1, SBProcess jarg1_, java.math.BigInteger jarg2, long jarg3, long jarg4, long jarg5, SBError jarg5_);
public final static native long SBProcess_ReadCStringFromMemory(long jarg1, SBProcess jarg1_, java.math.BigInteger jarg2, long jarg3, long jarg4, long jarg5, SBError jarg5_);
public final static native java.math.BigInteger SBProcess_ReadUnsignedFromMemory(long jarg1, SBProcess jarg1_, java.math.BigInteger jarg2, long jarg3, long jarg4, SBError jarg4_);
public final static native java.math.BigInteger SBProcess_ReadPointerFromMemory(long jarg1, SBProcess jarg1_, java.math.BigInteger jarg2, long jarg3, SBError jarg3_);
public final static native int SBProcess_GetStateFromEvent(long jarg1, SBEvent jarg1_);
public final static native boolean SBProcess_GetRestartedFromEvent(long jarg1, SBEvent jarg1_);
public final static native long SBProcess_GetNumRestartedReasonsFromEvent(long jarg1, SBEvent jarg1_);
public final static native String SBProcess_GetRestartedReasonAtIndexFromEvent(long jarg1, SBEvent jarg1_, long jarg2);
public final static native long SBProcess_GetProcessFromEvent(long jarg1, SBEvent jarg1_);
public final static native boolean SBProcess_GetInterruptedFromEvent(long jarg1, SBEvent jarg1_);
public final static native long SBProcess_GetStructuredDataFromEvent(long jarg1, SBEvent jarg1_);
public final static native boolean SBProcess_EventIsProcessEvent(long jarg1, SBEvent jarg1_);
public final static native boolean SBProcess_EventIsStructuredDataEvent(long jarg1, SBEvent jarg1_);
public final static native long SBProcess_GetBroadcaster(long jarg1, SBProcess jarg1_);
public final static native String SBProcess_GetBroadcasterClass();
public final static native boolean SBProcess_GetDescription(long jarg1, SBProcess jarg1_, long jarg2, SBStream jarg2_);
public final static native long SBProcess_GetExtendedCrashInformation(long jarg1, SBProcess jarg1_);
public final static native long SBProcess_GetNumSupportedHardwareWatchpoints(long jarg1, SBProcess jarg1_, long jarg2, SBError jarg2_);
public final static native long SBProcess_LoadImage__SWIG_0(long jarg1, SBProcess jarg1_, long jarg2, SBFileSpec jarg2_, long jarg3, SBError jarg3_);
public final static native long SBProcess_LoadImage__SWIG_1(long jarg1, SBProcess jarg1_, long jarg2, SBFileSpec jarg2_, long jarg3, SBFileSpec jarg3_, long jarg4, SBError jarg4_);
public final static native long SBProcess_LoadImageUsingPaths(long jarg1, SBProcess jarg1_, long jarg2, SBFileSpec jarg2_, long jarg3, SBStringList jarg3_, long jarg4, SBFileSpec jarg4_, long jarg5, SBError jarg5_);
public final static native long SBProcess_UnloadImage(long jarg1, SBProcess jarg1_, long jarg2);
public final static native long SBProcess_SendEventData(long jarg1, SBProcess jarg1_, String jarg2);
public final static native long SBProcess_GetNumExtendedBacktraceTypes(long jarg1, SBProcess jarg1_);
public final static native String SBProcess_GetExtendedBacktraceTypeAtIndex(long jarg1, SBProcess jarg1_, long jarg2);
public final static native long SBProcess_GetHistoryThreads(long jarg1, SBProcess jarg1_, java.math.BigInteger jarg2);
public final static native boolean SBProcess_IsInstrumentationRuntimePresent(long jarg1, SBProcess jarg1_, int jarg2);
public final static native long SBProcess_SaveCore__SWIG_0(long jarg1, SBProcess jarg1_, String jarg2, String jarg3, int jarg4);
public final static native long SBProcess_SaveCore__SWIG_1(long jarg1, SBProcess jarg1_, String jarg2);
public final static native long SBProcess_GetMemoryRegionInfo(long jarg1, SBProcess jarg1_, java.math.BigInteger jarg2, long jarg3, SBMemoryRegionInfo jarg3_);
public final static native long SBProcess_GetMemoryRegions(long jarg1, SBProcess jarg1_);
public final static native long SBProcess_GetProcessInfo(long jarg1, SBProcess jarg1_);
public final static native java.math.BigInteger SBProcess_AllocateMemory(long jarg1, SBProcess jarg1_, long jarg2, long jarg3, long jarg4, SBError jarg4_);
public final static native long SBProcess_DeallocateMemory(long jarg1, SBProcess jarg1_, java.math.BigInteger jarg2);
public final static native long SBProcess_GetScriptedImplementation(long jarg1, SBProcess jarg1_);
public final static native String SBProcess___repr__(long jarg1, SBProcess jarg1_);
public final static native long new_SBProcessInfo__SWIG_0();
public final static native long new_SBProcessInfo__SWIG_1(long jarg1, SBProcessInfo jarg1_);
public final static native void delete_SBProcessInfo(long jarg1);
public final static native boolean SBProcessInfo_IsValid(long jarg1, SBProcessInfo jarg1_);
public final static native String SBProcessInfo_GetName(long jarg1, SBProcessInfo jarg1_);
public final static native long SBProcessInfo_GetExecutableFile(long jarg1, SBProcessInfo jarg1_);
public final static native java.math.BigInteger SBProcessInfo_GetProcessID(long jarg1, SBProcessInfo jarg1_);
public final static native long SBProcessInfo_GetUserID(long jarg1, SBProcessInfo jarg1_);
public final static native long SBProcessInfo_GetGroupID(long jarg1, SBProcessInfo jarg1_);
public final static native boolean SBProcessInfo_UserIDIsValid(long jarg1, SBProcessInfo jarg1_);
public final static native boolean SBProcessInfo_GroupIDIsValid(long jarg1, SBProcessInfo jarg1_);
public final static native long SBProcessInfo_GetEffectiveUserID(long jarg1, SBProcessInfo jarg1_);
public final static native long SBProcessInfo_GetEffectiveGroupID(long jarg1, SBProcessInfo jarg1_);
public final static native boolean SBProcessInfo_EffectiveUserIDIsValid(long jarg1, SBProcessInfo jarg1_);
public final static native boolean SBProcessInfo_EffectiveGroupIDIsValid(long jarg1, SBProcessInfo jarg1_);
public final static native java.math.BigInteger SBProcessInfo_GetParentProcessID(long jarg1, SBProcessInfo jarg1_);
public final static native String SBProcessInfo_GetTriple(long jarg1, SBProcessInfo jarg1_);
public final static native long new_SBQueue__SWIG_0();
public final static native long new_SBQueue__SWIG_1(long jarg1, SBQueue jarg1_);
public final static native void delete_SBQueue(long jarg1);
public final static native boolean SBQueue_IsValid(long jarg1, SBQueue jarg1_);
public final static native void SBQueue_Clear(long jarg1, SBQueue jarg1_);
public final static native long SBQueue_GetProcess(long jarg1, SBQueue jarg1_);
public final static native java.math.BigInteger SBQueue_GetQueueID(long jarg1, SBQueue jarg1_);
public final static native String SBQueue_GetName(long jarg1, SBQueue jarg1_);
public final static native long SBQueue_GetIndexID(long jarg1, SBQueue jarg1_);
public final static native long SBQueue_GetNumThreads(long jarg1, SBQueue jarg1_);
public final static native long SBQueue_GetThreadAtIndex(long jarg1, SBQueue jarg1_, long jarg2);
public final static native long SBQueue_GetNumPendingItems(long jarg1, SBQueue jarg1_);
public final static native long SBQueue_GetPendingItemAtIndex(long jarg1, SBQueue jarg1_, long jarg2);
public final static native long SBQueue_GetNumRunningItems(long jarg1, SBQueue jarg1_);
public final static native int SBQueue_GetKind(long jarg1, SBQueue jarg1_);
public final static native long new_SBQueueItem();
public final static native void delete_SBQueueItem(long jarg1);
public final static native boolean SBQueueItem_IsValid(long jarg1, SBQueueItem jarg1_);
public final static native void SBQueueItem_Clear(long jarg1, SBQueueItem jarg1_);
public final static native int SBQueueItem_GetKind(long jarg1, SBQueueItem jarg1_);
public final static native void SBQueueItem_SetKind(long jarg1, SBQueueItem jarg1_, int jarg2);
public final static native long SBQueueItem_GetAddress(long jarg1, SBQueueItem jarg1_);
public final static native void SBQueueItem_SetAddress(long jarg1, SBQueueItem jarg1_, long jarg2, SBAddress jarg2_);
public final static native long SBQueueItem_GetExtendedBacktraceThread(long jarg1, SBQueueItem jarg1_, String jarg2);
public final static native String SBReproducer_Capture(String jarg1);
public final static native String SBReproducer_PassiveReplay(String jarg1);
public final static native boolean SBReproducer_SetAutoGenerate(boolean jarg1);
public final static native void SBReproducer_SetWorkingDirectory(String jarg1);
public final static native long new_SBReproducer();
public final static native void delete_SBReproducer(long jarg1);
public final static native long new_SBScriptObject__SWIG_0(long jarg1, int jarg2);
public final static native long new_SBScriptObject__SWIG_1(long jarg1, SBScriptObject jarg1_);
public final static native void delete_SBScriptObject(long jarg1);
public final static native boolean SBScriptObject_IsValid(long jarg1, SBScriptObject jarg1_);
public final static native long SBScriptObject_GetPointer(long jarg1, SBScriptObject jarg1_);
public final static native int SBScriptObject_GetLanguage(long jarg1, SBScriptObject jarg1_);
public final static native long new_SBSection__SWIG_0();
public final static native long new_SBSection__SWIG_1(long jarg1, SBSection jarg1_);
public final static native void delete_SBSection(long jarg1);
public final static native boolean SBSection_IsValid(long jarg1, SBSection jarg1_);
public final static native String SBSection_GetName(long jarg1, SBSection jarg1_);
public final static native long SBSection_GetParent(long jarg1, SBSection jarg1_);
public final static native long SBSection_FindSubSection(long jarg1, SBSection jarg1_, String jarg2);
public final static native long SBSection_GetNumSubSections(long jarg1, SBSection jarg1_);
public final static native long SBSection_GetSubSectionAtIndex(long jarg1, SBSection jarg1_, long jarg2);
public final static native java.math.BigInteger SBSection_GetFileAddress(long jarg1, SBSection jarg1_);
public final static native java.math.BigInteger SBSection_GetLoadAddress(long jarg1, SBSection jarg1_, long jarg2, SBTarget jarg2_);
public final static native java.math.BigInteger SBSection_GetByteSize(long jarg1, SBSection jarg1_);
public final static native java.math.BigInteger SBSection_GetFileOffset(long jarg1, SBSection jarg1_);
public final static native java.math.BigInteger SBSection_GetFileByteSize(long jarg1, SBSection jarg1_);
public final static native long SBSection_GetSectionData__SWIG_0(long jarg1, SBSection jarg1_);
public final static native long SBSection_GetSectionData__SWIG_1(long jarg1, SBSection jarg1_, java.math.BigInteger jarg2, java.math.BigInteger jarg3);
public final static native int SBSection_GetSectionType(long jarg1, SBSection jarg1_);
public final static native long SBSection_GetPermissions(long jarg1, SBSection jarg1_);
public final static native long SBSection_GetTargetByteSize(long jarg1, SBSection jarg1_);
public final static native long SBSection_GetAlignment(long jarg1, SBSection jarg1_);
public final static native boolean SBSection_GetDescription(long jarg1, SBSection jarg1_, long jarg2, SBStream jarg2_);
public final static native String SBSection___repr__(long jarg1, SBSection jarg1_);
public final static native long new_SBSourceManager__SWIG_0(long jarg1, SBDebugger jarg1_);
public final static native long new_SBSourceManager__SWIG_1(long jarg1, SBTarget jarg1_);
public final static native long new_SBSourceManager__SWIG_2(long jarg1, SBSourceManager jarg1_);
public final static native void delete_SBSourceManager(long jarg1);
public final static native long SBSourceManager_DisplaySourceLinesWithLineNumbers(long jarg1, SBSourceManager jarg1_, long jarg2, SBFileSpec jarg2_, long jarg3, long jarg4, long jarg5, String jarg6, long jarg7, SBStream jarg7_);
public final static native long SBSourceManager_DisplaySourceLinesWithLineNumbersAndColumn(long jarg1, SBSourceManager jarg1_, long jarg2, SBFileSpec jarg2_, long jarg3, long jarg4, long jarg5, long jarg6, String jarg7, long jarg8, SBStream jarg8_);
public final static native long new_SBStream();
public final static native void delete_SBStream(long jarg1);
public final static native boolean SBStream_IsValid(long jarg1, SBStream jarg1_);
public final static native String SBStream_GetData(long jarg1, SBStream jarg1_);
public final static native long SBStream_GetSize(long jarg1, SBStream jarg1_);
public final static native void SBStream_Print(long jarg1, SBStream jarg1_, String jarg2);
public final static native void SBStream_RedirectToFile__SWIG_0(long jarg1, SBStream jarg1_, String jarg2, boolean jarg3);
public final static native void SBStream_RedirectToFile__SWIG_1(long jarg1, SBStream jarg1_, long jarg2, SBFile jarg2_);
public final static native void SBStream_RedirectToFile__SWIG_2(long jarg1, SBStream jarg1_, long jarg2);
public final static native void SBStream_RedirectToFileDescriptor(long jarg1, SBStream jarg1_, int jarg2, boolean jarg3);
public final static native void SBStream_Clear(long jarg1, SBStream jarg1_);
public final static native void SBStream_RedirectToFileHandle(long jarg1, SBStream jarg1_, long jarg2, boolean jarg3);
public final static native long new_SBStringList__SWIG_0();
public final static native long new_SBStringList__SWIG_1(long jarg1, SBStringList jarg1_);
public final static native void delete_SBStringList(long jarg1);
public final static native boolean SBStringList_IsValid(long jarg1, SBStringList jarg1_);
public final static native void SBStringList_AppendString(long jarg1, SBStringList jarg1_, String jarg2);
public final static native void SBStringList_AppendList__SWIG_0(long jarg1, SBStringList jarg1_, String[] jarg2, int jarg3);
public final static native void SBStringList_AppendList__SWIG_1(long jarg1, SBStringList jarg1_, long jarg2, SBStringList jarg2_);
public final static native long SBStringList_GetSize(long jarg1, SBStringList jarg1_);
public final static native String SBStringList_GetStringAtIndex__SWIG_0(long jarg1, SBStringList jarg1_, long jarg2);
public final static native void SBStringList_Clear(long jarg1, SBStringList jarg1_);
public final static native long new_SBStructuredData__SWIG_0();
public final static native long new_SBStructuredData__SWIG_1(long jarg1, SBStructuredData jarg1_);
public final static native long new_SBStructuredData__SWIG_2(long jarg1, SBScriptObject jarg1_, long jarg2, SBDebugger jarg2_);
public final static native void delete_SBStructuredData(long jarg1);
public final static native boolean SBStructuredData_IsValid(long jarg1, SBStructuredData jarg1_);
public final static native long SBStructuredData_SetFromJSON__SWIG_0(long jarg1, SBStructuredData jarg1_, long jarg2, SBStream jarg2_);
public final static native long SBStructuredData_SetFromJSON__SWIG_1(long jarg1, SBStructuredData jarg1_, String jarg2);
public final static native void SBStructuredData_Clear(long jarg1, SBStructuredData jarg1_);
public final static native long SBStructuredData_GetAsJSON(long jarg1, SBStructuredData jarg1_, long jarg2, SBStream jarg2_);
public final static native long SBStructuredData_GetDescription(long jarg1, SBStructuredData jarg1_, long jarg2, SBStream jarg2_);
public final static native int SBStructuredData_GetType(long jarg1, SBStructuredData jarg1_);
public final static native long SBStructuredData_GetSize(long jarg1, SBStructuredData jarg1_);
public final static native boolean SBStructuredData_GetKeys(long jarg1, SBStructuredData jarg1_, long jarg2, SBStringList jarg2_);
public final static native long SBStructuredData_GetValueForKey(long jarg1, SBStructuredData jarg1_, String jarg2);
public final static native long SBStructuredData_GetItemAtIndex(long jarg1, SBStructuredData jarg1_, long jarg2);
public final static native java.math.BigInteger SBStructuredData_GetUnsignedIntegerValue__SWIG_0(long jarg1, SBStructuredData jarg1_, java.math.BigInteger jarg2);
public final static native java.math.BigInteger SBStructuredData_GetUnsignedIntegerValue__SWIG_1(long jarg1, SBStructuredData jarg1_);
public final static native long SBStructuredData_GetSignedIntegerValue__SWIG_0(long jarg1, SBStructuredData jarg1_, long jarg2);
public final static native long SBStructuredData_GetSignedIntegerValue__SWIG_1(long jarg1, SBStructuredData jarg1_);
public final static native java.math.BigInteger SBStructuredData_GetIntegerValue__SWIG_0(long jarg1, SBStructuredData jarg1_, java.math.BigInteger jarg2);
public final static native java.math.BigInteger SBStructuredData_GetIntegerValue__SWIG_1(long jarg1, SBStructuredData jarg1_);
public final static native double SBStructuredData_GetFloatValue__SWIG_0(long jarg1, SBStructuredData jarg1_, double jarg2);
public final static native double SBStructuredData_GetFloatValue__SWIG_1(long jarg1, SBStructuredData jarg1_);
public final static native boolean SBStructuredData_GetBooleanValue__SWIG_0(long jarg1, SBStructuredData jarg1_, boolean jarg2);
public final static native boolean SBStructuredData_GetBooleanValue__SWIG_1(long jarg1, SBStructuredData jarg1_);
public final static native long SBStructuredData_GetStringValue(long jarg1, SBStructuredData jarg1_, String jarg2, long jarg3);
public final static native long SBStructuredData_GetGenericValue(long jarg1, SBStructuredData jarg1_);
public final static native long new_SBSymbol__SWIG_0();
public final static native void delete_SBSymbol(long jarg1);
public final static native long new_SBSymbol__SWIG_1(long jarg1, SBSymbol jarg1_);
public final static native boolean SBSymbol_IsValid(long jarg1, SBSymbol jarg1_);
public final static native String SBSymbol_GetName(long jarg1, SBSymbol jarg1_);
public final static native String SBSymbol_GetDisplayName(long jarg1, SBSymbol jarg1_);
public final static native String SBSymbol_GetMangledName(long jarg1, SBSymbol jarg1_);
public final static native long SBSymbol_GetInstructions__SWIG_0(long jarg1, SBSymbol jarg1_, long jarg2, SBTarget jarg2_);
public final static native long SBSymbol_GetInstructions__SWIG_1(long jarg1, SBSymbol jarg1_, long jarg2, SBTarget jarg2_, String jarg3);
public final static native long SBSymbol_GetStartAddress(long jarg1, SBSymbol jarg1_);
public final static native long SBSymbol_GetEndAddress(long jarg1, SBSymbol jarg1_);
public final static native java.math.BigInteger SBSymbol_GetValue(long jarg1, SBSymbol jarg1_);
public final static native java.math.BigInteger SBSymbol_GetSize(long jarg1, SBSymbol jarg1_);
public final static native long SBSymbol_GetPrologueByteSize(long jarg1, SBSymbol jarg1_);
public final static native int SBSymbol_GetType(long jarg1, SBSymbol jarg1_);
public final static native boolean SBSymbol_GetDescription(long jarg1, SBSymbol jarg1_, long jarg2, SBStream jarg2_);
public final static native boolean SBSymbol_IsExternal(long jarg1, SBSymbol jarg1_);
public final static native boolean SBSymbol_IsSynthetic(long jarg1, SBSymbol jarg1_);
public final static native String SBSymbol___repr__(long jarg1, SBSymbol jarg1_);
public final static native long new_SBSymbolContext__SWIG_0();
public final static native long new_SBSymbolContext__SWIG_1(long jarg1, SBSymbolContext jarg1_);
public final static native void delete_SBSymbolContext(long jarg1);
public final static native boolean SBSymbolContext_IsValid(long jarg1, SBSymbolContext jarg1_);
public final static native long SBSymbolContext_GetModule(long jarg1, SBSymbolContext jarg1_);
public final static native long SBSymbolContext_GetCompileUnit(long jarg1, SBSymbolContext jarg1_);
public final static native long SBSymbolContext_GetFunction(long jarg1, SBSymbolContext jarg1_);
public final static native long SBSymbolContext_GetBlock(long jarg1, SBSymbolContext jarg1_);
public final static native long SBSymbolContext_GetLineEntry(long jarg1, SBSymbolContext jarg1_);
public final static native long SBSymbolContext_GetSymbol(long jarg1, SBSymbolContext jarg1_);
public final static native void SBSymbolContext_SetModule(long jarg1, SBSymbolContext jarg1_, long jarg2, SBModule jarg2_);
public final static native void SBSymbolContext_SetCompileUnit(long jarg1, SBSymbolContext jarg1_, long jarg2, SBCompileUnit jarg2_);
public final static native void SBSymbolContext_SetFunction(long jarg1, SBSymbolContext jarg1_, long jarg2, SBFunction jarg2_);
public final static native void SBSymbolContext_SetBlock(long jarg1, SBSymbolContext jarg1_, long jarg2, SBBlock jarg2_);
public final static native void SBSymbolContext_SetLineEntry(long jarg1, SBSymbolContext jarg1_, long jarg2, SBLineEntry jarg2_);
public final static native void SBSymbolContext_SetSymbol(long jarg1, SBSymbolContext jarg1_, long jarg2, SBSymbol jarg2_);
public final static native long SBSymbolContext_GetParentOfInlinedScope(long jarg1, SBSymbolContext jarg1_, long jarg2, SBAddress jarg2_, long jarg3, SBAddress jarg3_);
public final static native boolean SBSymbolContext_GetDescription(long jarg1, SBSymbolContext jarg1_, long jarg2, SBStream jarg2_);
public final static native String SBSymbolContext___repr__(long jarg1, SBSymbolContext jarg1_);
public final static native long new_SBSymbolContextList__SWIG_0();
public final static native long new_SBSymbolContextList__SWIG_1(long jarg1, SBSymbolContextList jarg1_);
public final static native void delete_SBSymbolContextList(long jarg1);
public final static native boolean SBSymbolContextList_IsValid(long jarg1, SBSymbolContextList jarg1_);
public final static native long SBSymbolContextList_GetSize(long jarg1, SBSymbolContextList jarg1_);
public final static native long SBSymbolContextList_GetContextAtIndex(long jarg1, SBSymbolContextList jarg1_, long jarg2);
public final static native boolean SBSymbolContextList_GetDescription(long jarg1, SBSymbolContextList jarg1_, long jarg2, SBStream jarg2_);
public final static native void SBSymbolContextList_Append__SWIG_0(long jarg1, SBSymbolContextList jarg1_, long jarg2, SBSymbolContext jarg2_);
public final static native void SBSymbolContextList_Append__SWIG_1(long jarg1, SBSymbolContextList jarg1_, long jarg2, SBSymbolContextList jarg2_);
public final static native void SBSymbolContextList_Clear(long jarg1, SBSymbolContextList jarg1_);
public final static native String SBSymbolContextList___repr__(long jarg1, SBSymbolContextList jarg1_);
public final static native int SBTarget_eBroadcastBitBreakpointChanged_get();
public final static native int SBTarget_eBroadcastBitModulesLoaded_get();
public final static native int SBTarget_eBroadcastBitModulesUnloaded_get();
public final static native int SBTarget_eBroadcastBitWatchpointChanged_get();
public final static native int SBTarget_eBroadcastBitSymbolsLoaded_get();
public final static native long new_SBTarget__SWIG_0();
public final static native long new_SBTarget__SWIG_1(long jarg1, SBTarget jarg1_);
public final static native void delete_SBTarget(long jarg1);
public final static native boolean SBTarget_IsValid(long jarg1, SBTarget jarg1_);
public final static native boolean SBTarget_EventIsTargetEvent(long jarg1, SBEvent jarg1_);
public final static native long SBTarget_GetTargetFromEvent(long jarg1, SBEvent jarg1_);
public final static native long SBTarget_GetNumModulesFromEvent(long jarg1, SBEvent jarg1_);
public final static native long SBTarget_GetModuleAtIndexFromEvent(long jarg1, long jarg2, SBEvent jarg2_);
public final static native String SBTarget_GetBroadcasterClassName();
public final static native long SBTarget_GetProcess(long jarg1, SBTarget jarg1_);
public final static native void SBTarget_SetCollectingStats(long jarg1, SBTarget jarg1_, boolean jarg2);
public final static native boolean SBTarget_GetCollectingStats(long jarg1, SBTarget jarg1_);
public final static native long SBTarget_GetStatistics(long jarg1, SBTarget jarg1_);
public final static native long SBTarget_GetPlatform(long jarg1, SBTarget jarg1_);
public final static native long SBTarget_GetEnvironment(long jarg1, SBTarget jarg1_);
public final static native long SBTarget_Install(long jarg1, SBTarget jarg1_);
public final static native long SBTarget_Launch__SWIG_0(long jarg1, SBTarget jarg1_, long jarg2, SBListener jarg2_, String[] jarg3, String[] jarg4, String jarg5, String jarg6, String jarg7, String jarg8, long jarg9, boolean jarg10, long jarg11, SBError jarg11_);
public final static native long SBTarget_LoadCore__SWIG_0(long jarg1, SBTarget jarg1_, String jarg2);
public final static native long SBTarget_LoadCore__SWIG_1(long jarg1, SBTarget jarg1_, String jarg2, long jarg3, SBError jarg3_);
public final static native long SBTarget_LaunchSimple(long jarg1, SBTarget jarg1_, String[] jarg2, String[] jarg3, String jarg4);
public final static native long SBTarget_Launch__SWIG_1(long jarg1, SBTarget jarg1_, long jarg2, SBLaunchInfo jarg2_, long jarg3, SBError jarg3_);
public final static native long SBTarget_Attach(long jarg1, SBTarget jarg1_, long jarg2, SBAttachInfo jarg2_, long jarg3, SBError jarg3_);
public final static native long SBTarget_AttachToProcessWithID(long jarg1, SBTarget jarg1_, long jarg2, SBListener jarg2_, java.math.BigInteger jarg3, long jarg4, SBError jarg4_);
public final static native long SBTarget_AttachToProcessWithName(long jarg1, SBTarget jarg1_, long jarg2, SBListener jarg2_, String jarg3, boolean jarg4, long jarg5, SBError jarg5_);
public final static native long SBTarget_ConnectRemote(long jarg1, SBTarget jarg1_, long jarg2, SBListener jarg2_, String jarg3, String jarg4, long jarg5, SBError jarg5_);
public final static native long SBTarget_GetExecutable(long jarg1, SBTarget jarg1_);
public final static native void SBTarget_AppendImageSearchPath(long jarg1, SBTarget jarg1_, String jarg2, String jarg3, long jarg4, SBError jarg4_);
public final static native boolean SBTarget_AddModule__SWIG_0(long jarg1, SBTarget jarg1_, long jarg2, SBModule jarg2_);
public final static native long SBTarget_AddModule__SWIG_1(long jarg1, SBTarget jarg1_, String jarg2, String jarg3, String jarg4);
public final static native long SBTarget_AddModule__SWIG_2(long jarg1, SBTarget jarg1_, String jarg2, String jarg3, String jarg4, String jarg5);
public final static native long SBTarget_AddModule__SWIG_3(long jarg1, SBTarget jarg1_, long jarg2, SBModuleSpec jarg2_);
public final static native long SBTarget_GetNumModules(long jarg1, SBTarget jarg1_);
public final static native long SBTarget_GetModuleAtIndex(long jarg1, SBTarget jarg1_, long jarg2);
public final static native boolean SBTarget_RemoveModule(long jarg1, SBTarget jarg1_, long jarg2, SBModule jarg2_);
public final static native long SBTarget_GetDebugger(long jarg1, SBTarget jarg1_);
public final static native long SBTarget_FindModule(long jarg1, SBTarget jarg1_, long jarg2, SBFileSpec jarg2_);
public final static native long SBTarget_FindCompileUnits(long jarg1, SBTarget jarg1_, long jarg2, SBFileSpec jarg2_);
public final static native int SBTarget_GetByteOrder(long jarg1, SBTarget jarg1_);
public final static native long SBTarget_GetAddressByteSize(long jarg1, SBTarget jarg1_);
public final static native String SBTarget_GetTriple(long jarg1, SBTarget jarg1_);
public final static native String SBTarget_GetABIName(long jarg1, SBTarget jarg1_);
public final static native String SBTarget_GetLabel(long jarg1, SBTarget jarg1_);
public final static native long SBTarget_SetLabel(long jarg1, SBTarget jarg1_, String jarg2);
public final static native long SBTarget_GetDataByteSize(long jarg1, SBTarget jarg1_);
public final static native long SBTarget_GetCodeByteSize(long jarg1, SBTarget jarg1_);
public final static native long SBTarget_GetMaximumNumberOfChildrenToDisplay(long jarg1, SBTarget jarg1_);
public final static native long SBTarget_SetSectionLoadAddress(long jarg1, SBTarget jarg1_, long jarg2, SBSection jarg2_, java.math.BigInteger jarg3);
public final static native long SBTarget_ClearSectionLoadAddress(long jarg1, SBTarget jarg1_, long jarg2, SBSection jarg2_);
public final static native long SBTarget_SetModuleLoadAddress(long jarg1, SBTarget jarg1_, long jarg2, SBModule jarg2_, java.math.BigInteger jarg3);
public final static native long SBTarget_ClearModuleLoadAddress(long jarg1, SBTarget jarg1_, long jarg2, SBModule jarg2_);
public final static native long SBTarget_FindFunctions__SWIG_0(long jarg1, SBTarget jarg1_, String jarg2, long jarg3);
public final static native long SBTarget_FindFunctions__SWIG_1(long jarg1, SBTarget jarg1_, String jarg2);
public final static native long SBTarget_FindGlobalVariables__SWIG_0(long jarg1, SBTarget jarg1_, String jarg2, long jarg3);
public final static native long SBTarget_FindFirstGlobalVariable(long jarg1, SBTarget jarg1_, String jarg2);
public final static native long SBTarget_FindGlobalVariables__SWIG_1(long jarg1, SBTarget jarg1_, String jarg2, long jarg3, int jarg4);
public final static native long SBTarget_FindGlobalFunctions(long jarg1, SBTarget jarg1_, String jarg2, long jarg3, int jarg4);
public final static native void SBTarget_Clear(long jarg1, SBTarget jarg1_);
public final static native long SBTarget_ResolveFileAddress(long jarg1, SBTarget jarg1_, java.math.BigInteger jarg2);
public final static native long SBTarget_ResolveLoadAddress(long jarg1, SBTarget jarg1_, java.math.BigInteger jarg2);
public final static native long SBTarget_ResolvePastLoadAddress(long jarg1, SBTarget jarg1_, long jarg2, java.math.BigInteger jarg3);
public final static native long SBTarget_ResolveSymbolContextForAddress(long jarg1, SBTarget jarg1_, long jarg2, SBAddress jarg2_, long jarg3);
public final static native long SBTarget_ReadMemory(long jarg1, SBTarget jarg1_, long jarg2, SBAddress jarg2_, long jarg3, long jarg4, long jarg5, SBError jarg5_);
public final static native long SBTarget_BreakpointCreateByLocation__SWIG_0(long jarg1, SBTarget jarg1_, String jarg2, long jarg3);
public final static native long SBTarget_BreakpointCreateByLocation__SWIG_1(long jarg1, SBTarget jarg1_, long jarg2, SBFileSpec jarg2_, long jarg3);
public final static native long SBTarget_BreakpointCreateByLocation__SWIG_2(long jarg1, SBTarget jarg1_, long jarg2, SBFileSpec jarg2_, long jarg3, java.math.BigInteger jarg4);
public final static native long SBTarget_BreakpointCreateByLocation__SWIG_3(long jarg1, SBTarget jarg1_, long jarg2, SBFileSpec jarg2_, long jarg3, java.math.BigInteger jarg4, long jarg5, SBFileSpecList jarg5_);
public final static native long SBTarget_BreakpointCreateByLocation__SWIG_4(long jarg1, SBTarget jarg1_, long jarg2, SBFileSpec jarg2_, long jarg3, long jarg4, java.math.BigInteger jarg5, long jarg6, SBFileSpecList jarg6_);
public final static native long SBTarget_BreakpointCreateByLocation__SWIG_5(long jarg1, SBTarget jarg1_, long jarg2, SBFileSpec jarg2_, long jarg3, long jarg4, java.math.BigInteger jarg5, long jarg6, SBFileSpecList jarg6_, boolean jarg7);
public final static native long SBTarget_BreakpointCreateByName__SWIG_0(long jarg1, SBTarget jarg1_, String jarg2, String jarg3);
public final static native long SBTarget_BreakpointCreateByName__SWIG_1(long jarg1, SBTarget jarg1_, String jarg2);
public final static native long SBTarget_BreakpointCreateByName__SWIG_2(long jarg1, SBTarget jarg1_, String jarg2, long jarg3, SBFileSpecList jarg3_, long jarg4, SBFileSpecList jarg4_);
public final static native long SBTarget_BreakpointCreateByName__SWIG_3(long jarg1, SBTarget jarg1_, String jarg2, long jarg3, long jarg4, SBFileSpecList jarg4_, long jarg5, SBFileSpecList jarg5_);
public final static native long SBTarget_BreakpointCreateByName__SWIG_4(long jarg1, SBTarget jarg1_, String jarg2, long jarg3, int jarg4, long jarg5, SBFileSpecList jarg5_, long jarg6, SBFileSpecList jarg6_);
public final static native long SBTarget_BreakpointCreateByNames__SWIG_0(long jarg1, SBTarget jarg1_, String[] jarg2, long jarg3, long jarg4, long jarg5, SBFileSpecList jarg5_, long jarg6, SBFileSpecList jarg6_);
public final static native long SBTarget_BreakpointCreateByNames__SWIG_1(long jarg1, SBTarget jarg1_, String[] jarg2, long jarg3, long jarg4, int jarg5, long jarg6, SBFileSpecList jarg6_, long jarg7, SBFileSpecList jarg7_);
public final static native long SBTarget_BreakpointCreateByNames__SWIG_2(long jarg1, SBTarget jarg1_, String[] jarg2, long jarg3, long jarg4, int jarg5, java.math.BigInteger jarg6, long jarg7, SBFileSpecList jarg7_, long jarg8, SBFileSpecList jarg8_);
public final static native long SBTarget_BreakpointCreateByRegex__SWIG_0(long jarg1, SBTarget jarg1_, String jarg2, String jarg3);
public final static native long SBTarget_BreakpointCreateByRegex__SWIG_1(long jarg1, SBTarget jarg1_, String jarg2);
public final static native long SBTarget_BreakpointCreateByRegex__SWIG_2(long jarg1, SBTarget jarg1_, String jarg2, long jarg3, SBFileSpecList jarg3_, long jarg4, SBFileSpecList jarg4_);
public final static native long SBTarget_BreakpointCreateByRegex__SWIG_3(long jarg1, SBTarget jarg1_, String jarg2, int jarg3, long jarg4, SBFileSpecList jarg4_, long jarg5, SBFileSpecList jarg5_);
public final static native long SBTarget_BreakpointCreateBySourceRegex__SWIG_0(long jarg1, SBTarget jarg1_, String jarg2, long jarg3, SBFileSpec jarg3_, String jarg4);
public final static native long SBTarget_BreakpointCreateBySourceRegex__SWIG_1(long jarg1, SBTarget jarg1_, String jarg2, long jarg3, SBFileSpec jarg3_);
public final static native long SBTarget_BreakpointCreateBySourceRegex__SWIG_2(long jarg1, SBTarget jarg1_, String jarg2, long jarg3, SBFileSpecList jarg3_, long jarg4, SBFileSpecList jarg4_);
public final static native long SBTarget_BreakpointCreateBySourceRegex__SWIG_3(long jarg1, SBTarget jarg1_, String jarg2, long jarg3, SBFileSpecList jarg3_, long jarg4, SBFileSpecList jarg4_, long jarg5, SBStringList jarg5_);
public final static native long SBTarget_BreakpointCreateForException(long jarg1, SBTarget jarg1_, int jarg2, boolean jarg3, boolean jarg4);
public final static native long SBTarget_BreakpointCreateByAddress(long jarg1, SBTarget jarg1_, java.math.BigInteger jarg2);
public final static native long SBTarget_BreakpointCreateBySBAddress(long jarg1, SBTarget jarg1_, long jarg2, SBAddress jarg2_);
public final static native long SBTarget_BreakpointCreateFromScript__SWIG_0(long jarg1, SBTarget jarg1_, String jarg2, long jarg3, SBStructuredData jarg3_, long jarg4, SBFileSpecList jarg4_, long jarg5, SBFileSpecList jarg5_, boolean jarg6);
public final static native long SBTarget_BreakpointCreateFromScript__SWIG_1(long jarg1, SBTarget jarg1_, String jarg2, long jarg3, SBStructuredData jarg3_, long jarg4, SBFileSpecList jarg4_, long jarg5, SBFileSpecList jarg5_);
public final static native long SBTarget_BreakpointsCreateFromFile__SWIG_0(long jarg1, SBTarget jarg1_, long jarg2, SBFileSpec jarg2_, long jarg3, SBBreakpointList jarg3_);
public final static native long SBTarget_BreakpointsCreateFromFile__SWIG_1(long jarg1, SBTarget jarg1_, long jarg2, SBFileSpec jarg2_, long jarg3, SBStringList jarg3_, long jarg4, SBBreakpointList jarg4_);
public final static native long SBTarget_BreakpointsWriteToFile__SWIG_0(long jarg1, SBTarget jarg1_, long jarg2, SBFileSpec jarg2_);
public final static native long SBTarget_BreakpointsWriteToFile__SWIG_1(long jarg1, SBTarget jarg1_, long jarg2, SBFileSpec jarg2_, long jarg3, SBBreakpointList jarg3_, boolean jarg4);
public final static native long SBTarget_BreakpointsWriteToFile__SWIG_2(long jarg1, SBTarget jarg1_, long jarg2, SBFileSpec jarg2_, long jarg3, SBBreakpointList jarg3_);
public final static native long SBTarget_GetNumBreakpoints(long jarg1, SBTarget jarg1_);
public final static native long SBTarget_GetBreakpointAtIndex(long jarg1, SBTarget jarg1_, long jarg2);
public final static native boolean SBTarget_BreakpointDelete(long jarg1, SBTarget jarg1_, int jarg2);
public final static native long SBTarget_FindBreakpointByID(long jarg1, SBTarget jarg1_, int jarg2);
public final static native boolean SBTarget_FindBreakpointsByName(long jarg1, SBTarget jarg1_, String jarg2, long jarg3, SBBreakpointList jarg3_);
public final static native void SBTarget_GetBreakpointNames(long jarg1, SBTarget jarg1_, long jarg2, SBStringList jarg2_);
public final static native void SBTarget_DeleteBreakpointName(long jarg1, SBTarget jarg1_, String jarg2);
public final static native boolean SBTarget_EnableAllBreakpoints(long jarg1, SBTarget jarg1_);
public final static native boolean SBTarget_DisableAllBreakpoints(long jarg1, SBTarget jarg1_);
public final static native boolean SBTarget_DeleteAllBreakpoints(long jarg1, SBTarget jarg1_);
public final static native long SBTarget_GetNumWatchpoints(long jarg1, SBTarget jarg1_);
public final static native long SBTarget_GetWatchpointAtIndex(long jarg1, SBTarget jarg1_, long jarg2);
public final static native boolean SBTarget_DeleteWatchpoint(long jarg1, SBTarget jarg1_, int jarg2);
public final static native long SBTarget_FindWatchpointByID(long jarg1, SBTarget jarg1_, int jarg2);
public final static native long SBTarget_WatchAddress(long jarg1, SBTarget jarg1_, java.math.BigInteger jarg2, long jarg3, boolean jarg4, boolean jarg5, long jarg6, SBError jarg6_);
public final static native boolean SBTarget_EnableAllWatchpoints(long jarg1, SBTarget jarg1_);
public final static native boolean SBTarget_DisableAllWatchpoints(long jarg1, SBTarget jarg1_);
public final static native boolean SBTarget_DeleteAllWatchpoints(long jarg1, SBTarget jarg1_);
public final static native long SBTarget_GetBroadcaster(long jarg1, SBTarget jarg1_);
public final static native long SBTarget_FindFirstType(long jarg1, SBTarget jarg1_, String jarg2);
public final static native long SBTarget_FindTypes(long jarg1, SBTarget jarg1_, String jarg2);
public final static native long SBTarget_GetBasicType(long jarg1, SBTarget jarg1_, int jarg2);
public final static native long SBTarget_CreateValueFromAddress(long jarg1, SBTarget jarg1_, String jarg2, long jarg3, SBAddress jarg3_, long jarg4, SBType jarg4_);
public final static native long SBTarget_CreateValueFromData(long jarg1, SBTarget jarg1_, String jarg2, long jarg3, SBData jarg3_, long jarg4, SBType jarg4_);
public final static native long SBTarget_CreateValueFromExpression(long jarg1, SBTarget jarg1_, String jarg2, String jarg3);
public final static native long SBTarget_GetSourceManager(long jarg1, SBTarget jarg1_);
public final static native long SBTarget_ReadInstructions__SWIG_0(long jarg1, SBTarget jarg1_, long jarg2, SBAddress jarg2_, long jarg3);
public final static native long SBTarget_ReadInstructions__SWIG_1(long jarg1, SBTarget jarg1_, long jarg2, SBAddress jarg2_, long jarg3, String jarg4);
public final static native long SBTarget_GetInstructions(long jarg1, SBTarget jarg1_, long jarg2, SBAddress jarg2_, long jarg3, long jarg4);
public final static native long SBTarget_GetInstructionsWithFlavor(long jarg1, SBTarget jarg1_, long jarg2, SBAddress jarg2_, String jarg3, long jarg4, long jarg5);
public final static native long SBTarget_FindSymbols__SWIG_0(long jarg1, SBTarget jarg1_, String jarg2, int jarg3);
public final static native long SBTarget_FindSymbols__SWIG_1(long jarg1, SBTarget jarg1_, String jarg2);
public final static native boolean SBTarget_GetDescription(long jarg1, SBTarget jarg1_, long jarg2, SBStream jarg2_, int jarg3);
public final static native long SBTarget_EvaluateExpression__SWIG_0(long jarg1, SBTarget jarg1_, String jarg2);
public final static native long SBTarget_EvaluateExpression__SWIG_1(long jarg1, SBTarget jarg1_, String jarg2, long jarg3, SBExpressionOptions jarg3_);
public final static native java.math.BigInteger SBTarget_GetStackRedZoneSize(long jarg1, SBTarget jarg1_);
public final static native boolean SBTarget_IsLoaded(long jarg1, SBTarget jarg1_, long jarg2, SBModule jarg2_);
public final static native long SBTarget_GetLaunchInfo(long jarg1, SBTarget jarg1_);
public final static native void SBTarget_SetLaunchInfo(long jarg1, SBTarget jarg1_, long jarg2, SBLaunchInfo jarg2_);
public final static native long SBTarget_GetTrace(long jarg1, SBTarget jarg1_);
public final static native long SBTarget_CreateTrace(long jarg1, SBTarget jarg1_, long jarg2, SBError jarg2_);
public final static native String SBTarget___repr__(long jarg1, SBTarget jarg1_);
public final static native int SBThread_eBroadcastBitStackChanged_get();
public final static native int SBThread_eBroadcastBitThreadSuspended_get();
public final static native int SBThread_eBroadcastBitThreadResumed_get();
public final static native int SBThread_eBroadcastBitSelectedFrameChanged_get();
public final static native int SBThread_eBroadcastBitThreadSelected_get();
public final static native String SBThread_GetBroadcasterClassName();
public final static native long new_SBThread__SWIG_0();
public final static native long new_SBThread__SWIG_1(long jarg1, SBThread jarg1_);
public final static native void delete_SBThread(long jarg1);
public final static native long SBThread_GetQueue(long jarg1, SBThread jarg1_);
public final static native boolean SBThread_IsValid(long jarg1, SBThread jarg1_);
public final static native void SBThread_Clear(long jarg1, SBThread jarg1_);
public final static native int SBThread_GetStopReason(long jarg1, SBThread jarg1_);
public final static native long SBThread_GetStopReasonDataCount(long jarg1, SBThread jarg1_);
public final static native java.math.BigInteger SBThread_GetStopReasonDataAtIndex(long jarg1, SBThread jarg1_, long jarg2);
public final static native boolean SBThread_GetStopReasonExtendedInfoAsJSON(long jarg1, SBThread jarg1_, long jarg2, SBStream jarg2_);
public final static native long SBThread_GetStopReasonExtendedBacktraces(long jarg1, SBThread jarg1_, int jarg2);
public final static native long SBThread_GetStopDescription(long jarg1, SBThread jarg1_, String jarg2, long jarg3);
public final static native long SBThread_GetStopReturnValue(long jarg1, SBThread jarg1_);
public final static native java.math.BigInteger SBThread_GetThreadID(long jarg1, SBThread jarg1_);
public final static native long SBThread_GetIndexID(long jarg1, SBThread jarg1_);
public final static native String SBThread_GetName(long jarg1, SBThread jarg1_);
public final static native String SBThread_GetQueueName(long jarg1, SBThread jarg1_);
public final static native java.math.BigInteger SBThread_GetQueueID(long jarg1, SBThread jarg1_);
public final static native boolean SBThread_GetInfoItemByPathAsString(long jarg1, SBThread jarg1_, String jarg2, long jarg3, SBStream jarg3_);
public final static native void SBThread_StepOver__SWIG_0(long jarg1, SBThread jarg1_, int jarg2);
public final static native void SBThread_StepOver__SWIG_1(long jarg1, SBThread jarg1_);
public final static native void SBThread_StepOver__SWIG_2(long jarg1, SBThread jarg1_, int jarg2, long jarg3, SBError jarg3_);
public final static native void SBThread_StepInto__SWIG_0(long jarg1, SBThread jarg1_, int jarg2);
public final static native void SBThread_StepInto__SWIG_1(long jarg1, SBThread jarg1_);
public final static native void SBThread_StepInto__SWIG_2(long jarg1, SBThread jarg1_, String jarg2, int jarg3);
public final static native void SBThread_StepInto__SWIG_3(long jarg1, SBThread jarg1_, String jarg2);
public final static native void SBThread_StepInto__SWIG_4(long jarg1, SBThread jarg1_, String jarg2, long jarg3, long jarg4, SBError jarg4_, int jarg5);
public final static native void SBThread_StepInto__SWIG_5(long jarg1, SBThread jarg1_, String jarg2, long jarg3, long jarg4, SBError jarg4_);
public final static native void SBThread_StepOut__SWIG_0(long jarg1, SBThread jarg1_);
public final static native void SBThread_StepOut__SWIG_1(long jarg1, SBThread jarg1_, long jarg2, SBError jarg2_);
public final static native void SBThread_StepOutOfFrame__SWIG_0(long jarg1, SBThread jarg1_, long jarg2, SBFrame jarg2_);
public final static native void SBThread_StepOutOfFrame__SWIG_1(long jarg1, SBThread jarg1_, long jarg2, SBFrame jarg2_, long jarg3, SBError jarg3_);
public final static native void SBThread_StepInstruction__SWIG_0(long jarg1, SBThread jarg1_, boolean jarg2);
public final static native void SBThread_StepInstruction__SWIG_1(long jarg1, SBThread jarg1_, boolean jarg2, long jarg3, SBError jarg3_);
public final static native long SBThread_StepOverUntil(long jarg1, SBThread jarg1_, long jarg2, SBFrame jarg2_, long jarg3, SBFileSpec jarg3_, long jarg4);
public final static native long SBThread_StepUsingScriptedThreadPlan__SWIG_0(long jarg1, SBThread jarg1_, String jarg2);
public final static native long SBThread_StepUsingScriptedThreadPlan__SWIG_1(long jarg1, SBThread jarg1_, String jarg2, boolean jarg3);
public final static native long SBThread_StepUsingScriptedThreadPlan__SWIG_2(long jarg1, SBThread jarg1_, String jarg2, long jarg3, SBStructuredData jarg3_, boolean jarg4);
public final static native long SBThread_JumpToLine(long jarg1, SBThread jarg1_, long jarg2, SBFileSpec jarg2_, long jarg3);
public final static native void SBThread_RunToAddress__SWIG_0(long jarg1, SBThread jarg1_, java.math.BigInteger jarg2);
public final static native void SBThread_RunToAddress__SWIG_1(long jarg1, SBThread jarg1_, java.math.BigInteger jarg2, long jarg3, SBError jarg3_);
public final static native long SBThread_ReturnFromFrame(long jarg1, SBThread jarg1_, long jarg2, SBFrame jarg2_, long jarg3, SBValue jarg3_);
public final static native long SBThread_UnwindInnermostExpression(long jarg1, SBThread jarg1_);
public final static native boolean SBThread_Suspend__SWIG_0(long jarg1, SBThread jarg1_);
public final static native boolean SBThread_Suspend__SWIG_1(long jarg1, SBThread jarg1_, long jarg2, SBError jarg2_);
public final static native boolean SBThread_Resume__SWIG_0(long jarg1, SBThread jarg1_);
public final static native boolean SBThread_Resume__SWIG_1(long jarg1, SBThread jarg1_, long jarg2, SBError jarg2_);
public final static native boolean SBThread_IsSuspended(long jarg1, SBThread jarg1_);
public final static native boolean SBThread_IsStopped(long jarg1, SBThread jarg1_);
public final static native long SBThread_GetNumFrames(long jarg1, SBThread jarg1_);
public final static native long SBThread_GetFrameAtIndex(long jarg1, SBThread jarg1_, long jarg2);
public final static native long SBThread_GetSelectedFrame(long jarg1, SBThread jarg1_);
public final static native long SBThread_SetSelectedFrame(long jarg1, SBThread jarg1_, long jarg2);
public final static native boolean SBThread_EventIsThreadEvent(long jarg1, SBEvent jarg1_);
public final static native long SBThread_GetStackFrameFromEvent(long jarg1, SBEvent jarg1_);
public final static native long SBThread_GetThreadFromEvent(long jarg1, SBEvent jarg1_);
public final static native long SBThread_GetProcess(long jarg1, SBThread jarg1_);
public final static native boolean SBThread_GetDescription__SWIG_0(long jarg1, SBThread jarg1_, long jarg2, SBStream jarg2_);
public final static native boolean SBThread_GetDescription__SWIG_1(long jarg1, SBThread jarg1_, long jarg2, SBStream jarg2_, boolean jarg3);
public final static native boolean SBThread_GetStatus(long jarg1, SBThread jarg1_, long jarg2, SBStream jarg2_);
public final static native long SBThread_GetExtendedBacktraceThread(long jarg1, SBThread jarg1_, String jarg2);
public final static native long SBThread_GetExtendedBacktraceOriginatingIndexID(long jarg1, SBThread jarg1_);
public final static native long SBThread_GetCurrentException(long jarg1, SBThread jarg1_);
public final static native long SBThread_GetCurrentExceptionBacktrace(long jarg1, SBThread jarg1_);
public final static native boolean SBThread_SafeToCallFunctions(long jarg1, SBThread jarg1_);
public final static native long SBThread_GetSiginfo(long jarg1, SBThread jarg1_);
public final static native String SBThread___repr__(long jarg1, SBThread jarg1_);
public final static native long new_SBThreadCollection__SWIG_0();
public final static native long new_SBThreadCollection__SWIG_1(long jarg1, SBThreadCollection jarg1_);
public final static native void delete_SBThreadCollection(long jarg1);
public final static native boolean SBThreadCollection_IsValid(long jarg1, SBThreadCollection jarg1_);
public final static native long SBThreadCollection_GetSize(long jarg1, SBThreadCollection jarg1_);
public final static native long SBThreadCollection_GetThreadAtIndex(long jarg1, SBThreadCollection jarg1_, long jarg2);
public final static native long new_SBThreadPlan__SWIG_0();
public final static native long new_SBThreadPlan__SWIG_1(long jarg1, SBThreadPlan jarg1_);
public final static native long new_SBThreadPlan__SWIG_2(long jarg1, SBThread jarg1_, String jarg2);
public final static native long new_SBThreadPlan__SWIG_3(long jarg1, SBThread jarg1_, String jarg2, long jarg3, SBStructuredData jarg3_);
public final static native void delete_SBThreadPlan(long jarg1);
public final static native boolean SBThreadPlan_IsValid__SWIG_0(long jarg1, SBThreadPlan jarg1_);
public final static native void SBThreadPlan_Clear(long jarg1, SBThreadPlan jarg1_);
public final static native int SBThreadPlan_GetStopReason(long jarg1, SBThreadPlan jarg1_);
public final static native long SBThreadPlan_GetStopReasonDataCount(long jarg1, SBThreadPlan jarg1_);
public final static native java.math.BigInteger SBThreadPlan_GetStopReasonDataAtIndex(long jarg1, SBThreadPlan jarg1_, long jarg2);
public final static native long SBThreadPlan_GetThread(long jarg1, SBThreadPlan jarg1_);
public final static native boolean SBThreadPlan_GetDescription(long jarg1, SBThreadPlan jarg1_, long jarg2, SBStream jarg2_);
public final static native void SBThreadPlan_SetPlanComplete(long jarg1, SBThreadPlan jarg1_, boolean jarg2);
public final static native boolean SBThreadPlan_IsPlanComplete(long jarg1, SBThreadPlan jarg1_);
public final static native boolean SBThreadPlan_IsPlanStale(long jarg1, SBThreadPlan jarg1_);
public final static native boolean SBThreadPlan_GetStopOthers(long jarg1, SBThreadPlan jarg1_);
public final static native void SBThreadPlan_SetStopOthers(long jarg1, SBThreadPlan jarg1_, boolean jarg2);
public final static native long SBThreadPlan_QueueThreadPlanForStepOverRange__SWIG_0(long jarg1, SBThreadPlan jarg1_, long jarg2, SBAddress jarg2_, java.math.BigInteger jarg3);
public final static native long SBThreadPlan_QueueThreadPlanForStepOverRange__SWIG_1(long jarg1, SBThreadPlan jarg1_, long jarg2, SBAddress jarg2_, java.math.BigInteger jarg3, long jarg4, SBError jarg4_);
public final static native long SBThreadPlan_QueueThreadPlanForStepInRange__SWIG_0(long jarg1, SBThreadPlan jarg1_, long jarg2, SBAddress jarg2_, java.math.BigInteger jarg3);
public final static native long SBThreadPlan_QueueThreadPlanForStepInRange__SWIG_1(long jarg1, SBThreadPlan jarg1_, long jarg2, SBAddress jarg2_, java.math.BigInteger jarg3, long jarg4, SBError jarg4_);
public final static native long SBThreadPlan_QueueThreadPlanForStepOut__SWIG_0(long jarg1, SBThreadPlan jarg1_, long jarg2, boolean jarg3);
public final static native long SBThreadPlan_QueueThreadPlanForStepOut__SWIG_1(long jarg1, SBThreadPlan jarg1_, long jarg2);
public final static native long SBThreadPlan_QueueThreadPlanForStepOut__SWIG_2(long jarg1, SBThreadPlan jarg1_, long jarg2, boolean jarg3, long jarg4, SBError jarg4_);
public final static native long SBThreadPlan_QueueThreadPlanForRunToAddress__SWIG_0(long jarg1, SBThreadPlan jarg1_, long jarg2, SBAddress jarg2_);
public final static native long SBThreadPlan_QueueThreadPlanForRunToAddress__SWIG_1(long jarg1, SBThreadPlan jarg1_, long jarg2, SBAddress jarg2_, long jarg3, SBError jarg3_);
public final static native long SBThreadPlan_QueueThreadPlanForStepScripted__SWIG_0(long jarg1, SBThreadPlan jarg1_, String jarg2);
public final static native long SBThreadPlan_QueueThreadPlanForStepScripted__SWIG_1(long jarg1, SBThreadPlan jarg1_, String jarg2, long jarg3, SBError jarg3_);
public final static native long SBThreadPlan_QueueThreadPlanForStepScripted__SWIG_2(long jarg1, SBThreadPlan jarg1_, String jarg2, long jarg3, SBStructuredData jarg3_, long jarg4, SBError jarg4_);
public final static native long new_SBTrace();
public final static native long SBTrace_LoadTraceFromFile(long jarg1, SBError jarg1_, long jarg2, SBDebugger jarg2_, long jarg3, SBFileSpec jarg3_);
public final static native long SBTrace_CreateNewCursor(long jarg1, SBTrace jarg1_, long jarg2, SBError jarg2_, long jarg3, SBThread jarg3_);
public final static native long SBTrace_SaveToDisk__SWIG_0(long jarg1, SBTrace jarg1_, long jarg2, SBError jarg2_, long jarg3, SBFileSpec jarg3_, boolean jarg4);
public final static native long SBTrace_SaveToDisk__SWIG_1(long jarg1, SBTrace jarg1_, long jarg2, SBError jarg2_, long jarg3, SBFileSpec jarg3_);
public final static native String SBTrace_GetStartConfigurationHelp(long jarg1, SBTrace jarg1_);
public final static native long SBTrace_Start__SWIG_0(long jarg1, SBTrace jarg1_, long jarg2, SBStructuredData jarg2_);
public final static native long SBTrace_Start__SWIG_1(long jarg1, SBTrace jarg1_, long jarg2, SBThread jarg2_, long jarg3, SBStructuredData jarg3_);
public final static native long SBTrace_Stop__SWIG_0(long jarg1, SBTrace jarg1_);
public final static native long SBTrace_Stop__SWIG_1(long jarg1, SBTrace jarg1_, long jarg2, SBThread jarg2_);
public final static native boolean SBTrace_IsValid(long jarg1, SBTrace jarg1_);
public final static native void delete_SBTrace(long jarg1);
public final static native long new_SBTraceCursor();
public final static native void SBTraceCursor_SetForwards(long jarg1, SBTraceCursor jarg1_, boolean jarg2);
public final static native boolean SBTraceCursor_IsForwards(long jarg1, SBTraceCursor jarg1_);
public final static native void SBTraceCursor_Next(long jarg1, SBTraceCursor jarg1_);
public final static native boolean SBTraceCursor_HasValue(long jarg1, SBTraceCursor jarg1_);
public final static native boolean SBTraceCursor_GoToId(long jarg1, SBTraceCursor jarg1_, java.math.BigInteger jarg2);
public final static native boolean SBTraceCursor_HasId(long jarg1, SBTraceCursor jarg1_, java.math.BigInteger jarg2);
public final static native java.math.BigInteger SBTraceCursor_GetId(long jarg1, SBTraceCursor jarg1_);
public final static native boolean SBTraceCursor_Seek(long jarg1, SBTraceCursor jarg1_, long jarg2, int jarg3);
public final static native int SBTraceCursor_GetItemKind(long jarg1, SBTraceCursor jarg1_);
public final static native boolean SBTraceCursor_IsError(long jarg1, SBTraceCursor jarg1_);
public final static native String SBTraceCursor_GetError(long jarg1, SBTraceCursor jarg1_);
public final static native boolean SBTraceCursor_IsEvent(long jarg1, SBTraceCursor jarg1_);
public final static native int SBTraceCursor_GetEventType(long jarg1, SBTraceCursor jarg1_);
public final static native String SBTraceCursor_GetEventTypeAsString(long jarg1, SBTraceCursor jarg1_);
public final static native boolean SBTraceCursor_IsInstruction(long jarg1, SBTraceCursor jarg1_);
public final static native java.math.BigInteger SBTraceCursor_GetLoadAddress(long jarg1, SBTraceCursor jarg1_);
public final static native long SBTraceCursor_GetCPU(long jarg1, SBTraceCursor jarg1_);
public final static native boolean SBTraceCursor_IsValid(long jarg1, SBTraceCursor jarg1_);
public final static native void delete_SBTraceCursor(long jarg1);
public final static native long new_SBTypeMember__SWIG_0();
public final static native long new_SBTypeMember__SWIG_1(long jarg1, SBTypeMember jarg1_);
public final static native void delete_SBTypeMember(long jarg1);
public final static native boolean SBTypeMember_IsValid(long jarg1, SBTypeMember jarg1_);
public final static native String SBTypeMember_GetName(long jarg1, SBTypeMember jarg1_);
public final static native long SBTypeMember_GetType(long jarg1, SBTypeMember jarg1_);
public final static native java.math.BigInteger SBTypeMember_GetOffsetInBytes(long jarg1, SBTypeMember jarg1_);
public final static native java.math.BigInteger SBTypeMember_GetOffsetInBits(long jarg1, SBTypeMember jarg1_);
public final static native boolean SBTypeMember_IsBitfield(long jarg1, SBTypeMember jarg1_);
public final static native long SBTypeMember_GetBitfieldSizeInBits(long jarg1, SBTypeMember jarg1_);
public final static native boolean SBTypeMember_GetDescription(long jarg1, SBTypeMember jarg1_, long jarg2, SBStream jarg2_, int jarg3);
public final static native String SBTypeMember___repr__(long jarg1, SBTypeMember jarg1_);
public final static native long new_SBTypeMemberFunction__SWIG_0();
public final static native long new_SBTypeMemberFunction__SWIG_1(long jarg1, SBTypeMemberFunction jarg1_);
public final static native void delete_SBTypeMemberFunction(long jarg1);
public final static native boolean SBTypeMemberFunction_IsValid(long jarg1, SBTypeMemberFunction jarg1_);
public final static native String SBTypeMemberFunction_GetName(long jarg1, SBTypeMemberFunction jarg1_);
public final static native String SBTypeMemberFunction_GetDemangledName(long jarg1, SBTypeMemberFunction jarg1_);
public final static native String SBTypeMemberFunction_GetMangledName(long jarg1, SBTypeMemberFunction jarg1_);
public final static native long SBTypeMemberFunction_GetType(long jarg1, SBTypeMemberFunction jarg1_);
public final static native long SBTypeMemberFunction_GetReturnType(long jarg1, SBTypeMemberFunction jarg1_);
public final static native long SBTypeMemberFunction_GetNumberOfArguments(long jarg1, SBTypeMemberFunction jarg1_);
public final static native long SBTypeMemberFunction_GetArgumentTypeAtIndex(long jarg1, SBTypeMemberFunction jarg1_, long jarg2);
public final static native int SBTypeMemberFunction_GetKind(long jarg1, SBTypeMemberFunction jarg1_);
public final static native boolean SBTypeMemberFunction_GetDescription(long jarg1, SBTypeMemberFunction jarg1_, long jarg2, SBStream jarg2_, int jarg3);
public final static native String SBTypeMemberFunction___repr__(long jarg1, SBTypeMemberFunction jarg1_);
public final static native long new_SBType__SWIG_0();
public final static native long new_SBType__SWIG_1(long jarg1, SBType jarg1_);
public final static native void delete_SBType(long jarg1);
public final static native boolean SBType_IsValid(long jarg1, SBType jarg1_);
public final static native java.math.BigInteger SBType_GetByteSize(long jarg1, SBType jarg1_);
public final static native boolean SBType_IsPointerType(long jarg1, SBType jarg1_);
public final static native boolean SBType_IsReferenceType(long jarg1, SBType jarg1_);
public final static native boolean SBType_IsFunctionType(long jarg1, SBType jarg1_);
public final static native boolean SBType_IsPolymorphicClass(long jarg1, SBType jarg1_);
public final static native boolean SBType_IsArrayType(long jarg1, SBType jarg1_);
public final static native boolean SBType_IsVectorType(long jarg1, SBType jarg1_);
public final static native boolean SBType_IsTypedefType(long jarg1, SBType jarg1_);
public final static native boolean SBType_IsAnonymousType(long jarg1, SBType jarg1_);
public final static native boolean SBType_IsScopedEnumerationType(long jarg1, SBType jarg1_);
public final static native boolean SBType_IsAggregateType(long jarg1, SBType jarg1_);
public final static native long SBType_GetPointerType(long jarg1, SBType jarg1_);
public final static native long SBType_GetPointeeType(long jarg1, SBType jarg1_);
public final static native long SBType_GetReferenceType(long jarg1, SBType jarg1_);
public final static native long SBType_GetTypedefedType(long jarg1, SBType jarg1_);
public final static native long SBType_GetDereferencedType(long jarg1, SBType jarg1_);
public final static native long SBType_GetUnqualifiedType(long jarg1, SBType jarg1_);
public final static native long SBType_GetArrayElementType(long jarg1, SBType jarg1_);
public final static native long SBType_GetArrayType(long jarg1, SBType jarg1_, java.math.BigInteger jarg2);
public final static native long SBType_GetVectorElementType(long jarg1, SBType jarg1_);
public final static native long SBType_GetCanonicalType(long jarg1, SBType jarg1_);
public final static native long SBType_GetEnumerationIntegerType(long jarg1, SBType jarg1_);
public final static native int SBType_GetBasicType__SWIG_0(long jarg1, SBType jarg1_);
public final static native long SBType_GetBasicType__SWIG_1(long jarg1, SBType jarg1_, int jarg2);
public final static native long SBType_GetNumberOfFields(long jarg1, SBType jarg1_);
public final static native long SBType_GetNumberOfDirectBaseClasses(long jarg1, SBType jarg1_);
public final static native long SBType_GetNumberOfVirtualBaseClasses(long jarg1, SBType jarg1_);
public final static native long SBType_GetFieldAtIndex(long jarg1, SBType jarg1_, long jarg2);
public final static native long SBType_GetDirectBaseClassAtIndex(long jarg1, SBType jarg1_, long jarg2);
public final static native long SBType_GetVirtualBaseClassAtIndex(long jarg1, SBType jarg1_, long jarg2);
public final static native long SBType_GetEnumMembers(long jarg1, SBType jarg1_);
public final static native long SBType_GetNumberOfTemplateArguments(long jarg1, SBType jarg1_);
public final static native long SBType_GetTemplateArgumentType(long jarg1, SBType jarg1_, long jarg2);
public final static native int SBType_GetTemplateArgumentKind(long jarg1, SBType jarg1_, long jarg2);
public final static native long SBType_GetFunctionReturnType(long jarg1, SBType jarg1_);
public final static native long SBType_GetFunctionArgumentTypes(long jarg1, SBType jarg1_);
public final static native long SBType_GetNumberOfMemberFunctions(long jarg1, SBType jarg1_);
public final static native long SBType_GetMemberFunctionAtIndex(long jarg1, SBType jarg1_, long jarg2);
public final static native long SBType_GetModule(long jarg1, SBType jarg1_);
public final static native String SBType_GetName(long jarg1, SBType jarg1_);
public final static native String SBType_GetDisplayTypeName(long jarg1, SBType jarg1_);
public final static native int SBType_GetTypeClass(long jarg1, SBType jarg1_);
public final static native boolean SBType_IsTypeComplete(long jarg1, SBType jarg1_);
public final static native long SBType_GetTypeFlags(long jarg1, SBType jarg1_);
public final static native boolean SBType_GetDescription(long jarg1, SBType jarg1_, long jarg2, SBStream jarg2_, int jarg3);
public final static native String SBType___repr__(long jarg1, SBType jarg1_);
public final static native long new_SBTypeList__SWIG_0();
public final static native long new_SBTypeList__SWIG_1(long jarg1, SBTypeList jarg1_);
public final static native void delete_SBTypeList(long jarg1);
public final static native boolean SBTypeList_IsValid(long jarg1, SBTypeList jarg1_);
public final static native void SBTypeList_Append(long jarg1, SBTypeList jarg1_, long jarg2, SBType jarg2_);
public final static native long SBTypeList_GetTypeAtIndex(long jarg1, SBTypeList jarg1_, long jarg2);
public final static native long SBTypeList_GetSize(long jarg1, SBTypeList jarg1_);
public final static native long new_SBTypeCategory__SWIG_0();
public final static native long new_SBTypeCategory__SWIG_1(long jarg1, SBTypeCategory jarg1_);
public final static native void delete_SBTypeCategory(long jarg1);
public final static native boolean SBTypeCategory_IsValid(long jarg1, SBTypeCategory jarg1_);
public final static native boolean SBTypeCategory_GetEnabled(long jarg1, SBTypeCategory jarg1_);
public final static native void SBTypeCategory_SetEnabled(long jarg1, SBTypeCategory jarg1_, boolean jarg2);
public final static native String SBTypeCategory_GetName(long jarg1, SBTypeCategory jarg1_);
public final static native int SBTypeCategory_GetLanguageAtIndex(long jarg1, SBTypeCategory jarg1_, long jarg2);
public final static native long SBTypeCategory_GetNumLanguages(long jarg1, SBTypeCategory jarg1_);
public final static native void SBTypeCategory_AddLanguage(long jarg1, SBTypeCategory jarg1_, int jarg2);
public final static native boolean SBTypeCategory_GetDescription(long jarg1, SBTypeCategory jarg1_, long jarg2, SBStream jarg2_, int jarg3);
public final static native long SBTypeCategory_GetNumFormats(long jarg1, SBTypeCategory jarg1_);
public final static native long SBTypeCategory_GetNumSummaries(long jarg1, SBTypeCategory jarg1_);
public final static native long SBTypeCategory_GetNumFilters(long jarg1, SBTypeCategory jarg1_);
public final static native long SBTypeCategory_GetNumSynthetics(long jarg1, SBTypeCategory jarg1_);
public final static native long SBTypeCategory_GetTypeNameSpecifierForFilterAtIndex(long jarg1, SBTypeCategory jarg1_, long jarg2);
public final static native long SBTypeCategory_GetTypeNameSpecifierForFormatAtIndex(long jarg1, SBTypeCategory jarg1_, long jarg2);
public final static native long SBTypeCategory_GetTypeNameSpecifierForSummaryAtIndex(long jarg1, SBTypeCategory jarg1_, long jarg2);
public final static native long SBTypeCategory_GetTypeNameSpecifierForSyntheticAtIndex(long jarg1, SBTypeCategory jarg1_, long jarg2);
public final static native long SBTypeCategory_GetFilterForType(long jarg1, SBTypeCategory jarg1_, long jarg2, SBTypeNameSpecifier jarg2_);
public final static native long SBTypeCategory_GetFormatForType(long jarg1, SBTypeCategory jarg1_, long jarg2, SBTypeNameSpecifier jarg2_);
public final static native long SBTypeCategory_GetSummaryForType(long jarg1, SBTypeCategory jarg1_, long jarg2, SBTypeNameSpecifier jarg2_);
public final static native long SBTypeCategory_GetSyntheticForType(long jarg1, SBTypeCategory jarg1_, long jarg2, SBTypeNameSpecifier jarg2_);
public final static native long SBTypeCategory_GetFilterAtIndex(long jarg1, SBTypeCategory jarg1_, long jarg2);
public final static native long SBTypeCategory_GetFormatAtIndex(long jarg1, SBTypeCategory jarg1_, long jarg2);
public final static native long SBTypeCategory_GetSummaryAtIndex(long jarg1, SBTypeCategory jarg1_, long jarg2);
public final static native long SBTypeCategory_GetSyntheticAtIndex(long jarg1, SBTypeCategory jarg1_, long jarg2);
public final static native boolean SBTypeCategory_AddTypeFormat(long jarg1, SBTypeCategory jarg1_, long jarg2, SBTypeNameSpecifier jarg2_, long jarg3, SBTypeFormat jarg3_);
public final static native boolean SBTypeCategory_DeleteTypeFormat(long jarg1, SBTypeCategory jarg1_, long jarg2, SBTypeNameSpecifier jarg2_);
public final static native boolean SBTypeCategory_AddTypeSummary(long jarg1, SBTypeCategory jarg1_, long jarg2, SBTypeNameSpecifier jarg2_, long jarg3, SBTypeSummary jarg3_);
public final static native boolean SBTypeCategory_DeleteTypeSummary(long jarg1, SBTypeCategory jarg1_, long jarg2, SBTypeNameSpecifier jarg2_);
public final static native boolean SBTypeCategory_AddTypeFilter(long jarg1, SBTypeCategory jarg1_, long jarg2, SBTypeNameSpecifier jarg2_, long jarg3, SBTypeFilter jarg3_);
public final static native boolean SBTypeCategory_DeleteTypeFilter(long jarg1, SBTypeCategory jarg1_, long jarg2, SBTypeNameSpecifier jarg2_);
public final static native boolean SBTypeCategory_AddTypeSynthetic(long jarg1, SBTypeCategory jarg1_, long jarg2, SBTypeNameSpecifier jarg2_, long jarg3, SBTypeSynthetic jarg3_);
public final static native boolean SBTypeCategory_DeleteTypeSynthetic(long jarg1, SBTypeCategory jarg1_, long jarg2, SBTypeNameSpecifier jarg2_);
public final static native String SBTypeCategory___repr__(long jarg1, SBTypeCategory jarg1_);
public final static native long new_SBTypeEnumMember__SWIG_0();
public final static native long new_SBTypeEnumMember__SWIG_1(long jarg1, SBTypeEnumMember jarg1_);
public final static native void delete_SBTypeEnumMember(long jarg1);
public final static native boolean SBTypeEnumMember_IsValid(long jarg1, SBTypeEnumMember jarg1_);
public final static native long SBTypeEnumMember_GetValueAsSigned(long jarg1, SBTypeEnumMember jarg1_);
public final static native java.math.BigInteger SBTypeEnumMember_GetValueAsUnsigned(long jarg1, SBTypeEnumMember jarg1_);
public final static native String SBTypeEnumMember_GetName(long jarg1, SBTypeEnumMember jarg1_);
public final static native long SBTypeEnumMember_GetType(long jarg1, SBTypeEnumMember jarg1_);
public final static native boolean SBTypeEnumMember_GetDescription(long jarg1, SBTypeEnumMember jarg1_, long jarg2, SBStream jarg2_, int jarg3);
public final static native String SBTypeEnumMember___repr__(long jarg1, SBTypeEnumMember jarg1_);
public final static native long new_SBTypeEnumMemberList__SWIG_0();
public final static native long new_SBTypeEnumMemberList__SWIG_1(long jarg1, SBTypeEnumMemberList jarg1_);
public final static native void delete_SBTypeEnumMemberList(long jarg1);
public final static native boolean SBTypeEnumMemberList_IsValid(long jarg1, SBTypeEnumMemberList jarg1_);
public final static native void SBTypeEnumMemberList_Append(long jarg1, SBTypeEnumMemberList jarg1_, long jarg2, SBTypeEnumMember jarg2_);
public final static native long SBTypeEnumMemberList_GetTypeEnumMemberAtIndex(long jarg1, SBTypeEnumMemberList jarg1_, long jarg2);
public final static native long SBTypeEnumMemberList_GetSize(long jarg1, SBTypeEnumMemberList jarg1_);
public final static native long new_SBTypeFilter__SWIG_0();
public final static native long new_SBTypeFilter__SWIG_1(long jarg1);
public final static native long new_SBTypeFilter__SWIG_2(long jarg1, SBTypeFilter jarg1_);
public final static native void delete_SBTypeFilter(long jarg1);
public final static native boolean SBTypeFilter_IsValid(long jarg1, SBTypeFilter jarg1_);
public final static native long SBTypeFilter_GetNumberOfExpressionPaths(long jarg1, SBTypeFilter jarg1_);
public final static native String SBTypeFilter_GetExpressionPathAtIndex(long jarg1, SBTypeFilter jarg1_, long jarg2);
public final static native boolean SBTypeFilter_ReplaceExpressionPathAtIndex(long jarg1, SBTypeFilter jarg1_, long jarg2, String jarg3);
public final static native void SBTypeFilter_AppendExpressionPath(long jarg1, SBTypeFilter jarg1_, String jarg2);
public final static native void SBTypeFilter_Clear(long jarg1, SBTypeFilter jarg1_);
public final static native long SBTypeFilter_GetOptions(long jarg1, SBTypeFilter jarg1_);
public final static native void SBTypeFilter_SetOptions(long jarg1, SBTypeFilter jarg1_, long jarg2);
public final static native boolean SBTypeFilter_GetDescription(long jarg1, SBTypeFilter jarg1_, long jarg2, SBStream jarg2_, int jarg3);
public final static native boolean SBTypeFilter_IsEqualTo(long jarg1, SBTypeFilter jarg1_, long jarg2, SBTypeFilter jarg2_);
public final static native String SBTypeFilter___repr__(long jarg1, SBTypeFilter jarg1_);
public final static native long new_SBTypeFormat__SWIG_0();
public final static native long new_SBTypeFormat__SWIG_1(int jarg1, long jarg2);
public final static native long new_SBTypeFormat__SWIG_2(int jarg1);
public final static native long new_SBTypeFormat__SWIG_3(String jarg1, long jarg2);
public final static native long new_SBTypeFormat__SWIG_4(String jarg1);
public final static native long new_SBTypeFormat__SWIG_5(long jarg1, SBTypeFormat jarg1_);
public final static native void delete_SBTypeFormat(long jarg1);
public final static native boolean SBTypeFormat_IsValid(long jarg1, SBTypeFormat jarg1_);
public final static native int SBTypeFormat_GetFormat(long jarg1, SBTypeFormat jarg1_);
public final static native String SBTypeFormat_GetTypeName(long jarg1, SBTypeFormat jarg1_);
public final static native long SBTypeFormat_GetOptions(long jarg1, SBTypeFormat jarg1_);
public final static native void SBTypeFormat_SetFormat(long jarg1, SBTypeFormat jarg1_, int jarg2);
public final static native void SBTypeFormat_SetTypeName(long jarg1, SBTypeFormat jarg1_, String jarg2);
public final static native void SBTypeFormat_SetOptions(long jarg1, SBTypeFormat jarg1_, long jarg2);
public final static native boolean SBTypeFormat_GetDescription(long jarg1, SBTypeFormat jarg1_, long jarg2, SBStream jarg2_, int jarg3);
public final static native boolean SBTypeFormat_IsEqualTo(long jarg1, SBTypeFormat jarg1_, long jarg2, SBTypeFormat jarg2_);
public final static native String SBTypeFormat___repr__(long jarg1, SBTypeFormat jarg1_);
public final static native long new_SBTypeNameSpecifier__SWIG_0();
public final static native long new_SBTypeNameSpecifier__SWIG_1(String jarg1, boolean jarg2);
public final static native long new_SBTypeNameSpecifier__SWIG_2(String jarg1);
public final static native long new_SBTypeNameSpecifier__SWIG_3(String jarg1, int jarg2);
public final static native long new_SBTypeNameSpecifier__SWIG_4(long jarg1, SBType jarg1_);
public final static native long new_SBTypeNameSpecifier__SWIG_5(long jarg1, SBTypeNameSpecifier jarg1_);
public final static native void delete_SBTypeNameSpecifier(long jarg1);
public final static native boolean SBTypeNameSpecifier_IsValid(long jarg1, SBTypeNameSpecifier jarg1_);
public final static native String SBTypeNameSpecifier_GetName(long jarg1, SBTypeNameSpecifier jarg1_);
public final static native long SBTypeNameSpecifier_GetType(long jarg1, SBTypeNameSpecifier jarg1_);
public final static native int SBTypeNameSpecifier_GetMatchType(long jarg1, SBTypeNameSpecifier jarg1_);
public final static native boolean SBTypeNameSpecifier_IsRegex(long jarg1, SBTypeNameSpecifier jarg1_);
public final static native boolean SBTypeNameSpecifier_GetDescription(long jarg1, SBTypeNameSpecifier jarg1_, long jarg2, SBStream jarg2_, int jarg3);
public final static native boolean SBTypeNameSpecifier_IsEqualTo(long jarg1, SBTypeNameSpecifier jarg1_, long jarg2, SBTypeNameSpecifier jarg2_);
public final static native String SBTypeNameSpecifier___repr__(long jarg1, SBTypeNameSpecifier jarg1_);
public final static native long new_SBTypeSummaryOptions__SWIG_0();
public final static native long new_SBTypeSummaryOptions__SWIG_1(long jarg1, SBTypeSummaryOptions jarg1_);
public final static native void delete_SBTypeSummaryOptions(long jarg1);
public final static native boolean SBTypeSummaryOptions_IsValid(long jarg1, SBTypeSummaryOptions jarg1_);
public final static native int SBTypeSummaryOptions_GetLanguage(long jarg1, SBTypeSummaryOptions jarg1_);
public final static native int SBTypeSummaryOptions_GetCapping(long jarg1, SBTypeSummaryOptions jarg1_);
public final static native void SBTypeSummaryOptions_SetLanguage(long jarg1, SBTypeSummaryOptions jarg1_, int jarg2);
public final static native void SBTypeSummaryOptions_SetCapping(long jarg1, SBTypeSummaryOptions jarg1_, int jarg2);
public final static native long new_SBTypeSummary__SWIG_0();
public final static native long SBTypeSummary_CreateWithSummaryString__SWIG_0(String jarg1, long jarg2);
public final static native long SBTypeSummary_CreateWithSummaryString__SWIG_1(String jarg1);
public final static native long SBTypeSummary_CreateWithFunctionName__SWIG_0(String jarg1, long jarg2);
public final static native long SBTypeSummary_CreateWithFunctionName__SWIG_1(String jarg1);
public final static native long SBTypeSummary_CreateWithScriptCode__SWIG_0(String jarg1, long jarg2);
public final static native long SBTypeSummary_CreateWithScriptCode__SWIG_1(String jarg1);
public final static native long new_SBTypeSummary__SWIG_1(long jarg1, SBTypeSummary jarg1_);
public final static native void delete_SBTypeSummary(long jarg1);
public final static native boolean SBTypeSummary_IsValid(long jarg1, SBTypeSummary jarg1_);
public final static native boolean SBTypeSummary_IsFunctionCode(long jarg1, SBTypeSummary jarg1_);
public final static native boolean SBTypeSummary_IsFunctionName(long jarg1, SBTypeSummary jarg1_);
public final static native boolean SBTypeSummary_IsSummaryString(long jarg1, SBTypeSummary jarg1_);
public final static native String SBTypeSummary_GetData(long jarg1, SBTypeSummary jarg1_);
public final static native void SBTypeSummary_SetSummaryString(long jarg1, SBTypeSummary jarg1_, String jarg2);
public final static native void SBTypeSummary_SetFunctionName(long jarg1, SBTypeSummary jarg1_, String jarg2);
public final static native void SBTypeSummary_SetFunctionCode(long jarg1, SBTypeSummary jarg1_, String jarg2);
public final static native long SBTypeSummary_GetOptions(long jarg1, SBTypeSummary jarg1_);
public final static native void SBTypeSummary_SetOptions(long jarg1, SBTypeSummary jarg1_, long jarg2);
public final static native boolean SBTypeSummary_GetDescription(long jarg1, SBTypeSummary jarg1_, long jarg2, SBStream jarg2_, int jarg3);
public final static native boolean SBTypeSummary_DoesPrintValue(long jarg1, SBTypeSummary jarg1_, long jarg2, SBValue jarg2_);
public final static native boolean SBTypeSummary_IsEqualTo(long jarg1, SBTypeSummary jarg1_, long jarg2, SBTypeSummary jarg2_);
public final static native String SBTypeSummary___repr__(long jarg1, SBTypeSummary jarg1_);
public final static native long new_SBTypeSynthetic__SWIG_0();
public final static native long SBTypeSynthetic_CreateWithClassName__SWIG_0(String jarg1, long jarg2);
public final static native long SBTypeSynthetic_CreateWithClassName__SWIG_1(String jarg1);
public final static native long SBTypeSynthetic_CreateWithScriptCode__SWIG_0(String jarg1, long jarg2);
public final static native long SBTypeSynthetic_CreateWithScriptCode__SWIG_1(String jarg1);
public final static native long new_SBTypeSynthetic__SWIG_1(long jarg1, SBTypeSynthetic jarg1_);
public final static native void delete_SBTypeSynthetic(long jarg1);
public final static native boolean SBTypeSynthetic_IsValid(long jarg1, SBTypeSynthetic jarg1_);
public final static native boolean SBTypeSynthetic_IsClassCode(long jarg1, SBTypeSynthetic jarg1_);
public final static native boolean SBTypeSynthetic_IsClassName(long jarg1, SBTypeSynthetic jarg1_);
public final static native String SBTypeSynthetic_GetData(long jarg1, SBTypeSynthetic jarg1_);
public final static native void SBTypeSynthetic_SetClassName(long jarg1, SBTypeSynthetic jarg1_, String jarg2);
public final static native void SBTypeSynthetic_SetClassCode(long jarg1, SBTypeSynthetic jarg1_, String jarg2);
public final static native long SBTypeSynthetic_GetOptions(long jarg1, SBTypeSynthetic jarg1_);
public final static native void SBTypeSynthetic_SetOptions(long jarg1, SBTypeSynthetic jarg1_, long jarg2);
public final static native boolean SBTypeSynthetic_GetDescription(long jarg1, SBTypeSynthetic jarg1_, long jarg2, SBStream jarg2_, int jarg3);
public final static native boolean SBTypeSynthetic_IsEqualTo(long jarg1, SBTypeSynthetic jarg1_, long jarg2, SBTypeSynthetic jarg2_);
public final static native String SBTypeSynthetic___repr__(long jarg1, SBTypeSynthetic jarg1_);
public final static native long new_SBUnixSignals__SWIG_0();
public final static native long new_SBUnixSignals__SWIG_1(long jarg1, SBUnixSignals jarg1_);
public final static native void delete_SBUnixSignals(long jarg1);
public final static native void SBUnixSignals_Clear(long jarg1, SBUnixSignals jarg1_);
public final static native boolean SBUnixSignals_IsValid(long jarg1, SBUnixSignals jarg1_);
public final static native String SBUnixSignals_GetSignalAsCString(long jarg1, SBUnixSignals jarg1_, int jarg2);
public final static native int SBUnixSignals_GetSignalNumberFromName(long jarg1, SBUnixSignals jarg1_, String jarg2);
public final static native boolean SBUnixSignals_GetShouldSuppress(long jarg1, SBUnixSignals jarg1_, int jarg2);
public final static native boolean SBUnixSignals_SetShouldSuppress(long jarg1, SBUnixSignals jarg1_, int jarg2, boolean jarg3);
public final static native boolean SBUnixSignals_GetShouldStop(long jarg1, SBUnixSignals jarg1_, int jarg2);
public final static native boolean SBUnixSignals_SetShouldStop(long jarg1, SBUnixSignals jarg1_, int jarg2, boolean jarg3);
public final static native boolean SBUnixSignals_GetShouldNotify(long jarg1, SBUnixSignals jarg1_, int jarg2);
public final static native boolean SBUnixSignals_SetShouldNotify(long jarg1, SBUnixSignals jarg1_, int jarg2, boolean jarg3);
public final static native int SBUnixSignals_GetNumSignals(long jarg1, SBUnixSignals jarg1_);
public final static native int SBUnixSignals_GetSignalAtIndex(long jarg1, SBUnixSignals jarg1_, int jarg2);
public final static native long new_SBValue__SWIG_0();
public final static native long new_SBValue__SWIG_1(long jarg1, SBValue jarg1_);
public final static native void delete_SBValue(long jarg1);
public final static native boolean SBValue_IsValid(long jarg1, SBValue jarg1_);
public final static native void SBValue_Clear(long jarg1, SBValue jarg1_);
public final static native long SBValue_GetError(long jarg1, SBValue jarg1_);
public final static native java.math.BigInteger SBValue_GetID(long jarg1, SBValue jarg1_);
public final static native String SBValue_GetName(long jarg1, SBValue jarg1_);
public final static native String SBValue_GetTypeName(long jarg1, SBValue jarg1_);
public final static native String SBValue_GetDisplayTypeName(long jarg1, SBValue jarg1_);
public final static native long SBValue_GetByteSize(long jarg1, SBValue jarg1_);
public final static native boolean SBValue_IsInScope(long jarg1, SBValue jarg1_);
public final static native int SBValue_GetFormat(long jarg1, SBValue jarg1_);
public final static native void SBValue_SetFormat(long jarg1, SBValue jarg1_, int jarg2);
public final static native String SBValue_GetValue(long jarg1, SBValue jarg1_);
public final static native long SBValue_GetValueAsSigned__SWIG_0(long jarg1, SBValue jarg1_, long jarg2, SBError jarg2_, long jarg3);
public final static native long SBValue_GetValueAsSigned__SWIG_1(long jarg1, SBValue jarg1_, long jarg2, SBError jarg2_);
public final static native java.math.BigInteger SBValue_GetValueAsUnsigned__SWIG_0(long jarg1, SBValue jarg1_, long jarg2, SBError jarg2_, java.math.BigInteger jarg3);
public final static native java.math.BigInteger SBValue_GetValueAsUnsigned__SWIG_1(long jarg1, SBValue jarg1_, long jarg2, SBError jarg2_);
public final static native long SBValue_GetValueAsSigned__SWIG_2(long jarg1, SBValue jarg1_, long jarg2);
public final static native long SBValue_GetValueAsSigned__SWIG_3(long jarg1, SBValue jarg1_);
public final static native java.math.BigInteger SBValue_GetValueAsUnsigned__SWIG_2(long jarg1, SBValue jarg1_, java.math.BigInteger jarg2);
public final static native java.math.BigInteger SBValue_GetValueAsUnsigned__SWIG_3(long jarg1, SBValue jarg1_);
public final static native int SBValue_GetValueType(long jarg1, SBValue jarg1_);
public final static native boolean SBValue_GetValueDidChange(long jarg1, SBValue jarg1_);
public final static native String SBValue_GetSummary__SWIG_0(long jarg1, SBValue jarg1_);
public final static native String SBValue_GetSummary__SWIG_1(long jarg1, SBValue jarg1_, long jarg2, SBStream jarg2_, long jarg3, SBTypeSummaryOptions jarg3_);
public final static native String SBValue_GetObjectDescription(long jarg1, SBValue jarg1_);
public final static native long SBValue_GetDynamicValue(long jarg1, SBValue jarg1_, int jarg2);
public final static native long SBValue_GetStaticValue(long jarg1, SBValue jarg1_);
public final static native long SBValue_GetNonSyntheticValue(long jarg1, SBValue jarg1_);
public final static native int SBValue_GetPreferDynamicValue(long jarg1, SBValue jarg1_);
public final static native void SBValue_SetPreferDynamicValue(long jarg1, SBValue jarg1_, int jarg2);
public final static native boolean SBValue_GetPreferSyntheticValue(long jarg1, SBValue jarg1_);
public final static native void SBValue_SetPreferSyntheticValue(long jarg1, SBValue jarg1_, boolean jarg2);
public final static native boolean SBValue_IsDynamic(long jarg1, SBValue jarg1_);
public final static native boolean SBValue_IsSynthetic(long jarg1, SBValue jarg1_);
public final static native boolean SBValue_IsSyntheticChildrenGenerated(long jarg1, SBValue jarg1_);
public final static native void SBValue_SetSyntheticChildrenGenerated(long jarg1, SBValue jarg1_, boolean jarg2);
public final static native String SBValue_GetLocation(long jarg1, SBValue jarg1_);
public final static native boolean SBValue_SetValueFromCString__SWIG_0(long jarg1, SBValue jarg1_, String jarg2);
public final static native boolean SBValue_SetValueFromCString__SWIG_1(long jarg1, SBValue jarg1_, String jarg2, long jarg3, SBError jarg3_);
public final static native long SBValue_GetTypeFormat(long jarg1, SBValue jarg1_);
public final static native long SBValue_GetTypeSummary(long jarg1, SBValue jarg1_);
public final static native long SBValue_GetTypeFilter(long jarg1, SBValue jarg1_);
public final static native long SBValue_GetTypeSynthetic(long jarg1, SBValue jarg1_);
public final static native long SBValue_GetChildAtIndex__SWIG_0(long jarg1, SBValue jarg1_, long jarg2);
public final static native long SBValue_CreateChildAtOffset(long jarg1, SBValue jarg1_, String jarg2, long jarg3, long jarg4, SBType jarg4_);
public final static native long SBValue_Cast(long jarg1, SBValue jarg1_, long jarg2, SBType jarg2_);
public final static native long SBValue_CreateValueFromExpression__SWIG_0(long jarg1, SBValue jarg1_, String jarg2, String jarg3);
public final static native long SBValue_CreateValueFromExpression__SWIG_1(long jarg1, SBValue jarg1_, String jarg2, String jarg3, long jarg4, SBExpressionOptions jarg4_);
public final static native long SBValue_CreateValueFromAddress(long jarg1, SBValue jarg1_, String jarg2, java.math.BigInteger jarg3, long jarg4, SBType jarg4_);
public final static native long SBValue_CreateValueFromData(long jarg1, SBValue jarg1_, String jarg2, long jarg3, SBData jarg3_, long jarg4, SBType jarg4_);
public final static native long SBValue_GetChildAtIndex__SWIG_1(long jarg1, SBValue jarg1_, long jarg2, int jarg3, boolean jarg4);
public final static native long SBValue_GetIndexOfChildWithName(long jarg1, SBValue jarg1_, String jarg2);
public final static native long SBValue_GetChildMemberWithName__SWIG_0(long jarg1, SBValue jarg1_, String jarg2);
public final static native long SBValue_GetChildMemberWithName__SWIG_1(long jarg1, SBValue jarg1_, String jarg2, int jarg3);
public final static native long SBValue_GetValueForExpressionPath(long jarg1, SBValue jarg1_, String jarg2);
public final static native long SBValue_AddressOf(long jarg1, SBValue jarg1_);
public final static native java.math.BigInteger SBValue_GetLoadAddress(long jarg1, SBValue jarg1_);
public final static native long SBValue_GetAddress(long jarg1, SBValue jarg1_);
public final static native long SBValue_GetPointeeData__SWIG_0(long jarg1, SBValue jarg1_, long jarg2, long jarg3);
public final static native long SBValue_GetPointeeData__SWIG_1(long jarg1, SBValue jarg1_, long jarg2);
public final static native long SBValue_GetPointeeData__SWIG_2(long jarg1, SBValue jarg1_);
public final static native long SBValue_GetData(long jarg1, SBValue jarg1_);
public final static native boolean SBValue_SetData(long jarg1, SBValue jarg1_, long jarg2, SBData jarg2_, long jarg3, SBError jarg3_);
public final static native long SBValue_Clone(long jarg1, SBValue jarg1_, String jarg2);
public final static native long SBValue_GetDeclaration(long jarg1, SBValue jarg1_);
public final static native boolean SBValue_MightHaveChildren(long jarg1, SBValue jarg1_);
public final static native boolean SBValue_IsRuntimeSupportValue(long jarg1, SBValue jarg1_);
public final static native long SBValue_GetNumChildren__SWIG_0(long jarg1, SBValue jarg1_);
public final static native long SBValue_GetNumChildren__SWIG_1(long jarg1, SBValue jarg1_, long jarg2);
public final static native long SBValue_GetOpaqueType(long jarg1, SBValue jarg1_);
public final static native long SBValue_GetTarget(long jarg1, SBValue jarg1_);
public final static native long SBValue_GetProcess(long jarg1, SBValue jarg1_);
public final static native long SBValue_GetThread(long jarg1, SBValue jarg1_);
public final static native long SBValue_GetFrame(long jarg1, SBValue jarg1_);
public final static native long SBValue_Dereference(long jarg1, SBValue jarg1_);
public final static native boolean SBValue_TypeIsPointerType(long jarg1, SBValue jarg1_);
public final static native long SBValue_GetType(long jarg1, SBValue jarg1_);
public final static native long SBValue_Persist(long jarg1, SBValue jarg1_);
public final static native boolean SBValue_GetDescription(long jarg1, SBValue jarg1_, long jarg2, SBStream jarg2_);
public final static native boolean SBValue_GetExpressionPath__SWIG_0(long jarg1, SBValue jarg1_, long jarg2, SBStream jarg2_);
public final static native boolean SBValue_GetExpressionPath__SWIG_1(long jarg1, SBValue jarg1_, long jarg2, SBStream jarg2_, boolean jarg3);
public final static native long SBValue_EvaluateExpression__SWIG_0(long jarg1, SBValue jarg1_, String jarg2);
public final static native long SBValue_EvaluateExpression__SWIG_1(long jarg1, SBValue jarg1_, String jarg2, long jarg3, SBExpressionOptions jarg3_);
public final static native long SBValue_EvaluateExpression__SWIG_2(long jarg1, SBValue jarg1_, String jarg2, long jarg3, SBExpressionOptions jarg3_, String jarg4);
public final static native long SBValue_Watch__SWIG_0(long jarg1, SBValue jarg1_, boolean jarg2, boolean jarg3, boolean jarg4, long jarg5, SBError jarg5_);
public final static native long SBValue_Watch__SWIG_1(long jarg1, SBValue jarg1_, boolean jarg2, boolean jarg3, boolean jarg4);
public final static native long SBValue_WatchPointee(long jarg1, SBValue jarg1_, boolean jarg2, boolean jarg3, boolean jarg4, long jarg5, SBError jarg5_);
public final static native String SBValue___repr__(long jarg1, SBValue jarg1_);
public final static native long new_SBValueList__SWIG_0();
public final static native long new_SBValueList__SWIG_1(long jarg1, SBValueList jarg1_);
public final static native void delete_SBValueList(long jarg1);
public final static native boolean SBValueList_IsValid(long jarg1, SBValueList jarg1_);
public final static native void SBValueList_Clear(long jarg1, SBValueList jarg1_);
public final static native void SBValueList_Append__SWIG_0(long jarg1, SBValueList jarg1_, long jarg2, SBValue jarg2_);
public final static native void SBValueList_Append__SWIG_1(long jarg1, SBValueList jarg1_, long jarg2, SBValueList jarg2_);
public final static native long SBValueList_GetSize(long jarg1, SBValueList jarg1_);
public final static native long SBValueList_GetValueAtIndex(long jarg1, SBValueList jarg1_, long jarg2);
public final static native long SBValueList_GetFirstValueByName(long jarg1, SBValueList jarg1_, String jarg2);
public final static native long SBValueList_FindValueObjectByUID(long jarg1, SBValueList jarg1_, java.math.BigInteger jarg2);
public final static native long SBValueList_GetError(long jarg1, SBValueList jarg1_);
public final static native String SBValueList___str__(long jarg1, SBValueList jarg1_);
public final static native long new_SBVariablesOptions__SWIG_0();
public final static native long new_SBVariablesOptions__SWIG_1(long jarg1, SBVariablesOptions jarg1_);
public final static native void delete_SBVariablesOptions(long jarg1);
public final static native boolean SBVariablesOptions_IsValid(long jarg1, SBVariablesOptions jarg1_);
public final static native boolean SBVariablesOptions_GetIncludeArguments(long jarg1, SBVariablesOptions jarg1_);
public final static native void SBVariablesOptions_SetIncludeArguments(long jarg1, SBVariablesOptions jarg1_, boolean jarg2);
public final static native boolean SBVariablesOptions_GetIncludeRecognizedArguments(long jarg1, SBVariablesOptions jarg1_, long jarg2, SBTarget jarg2_);
public final static native void SBVariablesOptions_SetIncludeRecognizedArguments(long jarg1, SBVariablesOptions jarg1_, boolean jarg2);
public final static native boolean SBVariablesOptions_GetIncludeLocals(long jarg1, SBVariablesOptions jarg1_);
public final static native void SBVariablesOptions_SetIncludeLocals(long jarg1, SBVariablesOptions jarg1_, boolean jarg2);
public final static native boolean SBVariablesOptions_GetIncludeStatics(long jarg1, SBVariablesOptions jarg1_);
public final static native void SBVariablesOptions_SetIncludeStatics(long jarg1, SBVariablesOptions jarg1_, boolean jarg2);
public final static native boolean SBVariablesOptions_GetInScopeOnly(long jarg1, SBVariablesOptions jarg1_);
public final static native void SBVariablesOptions_SetInScopeOnly(long jarg1, SBVariablesOptions jarg1_, boolean jarg2);
public final static native boolean SBVariablesOptions_GetIncludeRuntimeSupportValues(long jarg1, SBVariablesOptions jarg1_);
public final static native void SBVariablesOptions_SetIncludeRuntimeSupportValues(long jarg1, SBVariablesOptions jarg1_, boolean jarg2);
public final static native int SBVariablesOptions_GetUseDynamic(long jarg1, SBVariablesOptions jarg1_);
public final static native void SBVariablesOptions_SetUseDynamic(long jarg1, SBVariablesOptions jarg1_, int jarg2);
public final static native long new_SBWatchpoint__SWIG_0();
public final static native long new_SBWatchpoint__SWIG_1(long jarg1, SBWatchpoint jarg1_);
public final static native void delete_SBWatchpoint(long jarg1);
public final static native boolean SBWatchpoint_IsValid(long jarg1, SBWatchpoint jarg1_);
public final static native long SBWatchpoint_GetError(long jarg1, SBWatchpoint jarg1_);
public final static native int SBWatchpoint_GetID(long jarg1, SBWatchpoint jarg1_);
public final static native int SBWatchpoint_GetHardwareIndex(long jarg1, SBWatchpoint jarg1_);
public final static native java.math.BigInteger SBWatchpoint_GetWatchAddress(long jarg1, SBWatchpoint jarg1_);
public final static native long SBWatchpoint_GetWatchSize(long jarg1, SBWatchpoint jarg1_);
public final static native void SBWatchpoint_SetEnabled(long jarg1, SBWatchpoint jarg1_, boolean jarg2);
public final static native boolean SBWatchpoint_IsEnabled(long jarg1, SBWatchpoint jarg1_);
public final static native long SBWatchpoint_GetHitCount(long jarg1, SBWatchpoint jarg1_);
public final static native long SBWatchpoint_GetIgnoreCount(long jarg1, SBWatchpoint jarg1_);
public final static native void SBWatchpoint_SetIgnoreCount(long jarg1, SBWatchpoint jarg1_, long jarg2);
public final static native String SBWatchpoint_GetCondition(long jarg1, SBWatchpoint jarg1_);
public final static native void SBWatchpoint_SetCondition(long jarg1, SBWatchpoint jarg1_, String jarg2);
public final static native boolean SBWatchpoint_GetDescription(long jarg1, SBWatchpoint jarg1_, long jarg2, SBStream jarg2_, int jarg3);
public final static native void SBWatchpoint_Clear(long jarg1, SBWatchpoint jarg1_);
public final static native boolean SBWatchpoint_EventIsWatchpointEvent(long jarg1, SBEvent jarg1_);
public final static native int SBWatchpoint_GetWatchpointEventTypeFromEvent(long jarg1, SBEvent jarg1_);
public final static native long SBWatchpoint_GetWatchpointFromEvent(long jarg1, SBEvent jarg1_);
public final static native long SBWatchpoint_GetType(long jarg1, SBWatchpoint jarg1_);
public final static native int SBWatchpoint_GetWatchValueKind(long jarg1, SBWatchpoint jarg1_);
public final static native String SBWatchpoint_GetWatchSpec(long jarg1, SBWatchpoint jarg1_);
public final static native boolean SBWatchpoint_IsWatchingReads(long jarg1, SBWatchpoint jarg1_);
public final static native boolean SBWatchpoint_IsWatchingWrites(long jarg1, SBWatchpoint jarg1_);
public final static native String SBWatchpoint___repr__(long jarg1, SBWatchpoint jarg1_);
}
| NationalSecurityAgency/ghidra | Ghidra/Debug/Debugger-swig-lldb/src/main/java/SWIG/lldbJNI.java |
2,772 | // $Id: sumcol.java,v 1.5 2007-06-20 03:32:39 bfulgham Exp $
// http://www.bagley.org/~doug/shootout/
import java.io.*;
import java.util.*;
import java.text.*;
public class sumcol {
public static void main(String[] args) {
int sum = 0;
String line;
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while ((line = in.readLine()) != null) {
sum = sum + Integer.parseInt(line);
}
} catch (IOException e) {
System.err.println(e);
return;
}
System.out.println(Integer.toString(sum));
}
}
| CyberFlameGO/groovy | benchmark/bench/sumcol.java |
2,773 | package com.googleresearch.bustle;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static java.lang.Math.max;
import static java.lang.Math.min;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.googleresearch.bustle.propertysignatures.ComputeSignature;
import com.googleresearch.bustle.propertysignatures.PropertySummary;
import com.googleresearch.bustle.value.ConstantValue;
import com.googleresearch.bustle.value.InputValue;
import com.googleresearch.bustle.value.OutputValue;
import com.googleresearch.bustle.value.Value;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.stream.IntStream;
import org.apache.commons.text.similarity.LevenshteinDistance;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Mixin;
import picocli.CommandLine.Option;
/** BUSTLE synthesizer. */
@Command(name = "Synthesizer", mixinStandardHelpOptions = true)
public final class Synthesizer implements Callable<List<SynthesisResult>> {
@SuppressWarnings("FieldCanBeFinal") // picocli modifies value when flag is set
@Option(
names = {"--benchmark_name"},
description = "Name of benchmark to run, or \"ALL\".")
private static String benchmarkName = "ALL";
@SuppressWarnings("FieldCanBeFinal")
@Option(
names = {"--included_tags"},
description = "Benchmark tags to include, by default everything.")
private static ImmutableList<BenchmarkTag> includedTags = ImmutableList.of();
@SuppressWarnings("FieldCanBeFinal")
@Option(
names = {"--excluded_tags"},
description = "Benchmark tags to exclude.")
private static ImmutableList<BenchmarkTag> excludedTags =
ImmutableList.of(
BenchmarkTag.REGEX,
BenchmarkTag.ARRAY,
BenchmarkTag.TEXT_FORMATTING,
BenchmarkTag.TOO_DIFFICULT,
BenchmarkTag.SHOULD_FAIL);
@SuppressWarnings("FieldCanBeFinal")
@Option(
names = {"--sygus_benchmarks"},
description = "Whether to use (only) SyGuS benchmarks.")
private static boolean sygusBenchmarks = false;
@Mixin
private SygusBenchmarks sygusBenchmarksMixin; // Defines the --sygus_benchmarks_directory option.
@SuppressWarnings("FieldCanBeFinal")
@Option(
names = {"--output_file"},
description = "Where to save the json file summarizing the results.")
private static String outputFile = "/tmp/synthesis_results.json";
@SuppressWarnings("FieldCanBeFinal")
@Option(
names = {"--max_expressions"},
description = "Maximum number of expressions to try.")
private static int maxExpressions = 1000 * 1000 * 1000;
@SuppressWarnings("FieldCanBeFinal")
@Option(
names = {"--time_limit"},
description = "Maximum number of seconds to run.")
private static double timeLimit = 10.0;
@SuppressWarnings("FieldCanBeFinal")
@Option(
names = {"--max_weight"},
description = "Maximum weight of expressions to try.")
private static int maxWeight = 100;
@SuppressWarnings("FieldCanBeFinal")
@Option(
names = {"--print_progress"},
description = "Whether to print synthesis progress.")
private static boolean printProgress = false;
@SuppressWarnings("FieldCanBeFinal")
@Option(
names = {"--log_predictions"},
description = "Whether to log predictions to a separate file.")
private static boolean logPredictions = false;
@SuppressWarnings("FieldCanBeFinal")
@Option(
names = {"--prediction_log_directory"},
description = "Where to log model predictions.")
private static String predictionLogDirectory = "/tmp/prediction_logs/";
@SuppressWarnings("FieldCanBeFinal")
@Option(
names = {"--model_reweighting"},
description = "Whether to use a learned model to reweight intermediate values.")
private static boolean modelReweighting = true;
@SuppressWarnings("FieldCanBeFinal")
@Option(
names = {"--model_reweighting_fraction"},
description =
"Perform model reweighting only for the first fraction of the synthesis, either by time"
+ " or number of expressions.")
private static double modelReweightingFraction = 1.0;
@SuppressWarnings("FieldCanBeFinal")
@Option(
names = {"--model_directory"},
description = "Directory for saved model.")
private static String modelDirectory = "/tmp/saved_model_dir/";
@SuppressWarnings("FieldCanBeFinal")
@Option(
names = {"--model_batch_size"},
description = "Batch size for the model.")
private static int modelBatchSize = 1024;
@SuppressWarnings("FieldCanBeFinal")
@Option(
names = {"--reweight_alpha"},
description = "Alpha in reweighting scheme.")
private static double reweightAlpha = 0.6;
@SuppressWarnings("FieldCanBeFinal")
@Option(
names = {"--reweight_beta"},
description = "Beta in reweighting scheme.")
private static double reweightBeta = 0.4;
@SuppressWarnings("FieldCanBeFinal")
@Option(
names = {"--premise_selection"},
description = "Whether to use learned model to exclude some operations.")
private static boolean premiseSelection = false;
@SuppressWarnings("FieldCanBeFinal")
@Option(
names = {"--premise_selection_model_directory"},
description = "Directory for saved model.")
private static String premiseSelectionModelDirectory = "/tmp/saved_premise_selection_model_dir/";
@SuppressWarnings("FieldCanBeFinal")
@Option(
names = {"--premises_to_drop"},
description = "Number of premises to discard.")
private static int premisesToDrop = 2;
@SuppressWarnings("FieldCanBeFinal")
@Option(
names = {"--heuristic_reweighting"},
description =
"Whether to use substring and edit distance heuristics to reweight intermediate values.")
private static boolean heuristicReweighting = true;
@SuppressWarnings("FieldCanBeFinal")
@Option(
names = {"--output_substring_weight_reduction"},
description = "Weight subtracted from values that are substrings of the output.")
private static int outputSubstringWeightReduction = 2;
@SuppressWarnings("FieldCanBeFinal")
@Option(
names = {"--edit_distance_weight_addition"},
description = "Maximum weight added to values that have large edit distance to the output.")
private static int editDistanceWeightAddition = 3;
@SuppressWarnings("FieldCanBeFinal")
@Option(
names = {"--parse_flags_only"},
description = "Whether to only parse flags and skip synthesis (for testing).")
private static boolean parseFlagsOnly = false;
@SuppressWarnings("FieldCanBeFinal")
@Option(
names = {"--quick_test"},
description = "Whether to only synthesize the first 3 tasks (for testing).")
private static boolean quickTest = false;
// Constants that are always used.
private static final ImmutableList<Object> ALWAYS_USED_CONSTANTS =
ImmutableList.of("", 0, 1, 2, 3, 99);
// These string constants are used if they appear in an input or output string.
private static final ImmutableList<String> CANDIDATE_STRING_CONSTANTS =
ImmutableList.of(
" ", ",", ".", "!", "?", "(", ")", "[", "]", "<", ">", "{", "}", "-", "+", "_", "/", "$",
"#", ":", ";", "@", "%", "0");
/** Fills the container arguments to prepare for a bottom-up enumerative synthesis search. */
private static void synthesisSetup(
Benchmark benchmark,
List<List<? extends Object>> inputObjects,
List<InputValue> inputValues,
List<Object> outputObjects,
List<List<Value>> valuesByWeight,
Set<Value> seenValues) {
int numExamples = benchmark.getTrainExamples().size();
int numInputs = benchmark.getTrainExamples().get(0).inputs().size();
for (Example ex : benchmark.getTrainExamples()) {
if (ex.inputs().size() != numInputs) {
throw new IllegalArgumentException(
"Benchmark's examples must all have the same number of inputs.");
}
inputObjects.add(ex.inputs());
outputObjects.add(ex.output());
}
for (int i = 0; i < numInputs; i++) {
List<Object> thisInputObjects = new ArrayList<>();
for (int j = 0; j < numExamples; j++) {
thisInputObjects.add(inputObjects.get(j).get(i));
}
inputValues.add(new InputValue(thisInputObjects, "var_" + i));
}
OutputValue outputValue = new OutputValue(outputObjects);
valuesByWeight.add(ImmutableList.of()); // Nothing has weight 0.
ImmutableList<Value> alwaysUsedConstantValues =
ALWAYS_USED_CONSTANTS.stream()
.map(c -> new ConstantValue(c, numExamples))
.collect(toImmutableList());
ImmutableList<Value> extractedConstantValues =
ConstantExtraction.extractConstants(inputValues, outputValue, CANDIDATE_STRING_CONSTANTS)
.stream()
.map(c -> new ConstantValue(c, numExamples))
.collect(toImmutableList());
System.out.println("Extracted constants: " + extractedConstantValues);
List<Value> weightOneValues = new ArrayList<>();
weightOneValues.addAll(inputValues);
weightOneValues.addAll(alwaysUsedConstantValues);
weightOneValues.addAll(extractedConstantValues);
valuesByWeight.add(weightOneValues);
seenValues.addAll(weightOneValues);
for (int weight = 2; weight <= maxWeight; weight++) {
valuesByWeight.add(new ArrayList<>());
}
}
private static int heuristicReweightResult(
Value result, int weight, int numExamples, Class<?> outputType, List<Object> outputObjects) {
int resultWeight = weight;
if (outputType.equals(String.class) && result.getType().equals(String.class)) {
// Check for substrings, and increase weight of values that are very different from
// the output.
// If the weight reduction is zero, then don't bother checking for substrings at all.
boolean allResultsInOutputs = outputSubstringWeightReduction > 0;
double maxNormalizedDistance = 0.0;
for (int i = 0; i < numExamples; i++) {
String outputString = (String) outputObjects.get(i);
String resultString = (String) result.getWrappedValue(i);
if (allResultsInOutputs && !outputString.contains(resultString)) {
allResultsInOutputs = false;
}
if (editDistanceWeightAddition > 0) {
// Normalized distance: 2 * lev(x, y) / (len(x) + len(y) + lev(x, y)).
int distance = LevenshteinDistance.getDefaultInstance().apply(resultString, outputString);
double normalizedDistance =
2.0 * distance / (outputString.length() + resultString.length() + distance);
maxNormalizedDistance = max(maxNormalizedDistance, normalizedDistance);
}
}
if (allResultsInOutputs) {
resultWeight -= outputSubstringWeightReduction;
}
resultWeight += 1 + (int) (maxNormalizedDistance * editDistanceWeightAddition);
}
return max(resultWeight, weight);
}
/**
* Checks if a value is too large to include in the search. Very long strings can lead to slowdown
* when evaluating operations, and very large ints can as well for operations like REPT.
*/
private static boolean valueTooLarge(Value value) {
if (value.getType().equals(String.class)) {
for (Object str : value.getWrappedValues()) {
if (((String) str).length() >= 99) { // Make sure to throw out REPT(X, 99)
return true;
}
}
} else if (value.getType().equals(Integer.class)) {
for (Object val : value.getWrappedValues()) {
if (Math.abs((Integer) val) >= 100) {
return true;
}
}
}
return false;
}
private static double sigmoid(float x) {
if (x >= 0) {
return 1 / (1 + Math.exp(-x));
} else {
double z = Math.exp(x);
return z / (1 + z);
}
}
private static List<Operation> selectPremises(
SavedModelWrapper premiseSelectionModel, List<PropertySummary> exampleSignature) {
List<Operation> allOperations = Operation.getOperations();
List<Operation> operations = new ArrayList<>();
if (premiseSelectionModel == null) {
operations = allOperations;
} else {
List<PropertySummary> dummySignature =
ComputeSignature.computeValueSignature(null, new OutputValue(ImmutableList.of("dummy")));
List<PropertySummary> zeroSignature =
Collections.nCopies(dummySignature.size(), PropertySummary.ALL_TRUE);
float[][] premiseModelResults =
premiseSelectionModel.doInference(exampleSignature, ImmutableList.of(zeroSignature));
// indicesByScore is a list of indices - one-per-operation - sorted by model's estimated
// likelihood of that operation appearing in the solution.
// Note: the outputs of the premiseSelection model are in fact probabilties and not logits,
// due to some keras grossness.
ImmutableList<Integer> indicesByScore =
IntStream.range(0, allOperations.size()).boxed().collect(toImmutableList());
Collections.sort(indicesByScore, Comparator.comparing(idx -> premiseModelResults[0][idx]));
// We can then just throw out the operations whose indices appear first, as they are the ones
// with the lowest estimated likelihood.
for (int i = 0; i < allOperations.size(); i++) {
if (indicesByScore.indexOf(i) >= premisesToDrop) {
operations.add(allOperations.get(i));
}
}
}
return operations;
}
/**
* Bottom-up enumerative search. Expressions are enumerated in order of increasing weight. All
* inputs, constants, and operations have weight 1.
*/
public static SynthesisResult synthesize(Benchmark benchmark) {
return synthesize(benchmark, new HashSet<>());
}
public static SynthesisResult synthesize(Benchmark benchmark, Set<Value> seenValues) {
return synthesize(benchmark, null, null, seenValues);
}
public static SynthesisResult synthesize(
Benchmark benchmark, SavedModelWrapper model, SavedModelWrapper premiseSelectionModel) {
return synthesize(benchmark, model, premiseSelectionModel, new HashSet<>());
}
public static SynthesisResult synthesize(
Benchmark benchmark,
SavedModelWrapper model,
SavedModelWrapper premiseSelectionModel,
Set<Value> seenValues) {
long totalCoreTime = 0;
long totalSignatureTime = 0;
long totalModelTime = 0;
long totalHeuristicTime = 0;
long startTime = System.nanoTime();
int numExamples = benchmark.getTrainExamples().size();
if (numExamples == 0) {
throw new IllegalArgumentException("Benchmark must have at least one example.");
}
// Used for storing model predictions for further analysis (insertion is flag-guarded)
List<PredictionDataItem> predictionDataItems = new ArrayList<>();
List<List<? extends Object>> inputObjects = new ArrayList<>(); // numExamples x numInputs.
List<InputValue> inputValues = new ArrayList<>();
List<Object> outputObjects = new ArrayList<>();
// Implicitly a map from weight to list of values of that weight, with weight encoded by index.
List<List<Value>> valuesByWeight = new ArrayList<>();
synthesisSetup(benchmark, inputObjects, inputValues, outputObjects, valuesByWeight, seenValues);
OutputValue outputValue = new OutputValue(outputObjects);
Class<?> outputType = outputValue.getType();
List<PropertySummary> exampleSignature =
ComputeSignature.computeExampleSignature(inputValues, outputValue);
// Choose which operations to exclude based on the premise selector
List<Operation> operations = selectPremises(premiseSelectionModel, exampleSignature);
int numExpressionsTried = 0;
weightLoop:
for (int weight = 2; weight <= maxWeight; weight++) {
if (printProgress) {
System.out.println("Searching weight " + weight);
}
// Find new values with this weight.
List<Value> newValues = new ArrayList<>();
long coreStart = System.nanoTime();
for (Operation operation : operations) {
int numArgs = operation.getNumArgs();
List<Class<?>> argTypes = operation.getArgTypes();
for (List<Integer> argWeights : Utils.generatePartitions(weight - 1, numArgs)) {
if ((System.nanoTime() - startTime) / 1e9 > timeLimit) {
totalCoreTime += System.nanoTime() - coreStart;
break weightLoop;
}
List<List<Value>> allArgChoices = new ArrayList<>();
for (int argIndex = 0; argIndex < numArgs; argIndex++) {
final int finalArgIndex = argIndex;
allArgChoices.add(
valuesByWeight.get(argWeights.get(argIndex)).stream()
.filter(v -> v.getType().equals(argTypes.get(finalArgIndex)))
.collect(toImmutableList()));
}
for (List<Value> argList : Lists.cartesianProduct(allArgChoices)) {
if (numExpressionsTried >= maxExpressions) {
totalCoreTime += System.nanoTime() - coreStart;
break weightLoop;
}
Value result = operation.apply(argList);
numExpressionsTried++;
if (result == null || valueTooLarge(result)) {
continue;
}
if (seenValues.add(result)) {
newValues.add(result);
}
if (result.equals(outputValue)) {
String solution = result.expression();
System.out.println("Synthesis success! " + solution);
System.out.println("Num expressions tried: " + numExpressionsTried);
System.out.println("Num unique values: " + seenValues.size());
long endTime = System.nanoTime();
double elapsedTime = (endTime - startTime) / 1e9;
if (logPredictions) {
Utils.analyzePredictions(
true, result, predictionDataItems, predictionLogDirectory, benchmark);
}
return SynthesisResult.createSuccess(
benchmark.getName(),
numExpressionsTried,
seenValues.size(),
elapsedTime,
solution,
weight);
}
}
}
}
totalCoreTime += System.nanoTime() - coreStart;
if (printProgress) {
System.out.println(
" Found " + newValues.size() + " new values while searching weight " + weight);
}
// Reweight the new values using the model.
int[] modelWeightDeltas = new int[newValues.size()];
double[] probabilities = new double[newValues.size()]; // strictly for analysis
double currentSynthesisFraction =
max(
numExpressionsTried / (double) maxExpressions,
(System.nanoTime() - startTime) / 1e9 / timeLimit);
boolean skipModel = currentSynthesisFraction > modelReweightingFraction;
if (skipModel && printProgress) {
System.out.println("Skipping signatures and model runs for weight " + weight);
}
if (model == null || skipModel) {
Arrays.fill(modelWeightDeltas, 0);
Arrays.fill(probabilities, 0);
} else {
int numValuesProcessed = 0;
while (numValuesProcessed < newValues.size()) {
if ((System.nanoTime() - startTime) / 1e9 > timeLimit) {
break weightLoop;
}
int thisBatchSize = min(modelBatchSize, newValues.size() - numValuesProcessed);
long signatureStart = System.nanoTime();
// Compute property signatures with a parallel stream
ImmutableList<List<PropertySummary>> valueSignatures =
IntStream.range(numValuesProcessed, numValuesProcessed + thisBatchSize)
.boxed()
.collect(toImmutableList())
.stream()
.parallel()
.map(i -> ComputeSignature.computeValueSignature(newValues.get(i), outputValue))
.collect(toImmutableList());
totalSignatureTime += System.nanoTime() - signatureStart;
long modelStart = System.nanoTime();
float[][] modelResults = model.doInference(exampleSignature, valueSignatures);
for (int i = 0; i < thisBatchSize; i++) {
float logit = modelResults[i][0];
int modelWeightDelta = 0;
double probability = sigmoid(logit);
// Optionally pre-process predictions for out-of-band analysis
// Begin Analysis Code
if (logPredictions) {
predictionDataItems.add(
new PredictionDataItem(
benchmark.getExpectedProgram(),
newValues.get(numValuesProcessed + i),
newValues.get(numValuesProcessed + i).expression(),
true, // as a placeholder, set isPositiveExample to true
probability,
exampleSignature,
valueSignatures.get(i)));
}
// End Analysis Code
if (probability > reweightAlpha) {
modelWeightDelta = 0;
} else if (probability > reweightBeta) {
modelWeightDelta = 1;
} else {
// probability in [0, 0.4]
// (0.4 - probability) in [0, 0.4]
// (10 * (0.4 - probability) + 2) in [2, 6]
// Due to integer truncation, delta=6 won't happen unless probability is exactly 0.
modelWeightDelta = (int) (10 * (0.4 - probability) + 2);
}
modelWeightDeltas[numValuesProcessed + i] = modelWeightDelta;
probabilities[numValuesProcessed + i] = probability;
}
totalModelTime += System.nanoTime() - modelStart;
numValuesProcessed += thisBatchSize;
}
}
// Reweight the new values using heuristics.
int[] heuristicWeights = new int[newValues.size()];
if (!heuristicReweighting) {
Arrays.fill(heuristicWeights, weight);
} else {
long heuristicStart = System.nanoTime();
for (int i = 0; i < newValues.size(); i++) {
heuristicWeights[i] =
heuristicReweightResult(
newValues.get(i), weight, numExamples, outputType, outputObjects);
}
totalHeuristicTime += System.nanoTime() - heuristicStart;
}
// Record the new values using the updated weights.
for (int i = 0; i < newValues.size(); i++) {
int newValueWeight = heuristicWeights[i] + modelWeightDeltas[i];
if (newValueWeight <= maxWeight) {
valuesByWeight.get(newValueWeight).add(newValues.get(i));
}
}
}
System.out.println("Synthesis failure.");
System.out.println("Total core time: " + totalCoreTime / 1e9 + " sec");
System.out.println("Total signature time: " + totalSignatureTime / 1e9 + " sec");
System.out.println("Total model time: " + totalModelTime / 1e9 + " sec");
System.out.println("Total heuristic time: " + totalHeuristicTime / 1e9 + " sec");
return SynthesisResult.createFailure(
benchmark.getName(),
numExpressionsTried,
seenValues.size(),
(System.nanoTime() - startTime) / 1e9);
}
public static void warmUp(SavedModelWrapper model) {
// Warm up by synthesizing a benchmark.
System.out.println("Warming up...");
synthesize(Benchmarks.prependMr(), model, null);
System.out.println("\nDone warming up.\n");
}
private static double mean(List<? extends Number> numbers) {
return numbers.stream().mapToDouble(Number::doubleValue).average().orElse(Double.NaN);
}
private static double geometricMean(List<? extends Number> numbers) {
return Math.exp(
numbers.stream().mapToDouble(x -> Math.log(x.doubleValue())).average().orElse(Double.NaN));
}
private static Map<String, Object> saveResultsToJson(List<SynthesisResult> synthesisResults)
throws IOException {
int numSolved = 0;
int numBenchmarks = synthesisResults.size();
List<Double> solveTimes = new ArrayList<>();
List<Integer> solveNumExpressions = new ArrayList<>();
List<Integer> solveNumUnique = new ArrayList<>();
List<Double> allTimes = new ArrayList<>();
List<Integer> allNumExpressions = new ArrayList<>();
List<Integer> allNumUnique = new ArrayList<>();
for (SynthesisResult result : synthesisResults) {
if (result.getSuccess()) {
numSolved++;
solveTimes.add(result.getElapsedTime());
solveNumExpressions.add(result.getNumExpressionsTried());
solveNumUnique.add(result.getNumUniqueValues());
}
allTimes.add(result.getElapsedTime());
allNumExpressions.add(result.getNumExpressionsTried());
allNumUnique.add(result.getNumUniqueValues());
}
// Maintain insertion-order of entries for consistent JSON output.
Map<String, Object> jsonMap = new LinkedHashMap<>();
jsonMap.put("numSolved", numSolved);
jsonMap.put("numBenchmarks", numBenchmarks);
jsonMap.put("solveTimesMean", mean(solveTimes));
jsonMap.put("solveTimesGeoMean", geometricMean(solveTimes));
jsonMap.put("solveNumExpressionsMean", mean(solveNumExpressions));
jsonMap.put("solveNumExpressionsGeoMean", geometricMean(solveNumExpressions));
jsonMap.put("solveNumUniqueMean", mean(solveNumUnique));
jsonMap.put("solveNumUniqueGeoMean", geometricMean(solveNumUnique));
jsonMap.put("allTimesMean", mean(allTimes));
jsonMap.put("allTimesGeoMean", geometricMean(allTimes));
jsonMap.put("allNumExpressionsMean", mean(allNumExpressions));
jsonMap.put("allNumExpressionsGeoMean", geometricMean(allNumExpressions));
jsonMap.put("allNumUniqueMean", mean(allNumUnique));
jsonMap.put("allNumUniqueGeoMean", geometricMean(allNumUnique));
jsonMap.put("results", synthesisResults);
Gson gson =
new GsonBuilder()
.disableHtmlEscaping()
.setPrettyPrinting()
.serializeSpecialFloatingPointValues()
.create();
try (PrintWriter writer = new PrintWriter(outputFile, "UTF-8")) {
writer.println(gson.toJson(jsonMap));
writer.close();
} catch (IOException e) {
System.out.println("OH NO! We couldn't write the results file.");
throw e;
}
return jsonMap;
}
@Override
public List<SynthesisResult> call() throws IOException {
if (parseFlagsOnly) {
return new ArrayList<>();
}
SavedModelWrapper model = modelReweighting ? new SavedModelWrapper(modelDirectory) : null;
SavedModelWrapper premiseSelectionModel =
premiseSelection ? new SavedModelWrapper(premiseSelectionModelDirectory) : null;
warmUp(model);
List<Benchmark> benchmarks;
if (sygusBenchmarks) {
benchmarks = SygusBenchmarks.getSygusBenchmarks();
} else {
benchmarks = Benchmarks.getBenchmarkWithName(benchmarkName, includedTags, excludedTags);
}
List<SynthesisResult> synthesisResults = new ArrayList<>();
for (Benchmark b : benchmarks) {
if (quickTest && synthesisResults.size() >= 3) {
break;
}
System.gc();
System.out.println("--------------------------------------------------------------");
System.out.println("Attempting benchmark: " + b);
long startTime = System.nanoTime();
SynthesisResult synthesisResult = synthesize(b, model, premiseSelectionModel);
long endTime = System.nanoTime();
System.out.println("Elapsed time: " + (endTime - startTime) / 1e9 + " seconds");
synthesisResults.add(synthesisResult);
}
System.out.println("Writing synthesis results to: " + outputFile);
Map<String, Object> jsonMap = saveResultsToJson(synthesisResults);
System.out.printf(
"\nSolved %d / %d benchmarks.\n",
(int) jsonMap.get("numSolved"),
(int) jsonMap.get("numBenchmarks"));
System.out.printf(
"Arithmetic mean of successes: %5.2f seconds, %10.1f expressions, %9.1f unique values\n",
(double) jsonMap.get("solveTimesMean"),
(double) jsonMap.get("solveNumExpressionsMean"),
(double) jsonMap.get("solveNumUniqueMean"));
System.out.printf(
"Geometric mean of successes: %5.2f seconds, %10.1f expressions, %9.1f unique values\n",
(double) jsonMap.get("solveTimesGeoMean"),
(double) jsonMap.get("solveNumExpressionsGeoMean"),
(double) jsonMap.get("solveNumUniqueGeoMean"));
return synthesisResults;
}
public static void main(String[] args) {
int exitCode = new CommandLine(new Synthesizer()).execute(args);
System.exit(exitCode);
}
}
| google-research/google-research | bustle/com/googleresearch/bustle/Synthesizer.java |
2,774 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* 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 com.google.android.exoplayer2;
import static com.google.android.exoplayer2.C.TRACK_TYPE_AUDIO;
import static com.google.android.exoplayer2.C.TRACK_TYPE_CAMERA_MOTION;
import static com.google.android.exoplayer2.C.TRACK_TYPE_VIDEO;
import static com.google.android.exoplayer2.Renderer.MSG_SET_AUDIO_ATTRIBUTES;
import static com.google.android.exoplayer2.Renderer.MSG_SET_AUDIO_SESSION_ID;
import static com.google.android.exoplayer2.Renderer.MSG_SET_AUX_EFFECT_INFO;
import static com.google.android.exoplayer2.Renderer.MSG_SET_CAMERA_MOTION_LISTENER;
import static com.google.android.exoplayer2.Renderer.MSG_SET_CHANGE_FRAME_RATE_STRATEGY;
import static com.google.android.exoplayer2.Renderer.MSG_SET_PREFERRED_AUDIO_DEVICE;
import static com.google.android.exoplayer2.Renderer.MSG_SET_SCALING_MODE;
import static com.google.android.exoplayer2.Renderer.MSG_SET_SKIP_SILENCE_ENABLED;
import static com.google.android.exoplayer2.Renderer.MSG_SET_VIDEO_FRAME_METADATA_LISTENER;
import static com.google.android.exoplayer2.Renderer.MSG_SET_VIDEO_OUTPUT;
import static com.google.android.exoplayer2.Renderer.MSG_SET_VOLUME;
import static com.google.android.exoplayer2.util.Assertions.checkArgument;
import static com.google.android.exoplayer2.util.Assertions.checkNotNull;
import static com.google.android.exoplayer2.util.Assertions.checkState;
import static com.google.android.exoplayer2.util.Util.castNonNull;
import static java.lang.Math.max;
import static java.lang.Math.min;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.SurfaceTexture;
import android.media.AudioDeviceInfo;
import android.media.AudioFormat;
import android.media.AudioTrack;
import android.media.MediaFormat;
import android.media.metrics.LogSessionId;
import android.os.Handler;
import android.os.Looper;
import android.util.Pair;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.TextureView;
import androidx.annotation.DoNotInline;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import com.google.android.exoplayer2.PlayerMessage.Target;
import com.google.android.exoplayer2.Renderer.MessageType;
import com.google.android.exoplayer2.analytics.AnalyticsCollector;
import com.google.android.exoplayer2.analytics.AnalyticsListener;
import com.google.android.exoplayer2.analytics.DefaultAnalyticsCollector;
import com.google.android.exoplayer2.analytics.MediaMetricsListener;
import com.google.android.exoplayer2.analytics.PlayerId;
import com.google.android.exoplayer2.audio.AudioAttributes;
import com.google.android.exoplayer2.audio.AudioRendererEventListener;
import com.google.android.exoplayer2.audio.AuxEffectInfo;
import com.google.android.exoplayer2.decoder.DecoderCounters;
import com.google.android.exoplayer2.decoder.DecoderReuseEvaluation;
import com.google.android.exoplayer2.metadata.Metadata;
import com.google.android.exoplayer2.metadata.MetadataOutput;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.MediaSource.MediaPeriodId;
import com.google.android.exoplayer2.source.ShuffleOrder;
import com.google.android.exoplayer2.source.TrackGroup;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.text.Cue;
import com.google.android.exoplayer2.text.CueGroup;
import com.google.android.exoplayer2.text.TextOutput;
import com.google.android.exoplayer2.trackselection.ExoTrackSelection;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.trackselection.TrackSelectionParameters;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelectorResult;
import com.google.android.exoplayer2.upstream.BandwidthMeter;
import com.google.android.exoplayer2.util.Clock;
import com.google.android.exoplayer2.util.ConditionVariable;
import com.google.android.exoplayer2.util.HandlerWrapper;
import com.google.android.exoplayer2.util.ListenerSet;
import com.google.android.exoplayer2.util.Log;
import com.google.android.exoplayer2.util.PriorityTaskManager;
import com.google.android.exoplayer2.util.Size;
import com.google.android.exoplayer2.util.Util;
import com.google.android.exoplayer2.video.VideoDecoderOutputBufferRenderer;
import com.google.android.exoplayer2.video.VideoFrameMetadataListener;
import com.google.android.exoplayer2.video.VideoRendererEventListener;
import com.google.android.exoplayer2.video.VideoSize;
import com.google.android.exoplayer2.video.spherical.CameraMotionListener;
import com.google.android.exoplayer2.video.spherical.SphericalGLSurfaceView;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import org.telegram.messenger.DispatchQueue;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.TimeoutException;
/** The default implementation of {@link ExoPlayer}. */
/* package */ final class ExoPlayerImpl extends BasePlayer
implements ExoPlayer,
ExoPlayer.AudioComponent,
ExoPlayer.VideoComponent,
ExoPlayer.TextComponent,
ExoPlayer.DeviceComponent {
static {
ExoPlayerLibraryInfo.registerModule("goog.exo.exoplayer");
}
private static final String TAG = "ExoPlayerImpl";
/**
* This empty track selector result can only be used for {@link PlaybackInfo#trackSelectorResult}
* when the player does not have any track selection made (such as when player is reset, or when
* player seeks to an unprepared period). It will not be used as result of any {@link
* TrackSelector#selectTracks(RendererCapabilities[], TrackGroupArray, MediaPeriodId, Timeline)}
* operation.
*/
/* package */ final TrackSelectorResult emptyTrackSelectorResult;
/* package */ final Commands permanentAvailableCommands;
private final ConditionVariable constructorFinished;
private final Context applicationContext;
private final Player wrappingPlayer;
private final Renderer[] renderers;
private final TrackSelector trackSelector;
private final HandlerWrapper playbackInfoUpdateHandler;
private final ExoPlayerImplInternal.PlaybackInfoUpdateListener playbackInfoUpdateListener;
private final ExoPlayerImplInternal internalPlayer;
private final ListenerSet<Listener> listeners;
private final CopyOnWriteArraySet<AudioOffloadListener> audioOffloadListeners;
private final Timeline.Period period;
private final List<MediaSourceHolderSnapshot> mediaSourceHolderSnapshots;
private final boolean useLazyPreparation;
private final MediaSource.Factory mediaSourceFactory;
private final AnalyticsCollector analyticsCollector;
private final Looper applicationLooper;
private final BandwidthMeter bandwidthMeter;
private final long seekBackIncrementMs;
private final long seekForwardIncrementMs;
private final Clock clock;
private final ComponentListener componentListener;
private final FrameMetadataListener frameMetadataListener;
private final AudioBecomingNoisyManager audioBecomingNoisyManager;
private final AudioFocusManager audioFocusManager;
private final StreamVolumeManager streamVolumeManager;
private final WakeLockManager wakeLockManager;
private final WifiLockManager wifiLockManager;
private final long detachSurfaceTimeoutMs;
private @RepeatMode int repeatMode;
private boolean shuffleModeEnabled;
private int pendingOperationAcks;
private @DiscontinuityReason int pendingDiscontinuityReason;
private boolean pendingDiscontinuity;
private @PlayWhenReadyChangeReason int pendingPlayWhenReadyChangeReason;
private boolean foregroundMode;
private SeekParameters seekParameters;
private ShuffleOrder shuffleOrder;
private boolean pauseAtEndOfMediaItems;
private Commands availableCommands;
private MediaMetadata mediaMetadata;
private MediaMetadata playlistMetadata;
@Nullable private Format videoFormat;
@Nullable private Format audioFormat;
@Nullable private AudioTrack keepSessionIdAudioTrack;
@Nullable private Object videoOutput;
@Nullable private Surface ownedSurface;
@Nullable private SurfaceHolder surfaceHolder;
@Nullable private SphericalGLSurfaceView sphericalGLSurfaceView;
private boolean surfaceHolderSurfaceIsVideoOutput;
@Nullable private TextureView textureView;
private @C.VideoScalingMode int videoScalingMode;
private @C.VideoChangeFrameRateStrategy int videoChangeFrameRateStrategy;
private Size surfaceSize;
@Nullable private DecoderCounters videoDecoderCounters;
@Nullable private DecoderCounters audioDecoderCounters;
private int audioSessionId;
private AudioAttributes audioAttributes;
private float volume;
private boolean skipSilenceEnabled;
private CueGroup currentCueGroup;
@Nullable private VideoFrameMetadataListener videoFrameMetadataListener;
@Nullable private CameraMotionListener cameraMotionListener;
private boolean throwsWhenUsingWrongThread;
private boolean hasNotifiedFullWrongThreadWarning;
@Nullable private PriorityTaskManager priorityTaskManager;
private boolean isPriorityTaskManagerRegistered;
private boolean playerReleased;
private DeviceInfo deviceInfo;
private VideoSize videoSize;
// MediaMetadata built from static (TrackGroup Format) and dynamic (onMetadata(Metadata)) metadata
// sources.
private MediaMetadata staticAndDynamicMediaMetadata;
// Playback information when there is no pending seek/set source operation.
private PlaybackInfo playbackInfo;
// Playback information when there is a pending seek/set source operation.
private int maskingWindowIndex;
private int maskingPeriodIndex;
private long maskingWindowPositionMs;
private DispatchQueue workerQueue;
@SuppressLint("HandlerLeak")
public ExoPlayerImpl(ExoPlayer.Builder builder, @Nullable Player wrappingPlayer) {
constructorFinished = new ConditionVariable();
try {
Log.i(
TAG,
"Init "
+ Integer.toHexString(System.identityHashCode(this))
+ " ["
+ ExoPlayerLibraryInfo.VERSION_SLASHY
+ "] ["
+ Util.DEVICE_DEBUG_INFO
+ "]");
applicationContext = builder.context.getApplicationContext();
analyticsCollector = builder.analyticsCollectorFunction.apply(builder.clock);
priorityTaskManager = builder.priorityTaskManager;
audioAttributes = builder.audioAttributes;
videoScalingMode = builder.videoScalingMode;
videoChangeFrameRateStrategy = builder.videoChangeFrameRateStrategy;
skipSilenceEnabled = builder.skipSilenceEnabled;
detachSurfaceTimeoutMs = builder.detachSurfaceTimeoutMs;
componentListener = new ComponentListener();
frameMetadataListener = new FrameMetadataListener();
Handler eventHandler = new Handler(builder.looper);
renderers =
builder
.renderersFactorySupplier
.get()
.createRenderers(
eventHandler,
componentListener,
componentListener,
componentListener,
componentListener);
checkState(renderers.length > 0);
this.trackSelector = builder.trackSelectorSupplier.get();
this.mediaSourceFactory = builder.mediaSourceFactorySupplier.get();
this.bandwidthMeter = builder.bandwidthMeterSupplier.get();
this.useLazyPreparation = builder.useLazyPreparation;
this.seekParameters = builder.seekParameters;
this.seekBackIncrementMs = builder.seekBackIncrementMs;
this.seekForwardIncrementMs = builder.seekForwardIncrementMs;
this.pauseAtEndOfMediaItems = builder.pauseAtEndOfMediaItems;
this.applicationLooper = builder.looper;
this.clock = builder.clock;
this.wrappingPlayer = wrappingPlayer == null ? this : wrappingPlayer;
listeners =
new ListenerSet<>(
applicationLooper,
clock,
(listener, flags) -> listener.onEvents(this.wrappingPlayer, new Events(flags)));
audioOffloadListeners = new CopyOnWriteArraySet<>();
mediaSourceHolderSnapshots = new ArrayList<>();
shuffleOrder = new ShuffleOrder.DefaultShuffleOrder(/* length= */ 0);
emptyTrackSelectorResult =
new TrackSelectorResult(
new RendererConfiguration[renderers.length],
new ExoTrackSelection[renderers.length],
Tracks.EMPTY,
/* info= */ null);
period = new Timeline.Period();
permanentAvailableCommands =
new Commands.Builder()
.addAll(
COMMAND_PLAY_PAUSE,
COMMAND_PREPARE,
COMMAND_STOP,
COMMAND_SET_SPEED_AND_PITCH,
COMMAND_SET_SHUFFLE_MODE,
COMMAND_SET_REPEAT_MODE,
COMMAND_GET_CURRENT_MEDIA_ITEM,
COMMAND_GET_TIMELINE,
COMMAND_GET_MEDIA_ITEMS_METADATA,
COMMAND_SET_MEDIA_ITEMS_METADATA,
COMMAND_SET_MEDIA_ITEM,
COMMAND_CHANGE_MEDIA_ITEMS,
COMMAND_GET_TRACKS,
COMMAND_GET_AUDIO_ATTRIBUTES,
COMMAND_GET_VOLUME,
COMMAND_GET_DEVICE_VOLUME,
COMMAND_SET_VOLUME,
COMMAND_SET_DEVICE_VOLUME,
COMMAND_ADJUST_DEVICE_VOLUME,
COMMAND_SET_VIDEO_SURFACE,
COMMAND_GET_TEXT)
.addIf(
COMMAND_SET_TRACK_SELECTION_PARAMETERS, trackSelector.isSetParametersSupported())
.build();
availableCommands =
new Commands.Builder()
.addAll(permanentAvailableCommands)
.add(COMMAND_SEEK_TO_DEFAULT_POSITION)
.add(COMMAND_SEEK_TO_MEDIA_ITEM)
.build();
playbackInfoUpdateHandler = clock.createHandler(applicationLooper, /* callback= */ null);
playbackInfoUpdateListener =
playbackInfoUpdate ->
playbackInfoUpdateHandler.post(() -> handlePlaybackInfo(playbackInfoUpdate));
playbackInfo = PlaybackInfo.createDummy(emptyTrackSelectorResult);
analyticsCollector.setPlayer(this.wrappingPlayer, applicationLooper);
PlayerId playerId =
Util.SDK_INT < 31
? new PlayerId()
: Api31.registerMediaMetricsListener(
applicationContext, /* player= */ this, builder.usePlatformDiagnostics);
internalPlayer =
new ExoPlayerImplInternal(
renderers,
trackSelector,
emptyTrackSelectorResult,
builder.loadControlSupplier.get(),
bandwidthMeter,
repeatMode,
shuffleModeEnabled,
analyticsCollector,
seekParameters,
builder.livePlaybackSpeedControl,
builder.releaseTimeoutMs,
pauseAtEndOfMediaItems,
applicationLooper,
clock,
playbackInfoUpdateListener,
playerId,
builder.playbackLooper);
volume = 1;
repeatMode = Player.REPEAT_MODE_OFF;
mediaMetadata = MediaMetadata.EMPTY;
playlistMetadata = MediaMetadata.EMPTY;
staticAndDynamicMediaMetadata = MediaMetadata.EMPTY;
maskingWindowIndex = C.INDEX_UNSET;
if (Util.SDK_INT < 21) {
audioSessionId = initializeKeepSessionIdAudioTrack(C.AUDIO_SESSION_ID_UNSET);
} else {
audioSessionId = Util.generateAudioSessionIdV21(applicationContext);
}
currentCueGroup = CueGroup.EMPTY_TIME_ZERO;
throwsWhenUsingWrongThread = true;
addListener(analyticsCollector);
bandwidthMeter.addEventListener(new Handler(applicationLooper), analyticsCollector);
addAudioOffloadListener(componentListener);
if (builder.foregroundModeTimeoutMs > 0) {
internalPlayer.experimentalSetForegroundModeTimeoutMs(builder.foregroundModeTimeoutMs);
}
audioBecomingNoisyManager =
new AudioBecomingNoisyManager(builder.context, eventHandler, componentListener);
audioBecomingNoisyManager.setEnabled(builder.handleAudioBecomingNoisy);
audioFocusManager = new AudioFocusManager(builder.context, eventHandler, componentListener);
audioFocusManager.setAudioAttributes(builder.handleAudioFocus ? audioAttributes : null);
streamVolumeManager =
new StreamVolumeManager(builder.context, eventHandler, componentListener);
streamVolumeManager.setStreamType(Util.getStreamTypeForAudioUsage(audioAttributes.usage));
wakeLockManager = new WakeLockManager(builder.context);
wakeLockManager.setEnabled(builder.wakeMode != C.WAKE_MODE_NONE);
wifiLockManager = new WifiLockManager(builder.context);
wifiLockManager.setEnabled(builder.wakeMode == C.WAKE_MODE_NETWORK);
deviceInfo = createDeviceInfo(streamVolumeManager);
videoSize = VideoSize.UNKNOWN;
surfaceSize = Size.UNKNOWN;
trackSelector.setAudioAttributes(audioAttributes);
sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_AUDIO_SESSION_ID, audioSessionId);
sendRendererMessage(TRACK_TYPE_VIDEO, MSG_SET_AUDIO_SESSION_ID, audioSessionId);
sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_AUDIO_ATTRIBUTES, audioAttributes);
sendRendererMessage(TRACK_TYPE_VIDEO, MSG_SET_SCALING_MODE, videoScalingMode);
sendRendererMessage(
TRACK_TYPE_VIDEO, MSG_SET_CHANGE_FRAME_RATE_STRATEGY, videoChangeFrameRateStrategy);
sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_SKIP_SILENCE_ENABLED, skipSilenceEnabled);
sendRendererMessage(
TRACK_TYPE_VIDEO, MSG_SET_VIDEO_FRAME_METADATA_LISTENER, frameMetadataListener);
sendRendererMessage(
TRACK_TYPE_CAMERA_MOTION, MSG_SET_CAMERA_MOTION_LISTENER, frameMetadataListener);
} finally {
constructorFinished.open();
}
}
@CanIgnoreReturnValue
@SuppressWarnings("deprecation") // Returning deprecated class.
@Override
@Deprecated
public AudioComponent getAudioComponent() {
verifyApplicationThread();
return this;
}
@CanIgnoreReturnValue
@SuppressWarnings("deprecation") // Returning deprecated class.
@Override
@Deprecated
public VideoComponent getVideoComponent() {
verifyApplicationThread();
return this;
}
@CanIgnoreReturnValue
@SuppressWarnings("deprecation") // Returning deprecated class.
@Override
@Deprecated
public TextComponent getTextComponent() {
verifyApplicationThread();
return this;
}
@CanIgnoreReturnValue
@SuppressWarnings("deprecation") // Returning deprecated class.
@Override
@Deprecated
public DeviceComponent getDeviceComponent() {
verifyApplicationThread();
return this;
}
@Override
public void experimentalSetOffloadSchedulingEnabled(boolean offloadSchedulingEnabled) {
verifyApplicationThread();
internalPlayer.experimentalSetOffloadSchedulingEnabled(offloadSchedulingEnabled);
for (AudioOffloadListener listener : audioOffloadListeners) {
listener.onExperimentalOffloadSchedulingEnabledChanged(offloadSchedulingEnabled);
}
}
@Override
public boolean experimentalIsSleepingForOffload() {
verifyApplicationThread();
return playbackInfo.sleepingForOffload;
}
@Override
public Looper getPlaybackLooper() {
// Don't verify application thread. We allow calls to this method from any thread.
return internalPlayer.getPlaybackLooper();
}
@Override
public Looper getApplicationLooper() {
// Don't verify application thread. We allow calls to this method from any thread.
return applicationLooper;
}
@Override
public Clock getClock() {
// Don't verify application thread. We allow calls to this method from any thread.
return clock;
}
@Override
public void addAudioOffloadListener(AudioOffloadListener listener) {
// Don't verify application thread. We allow calls to this method from any thread.
audioOffloadListeners.add(listener);
}
@Override
public void removeAudioOffloadListener(AudioOffloadListener listener) {
verifyApplicationThread();
audioOffloadListeners.remove(listener);
}
@Override
public Commands getAvailableCommands() {
verifyApplicationThread();
return availableCommands;
}
@Override
public @State int getPlaybackState() {
verifyApplicationThread();
return playbackInfo.playbackState;
}
@Override
public @PlaybackSuppressionReason int getPlaybackSuppressionReason() {
verifyApplicationThread();
return playbackInfo.playbackSuppressionReason;
}
@Override
public void setWorkerQueue(DispatchQueue dispatchQueue) {
workerQueue = dispatchQueue;
}
@Override
@Nullable
public ExoPlaybackException getPlayerError() {
verifyApplicationThread();
return playbackInfo.playbackError;
}
@Override
@Deprecated
public void retry() {
verifyApplicationThread();
prepare();
}
@Override
public void prepare() {
verifyApplicationThread();
boolean playWhenReady = getPlayWhenReady();
@AudioFocusManager.PlayerCommand
int playerCommand = audioFocusManager.updateAudioFocus(playWhenReady, Player.STATE_BUFFERING);
updatePlayWhenReady(
playWhenReady, playerCommand, getPlayWhenReadyChangeReason(playWhenReady, playerCommand));
if (playbackInfo.playbackState != Player.STATE_IDLE) {
return;
}
PlaybackInfo playbackInfo = this.playbackInfo.copyWithPlaybackError(null);
playbackInfo =
playbackInfo.copyWithPlaybackState(
playbackInfo.timeline.isEmpty() ? STATE_ENDED : STATE_BUFFERING);
// Trigger internal prepare first before updating the playback info and notifying external
// listeners to ensure that new operations issued in the listener notifications reach the
// player after this prepare. The internal player can't change the playback info immediately
// because it uses a callback.
pendingOperationAcks++;
internalPlayer.prepare();
updatePlaybackInfo(
playbackInfo,
/* ignored */ TIMELINE_CHANGE_REASON_SOURCE_UPDATE,
/* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST,
/* seekProcessed= */ false,
/* positionDiscontinuity= */ false,
/* ignored */ DISCONTINUITY_REASON_INTERNAL,
/* ignored */ C.TIME_UNSET,
/* ignored */ C.INDEX_UNSET,
/* repeatCurrentMediaItem= */ false);
}
@Override
@Deprecated
public void prepare(MediaSource mediaSource) {
verifyApplicationThread();
setMediaSource(mediaSource);
prepare();
}
@Override
@Deprecated
public void prepare(MediaSource mediaSource, boolean resetPosition, boolean resetState) {
verifyApplicationThread();
setMediaSource(mediaSource, resetPosition);
prepare();
}
@Override
public void setMediaItems(List<MediaItem> mediaItems, boolean resetPosition) {
verifyApplicationThread();
setMediaSources(createMediaSources(mediaItems), resetPosition);
}
@Override
public void setMediaItems(List<MediaItem> mediaItems, int startIndex, long startPositionMs) {
verifyApplicationThread();
setMediaSources(createMediaSources(mediaItems), startIndex, startPositionMs);
}
@Override
public void setMediaSource(MediaSource mediaSource) {
verifyApplicationThread();
setMediaSources(Collections.singletonList(mediaSource));
}
@Override
public void setMediaSource(MediaSource mediaSource, long startPositionMs) {
verifyApplicationThread();
setMediaSources(
Collections.singletonList(mediaSource), /* startWindowIndex= */ 0, startPositionMs);
}
@Override
public void setMediaSource(MediaSource mediaSource, boolean resetPosition) {
verifyApplicationThread();
setMediaSources(Collections.singletonList(mediaSource), resetPosition);
}
@Override
public void setMediaSources(List<MediaSource> mediaSources) {
verifyApplicationThread();
setMediaSources(mediaSources, /* resetPosition= */ true);
}
@Override
public void setMediaSources(List<MediaSource> mediaSources, boolean resetPosition) {
verifyApplicationThread();
setMediaSourcesInternal(
mediaSources,
/* startWindowIndex= */ C.INDEX_UNSET,
/* startPositionMs= */ C.TIME_UNSET,
/* resetToDefaultPosition= */ resetPosition);
}
@Override
public void setMediaSources(
List<MediaSource> mediaSources, int startWindowIndex, long startPositionMs) {
verifyApplicationThread();
setMediaSourcesInternal(
mediaSources, startWindowIndex, startPositionMs, /* resetToDefaultPosition= */ false);
}
@Override
public void addMediaItems(int index, List<MediaItem> mediaItems) {
verifyApplicationThread();
addMediaSources(index, createMediaSources(mediaItems));
}
@Override
public void addMediaSource(MediaSource mediaSource) {
verifyApplicationThread();
addMediaSources(Collections.singletonList(mediaSource));
}
@Override
public void addMediaSource(int index, MediaSource mediaSource) {
verifyApplicationThread();
addMediaSources(index, Collections.singletonList(mediaSource));
}
@Override
public void addMediaSources(List<MediaSource> mediaSources) {
verifyApplicationThread();
addMediaSources(/* index= */ mediaSourceHolderSnapshots.size(), mediaSources);
}
@Override
public void addMediaSources(int index, List<MediaSource> mediaSources) {
verifyApplicationThread();
checkArgument(index >= 0);
index = min(index, mediaSourceHolderSnapshots.size());
Timeline oldTimeline = getCurrentTimeline();
pendingOperationAcks++;
List<MediaSourceList.MediaSourceHolder> holders = addMediaSourceHolders(index, mediaSources);
Timeline newTimeline = createMaskingTimeline();
PlaybackInfo newPlaybackInfo =
maskTimelineAndPosition(
playbackInfo,
newTimeline,
getPeriodPositionUsAfterTimelineChanged(oldTimeline, newTimeline));
internalPlayer.addMediaSources(index, holders, shuffleOrder);
updatePlaybackInfo(
newPlaybackInfo,
/* timelineChangeReason= */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED,
/* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST,
/* seekProcessed= */ false,
/* positionDiscontinuity= */ false,
/* ignored */ DISCONTINUITY_REASON_INTERNAL,
/* ignored */ C.TIME_UNSET,
/* ignored */ C.INDEX_UNSET,
/* repeatCurrentMediaItem= */ false);
}
@Override
public void removeMediaItems(int fromIndex, int toIndex) {
verifyApplicationThread();
checkArgument(fromIndex >= 0 && toIndex >= fromIndex);
int playlistSize = mediaSourceHolderSnapshots.size();
toIndex = min(toIndex, playlistSize);
if (fromIndex >= playlistSize || fromIndex == toIndex) {
// Do nothing.
return;
}
PlaybackInfo newPlaybackInfo = removeMediaItemsInternal(fromIndex, toIndex);
boolean positionDiscontinuity =
!newPlaybackInfo.periodId.periodUid.equals(playbackInfo.periodId.periodUid);
updatePlaybackInfo(
newPlaybackInfo,
/* timelineChangeReason= */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED,
/* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST,
/* seekProcessed= */ false,
positionDiscontinuity,
DISCONTINUITY_REASON_REMOVE,
/* discontinuityWindowStartPositionUs= */ getCurrentPositionUsInternal(newPlaybackInfo),
/* ignored */ C.INDEX_UNSET,
/* repeatCurrentMediaItem= */ false);
}
@Override
public void moveMediaItems(int fromIndex, int toIndex, int newFromIndex) {
verifyApplicationThread();
checkArgument(fromIndex >= 0 && fromIndex <= toIndex && newFromIndex >= 0);
int playlistSize = mediaSourceHolderSnapshots.size();
toIndex = min(toIndex, playlistSize);
newFromIndex = min(newFromIndex, playlistSize - (toIndex - fromIndex));
if (fromIndex >= playlistSize || fromIndex == toIndex || fromIndex == newFromIndex) {
// Do nothing.
return;
}
Timeline oldTimeline = getCurrentTimeline();
pendingOperationAcks++;
Util.moveItems(mediaSourceHolderSnapshots, fromIndex, toIndex, newFromIndex);
Timeline newTimeline = createMaskingTimeline();
PlaybackInfo newPlaybackInfo =
maskTimelineAndPosition(
playbackInfo,
newTimeline,
getPeriodPositionUsAfterTimelineChanged(oldTimeline, newTimeline));
internalPlayer.moveMediaSources(fromIndex, toIndex, newFromIndex, shuffleOrder);
updatePlaybackInfo(
newPlaybackInfo,
/* timelineChangeReason= */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED,
/* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST,
/* seekProcessed= */ false,
/* positionDiscontinuity= */ false,
/* ignored */ DISCONTINUITY_REASON_INTERNAL,
/* ignored */ C.TIME_UNSET,
/* ignored */ C.INDEX_UNSET,
/* repeatCurrentMediaItem= */ false);
}
@Override
public void setShuffleOrder(ShuffleOrder shuffleOrder) {
verifyApplicationThread();
this.shuffleOrder = shuffleOrder;
Timeline timeline = createMaskingTimeline();
PlaybackInfo newPlaybackInfo =
maskTimelineAndPosition(
playbackInfo,
timeline,
maskWindowPositionMsOrGetPeriodPositionUs(
timeline, getCurrentMediaItemIndex(), getCurrentPosition()));
pendingOperationAcks++;
internalPlayer.setShuffleOrder(shuffleOrder);
updatePlaybackInfo(
newPlaybackInfo,
/* timelineChangeReason= */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED,
/* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST,
/* seekProcessed= */ false,
/* positionDiscontinuity= */ false,
/* ignored */ DISCONTINUITY_REASON_INTERNAL,
/* ignored */ C.TIME_UNSET,
/* ignored */ C.INDEX_UNSET,
/* repeatCurrentMediaItem= */ false);
}
@Override
public void setPauseAtEndOfMediaItems(boolean pauseAtEndOfMediaItems) {
verifyApplicationThread();
if (this.pauseAtEndOfMediaItems == pauseAtEndOfMediaItems) {
return;
}
this.pauseAtEndOfMediaItems = pauseAtEndOfMediaItems;
internalPlayer.setPauseAtEndOfWindow(pauseAtEndOfMediaItems);
}
@Override
public boolean getPauseAtEndOfMediaItems() {
verifyApplicationThread();
return pauseAtEndOfMediaItems;
}
@Override
public void setPlayWhenReady(boolean playWhenReady) {
verifyApplicationThread();
@AudioFocusManager.PlayerCommand
int playerCommand = audioFocusManager.updateAudioFocus(playWhenReady, getPlaybackState());
updatePlayWhenReady(
playWhenReady, playerCommand, getPlayWhenReadyChangeReason(playWhenReady, playerCommand));
}
@Override
public boolean getPlayWhenReady() {
verifyApplicationThread();
return playbackInfo.playWhenReady;
}
@Override
public void setRepeatMode(@RepeatMode int repeatMode) {
verifyApplicationThread();
if (this.repeatMode != repeatMode) {
this.repeatMode = repeatMode;
internalPlayer.setRepeatMode(repeatMode);
listeners.queueEvent(
Player.EVENT_REPEAT_MODE_CHANGED, listener -> listener.onRepeatModeChanged(repeatMode));
updateAvailableCommands();
listeners.flushEvents();
}
}
@Override
public @RepeatMode int getRepeatMode() {
verifyApplicationThread();
return repeatMode;
}
@Override
public void setShuffleModeEnabled(boolean shuffleModeEnabled) {
verifyApplicationThread();
if (this.shuffleModeEnabled != shuffleModeEnabled) {
this.shuffleModeEnabled = shuffleModeEnabled;
internalPlayer.setShuffleModeEnabled(shuffleModeEnabled);
listeners.queueEvent(
Player.EVENT_SHUFFLE_MODE_ENABLED_CHANGED,
listener -> listener.onShuffleModeEnabledChanged(shuffleModeEnabled));
updateAvailableCommands();
listeners.flushEvents();
}
}
@Override
public boolean getShuffleModeEnabled() {
verifyApplicationThread();
return shuffleModeEnabled;
}
@Override
public boolean isLoading() {
verifyApplicationThread();
return playbackInfo.isLoading;
}
@Override
public void seekTo(
int mediaItemIndex,
long positionMs,
@Player.Command int seekCommand,
boolean isRepeatingCurrentItem) {
verifyApplicationThread();
checkArgument(mediaItemIndex >= 0);
analyticsCollector.notifySeekStarted();
Timeline timeline = playbackInfo.timeline;
if (!timeline.isEmpty() && mediaItemIndex >= timeline.getWindowCount()) {
return;
}
pendingOperationAcks++;
if (isPlayingAd()) {
// TODO: Investigate adding support for seeking during ads. This is complicated to do in
// general because the midroll ad preceding the seek destination must be played before the
// content position can be played, if a different ad is playing at the moment.
Log.w(TAG, "seekTo ignored because an ad is playing");
ExoPlayerImplInternal.PlaybackInfoUpdate playbackInfoUpdate =
new ExoPlayerImplInternal.PlaybackInfoUpdate(this.playbackInfo);
playbackInfoUpdate.incrementPendingOperationAcks(1);
playbackInfoUpdateListener.onPlaybackInfoUpdate(playbackInfoUpdate);
return;
}
@Player.State
int newPlaybackState =
getPlaybackState() == Player.STATE_IDLE ? Player.STATE_IDLE : STATE_BUFFERING;
int oldMaskingMediaItemIndex = getCurrentMediaItemIndex();
PlaybackInfo newPlaybackInfo = playbackInfo.copyWithPlaybackState(newPlaybackState);
newPlaybackInfo =
maskTimelineAndPosition(
newPlaybackInfo,
timeline,
maskWindowPositionMsOrGetPeriodPositionUs(timeline, mediaItemIndex, positionMs));
internalPlayer.seekTo(timeline, mediaItemIndex, Util.msToUs(positionMs));
updatePlaybackInfo(
newPlaybackInfo,
/* ignored */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED,
/* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST,
/* seekProcessed= */ true,
/* positionDiscontinuity= */ true,
/* positionDiscontinuityReason= */ DISCONTINUITY_REASON_SEEK,
/* discontinuityWindowStartPositionUs= */ getCurrentPositionUsInternal(newPlaybackInfo),
oldMaskingMediaItemIndex,
isRepeatingCurrentItem);
}
@Override
public long getSeekBackIncrement() {
verifyApplicationThread();
return seekBackIncrementMs;
}
@Override
public long getSeekForwardIncrement() {
verifyApplicationThread();
return seekForwardIncrementMs;
}
@Override
public long getMaxSeekToPreviousPosition() {
verifyApplicationThread();
return C.DEFAULT_MAX_SEEK_TO_PREVIOUS_POSITION_MS;
}
@Override
public void setPlaybackParameters(PlaybackParameters playbackParameters) {
verifyApplicationThread();
if (playbackParameters == null) {
playbackParameters = PlaybackParameters.DEFAULT;
}
if (playbackInfo.playbackParameters.equals(playbackParameters)) {
return;
}
PlaybackInfo newPlaybackInfo = playbackInfo.copyWithPlaybackParameters(playbackParameters);
pendingOperationAcks++;
internalPlayer.setPlaybackParameters(playbackParameters);
updatePlaybackInfo(
newPlaybackInfo,
/* ignored */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED,
/* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST,
/* seekProcessed= */ false,
/* positionDiscontinuity= */ false,
/* ignored */ DISCONTINUITY_REASON_INTERNAL,
/* ignored */ C.TIME_UNSET,
/* ignored */ C.INDEX_UNSET,
/* repeatCurrentMediaItem= */ false);
}
@Override
public PlaybackParameters getPlaybackParameters() {
verifyApplicationThread();
return playbackInfo.playbackParameters;
}
@Override
public void setSeekParameters(@Nullable SeekParameters seekParameters) {
verifyApplicationThread();
if (seekParameters == null) {
seekParameters = SeekParameters.DEFAULT;
}
if (!this.seekParameters.equals(seekParameters)) {
this.seekParameters = seekParameters;
internalPlayer.setSeekParameters(seekParameters);
}
}
@Override
public SeekParameters getSeekParameters() {
verifyApplicationThread();
return seekParameters;
}
@Override
public void setForegroundMode(boolean foregroundMode) {
verifyApplicationThread();
if (this.foregroundMode != foregroundMode) {
this.foregroundMode = foregroundMode;
if (!internalPlayer.setForegroundMode(foregroundMode)) {
// One of the renderers timed out releasing its resources.
stopInternal(
/* reset= */ false,
ExoPlaybackException.createForUnexpected(
new ExoTimeoutException(ExoTimeoutException.TIMEOUT_OPERATION_SET_FOREGROUND_MODE),
PlaybackException.ERROR_CODE_TIMEOUT));
}
}
}
@Override
public void stop() {
verifyApplicationThread();
stop(/* reset= */ false);
}
@Override
public void stop(boolean reset) {
verifyApplicationThread();
audioFocusManager.updateAudioFocus(getPlayWhenReady(), Player.STATE_IDLE);
stopInternal(reset, /* error= */ null);
currentCueGroup = new CueGroup(ImmutableList.of(), playbackInfo.positionUs);
}
@Override
public void release() {
Log.i(
TAG,
"Release "
+ Integer.toHexString(System.identityHashCode(this))
+ " ["
+ ExoPlayerLibraryInfo.VERSION_SLASHY
+ "] ["
+ Util.DEVICE_DEBUG_INFO
+ "] ["
+ ExoPlayerLibraryInfo.registeredModules()
+ "]");
verifyApplicationThread();
if (Util.SDK_INT < 21 && keepSessionIdAudioTrack != null) {
keepSessionIdAudioTrack.release();
keepSessionIdAudioTrack = null;
}
audioBecomingNoisyManager.setEnabled(false);
streamVolumeManager.release();
wakeLockManager.setStayAwake(false);
wifiLockManager.setStayAwake(false);
audioFocusManager.release();
if (!internalPlayer.release()) {
// One of the renderers timed out releasing its resources.
listeners.sendEvent(
Player.EVENT_PLAYER_ERROR,
listener ->
listener.onPlayerError(
ExoPlaybackException.createForUnexpected(
new ExoTimeoutException(ExoTimeoutException.TIMEOUT_OPERATION_RELEASE),
PlaybackException.ERROR_CODE_TIMEOUT)));
}
listeners.release();
playbackInfoUpdateHandler.removeCallbacksAndMessages(null);
bandwidthMeter.removeEventListener(analyticsCollector);
playbackInfo = playbackInfo.copyWithPlaybackState(Player.STATE_IDLE);
playbackInfo = playbackInfo.copyWithLoadingMediaPeriodId(playbackInfo.periodId);
playbackInfo.bufferedPositionUs = playbackInfo.positionUs;
playbackInfo.totalBufferedDurationUs = 0;
analyticsCollector.release();
trackSelector.release();
removeSurfaceCallbacks();
if (ownedSurface != null) {
ownedSurface.release();
ownedSurface = null;
}
if (isPriorityTaskManagerRegistered) {
checkNotNull(priorityTaskManager).remove(C.PRIORITY_PLAYBACK);
isPriorityTaskManagerRegistered = false;
}
currentCueGroup = CueGroup.EMPTY_TIME_ZERO;
playerReleased = true;
}
@Override
public PlayerMessage createMessage(Target target) {
verifyApplicationThread();
return createMessageInternal(target);
}
@Override
public int getCurrentPeriodIndex() {
verifyApplicationThread();
if (playbackInfo.timeline.isEmpty()) {
return maskingPeriodIndex;
} else {
return playbackInfo.timeline.getIndexOfPeriod(playbackInfo.periodId.periodUid);
}
}
@Override
public int getCurrentMediaItemIndex() {
verifyApplicationThread();
int currentWindowIndex = getCurrentWindowIndexInternal();
return currentWindowIndex == C.INDEX_UNSET ? 0 : currentWindowIndex;
}
@Override
public long getDuration() {
verifyApplicationThread();
if (isPlayingAd()) {
MediaPeriodId periodId = playbackInfo.periodId;
playbackInfo.timeline.getPeriodByUid(periodId.periodUid, period);
long adDurationUs = period.getAdDurationUs(periodId.adGroupIndex, periodId.adIndexInAdGroup);
return Util.usToMs(adDurationUs);
}
return getContentDuration();
}
@Override
public long getCurrentPosition() {
verifyApplicationThread();
return Util.usToMs(getCurrentPositionUsInternal(playbackInfo));
}
@Override
public long getBufferedPosition() {
verifyApplicationThread();
if (isPlayingAd()) {
return playbackInfo.loadingMediaPeriodId.equals(playbackInfo.periodId)
? Util.usToMs(playbackInfo.bufferedPositionUs)
: getDuration();
}
return getContentBufferedPosition();
}
@Override
public long getTotalBufferedDuration() {
verifyApplicationThread();
return Util.usToMs(playbackInfo.totalBufferedDurationUs);
}
@Override
public boolean isPlayingAd() {
verifyApplicationThread();
return playbackInfo.periodId.isAd();
}
@Override
public int getCurrentAdGroupIndex() {
verifyApplicationThread();
return isPlayingAd() ? playbackInfo.periodId.adGroupIndex : C.INDEX_UNSET;
}
@Override
public int getCurrentAdIndexInAdGroup() {
verifyApplicationThread();
return isPlayingAd() ? playbackInfo.periodId.adIndexInAdGroup : C.INDEX_UNSET;
}
@Override
public long getContentPosition() {
verifyApplicationThread();
if (isPlayingAd()) {
playbackInfo.timeline.getPeriodByUid(playbackInfo.periodId.periodUid, period);
return playbackInfo.requestedContentPositionUs == C.TIME_UNSET
? playbackInfo
.timeline
.getWindow(getCurrentMediaItemIndex(), window)
.getDefaultPositionMs()
: period.getPositionInWindowMs() + Util.usToMs(playbackInfo.requestedContentPositionUs);
} else {
return getCurrentPosition();
}
}
@Override
public long getContentBufferedPosition() {
verifyApplicationThread();
if (playbackInfo.timeline.isEmpty()) {
return maskingWindowPositionMs;
}
if (playbackInfo.loadingMediaPeriodId.windowSequenceNumber
!= playbackInfo.periodId.windowSequenceNumber) {
return playbackInfo.timeline.getWindow(getCurrentMediaItemIndex(), window).getDurationMs();
}
long contentBufferedPositionUs = playbackInfo.bufferedPositionUs;
if (playbackInfo.loadingMediaPeriodId.isAd()) {
Timeline.Period loadingPeriod =
playbackInfo.timeline.getPeriodByUid(playbackInfo.loadingMediaPeriodId.periodUid, period);
contentBufferedPositionUs =
loadingPeriod.getAdGroupTimeUs(playbackInfo.loadingMediaPeriodId.adGroupIndex);
if (contentBufferedPositionUs == C.TIME_END_OF_SOURCE) {
contentBufferedPositionUs = loadingPeriod.durationUs;
}
}
return Util.usToMs(
periodPositionUsToWindowPositionUs(
playbackInfo.timeline, playbackInfo.loadingMediaPeriodId, contentBufferedPositionUs));
}
@Override
public int getRendererCount() {
verifyApplicationThread();
return renderers.length;
}
@Override
public @C.TrackType int getRendererType(int index) {
verifyApplicationThread();
return renderers[index].getTrackType();
}
@Override
public Renderer getRenderer(int index) {
verifyApplicationThread();
return renderers[index];
}
@Override
public TrackSelector getTrackSelector() {
verifyApplicationThread();
return trackSelector;
}
@Override
public TrackGroupArray getCurrentTrackGroups() {
verifyApplicationThread();
return playbackInfo.trackGroups;
}
@Override
public TrackSelectionArray getCurrentTrackSelections() {
verifyApplicationThread();
return new TrackSelectionArray(playbackInfo.trackSelectorResult.selections);
}
@Override
public Tracks getCurrentTracks() {
verifyApplicationThread();
return playbackInfo.trackSelectorResult.tracks;
}
@Override
public TrackSelectionParameters getTrackSelectionParameters() {
verifyApplicationThread();
return trackSelector.getParameters();
}
@Override
public void setTrackSelectionParameters(TrackSelectionParameters parameters) {
verifyApplicationThread();
if (!trackSelector.isSetParametersSupported()
|| parameters.equals(trackSelector.getParameters())) {
return;
}
trackSelector.setParameters(parameters);
listeners.sendEvent(
EVENT_TRACK_SELECTION_PARAMETERS_CHANGED,
listener -> listener.onTrackSelectionParametersChanged(parameters));
}
@Override
public MediaMetadata getMediaMetadata() {
verifyApplicationThread();
return mediaMetadata;
}
@Override
public MediaMetadata getPlaylistMetadata() {
verifyApplicationThread();
return playlistMetadata;
}
@Override
public void setPlaylistMetadata(MediaMetadata playlistMetadata) {
verifyApplicationThread();
checkNotNull(playlistMetadata);
if (playlistMetadata.equals(this.playlistMetadata)) {
return;
}
this.playlistMetadata = playlistMetadata;
listeners.sendEvent(
EVENT_PLAYLIST_METADATA_CHANGED,
listener -> listener.onPlaylistMetadataChanged(this.playlistMetadata));
}
@Override
public Timeline getCurrentTimeline() {
verifyApplicationThread();
return playbackInfo.timeline;
}
@Override
public void setVideoScalingMode(@C.VideoScalingMode int videoScalingMode) {
verifyApplicationThread();
this.videoScalingMode = videoScalingMode;
sendRendererMessage(TRACK_TYPE_VIDEO, MSG_SET_SCALING_MODE, videoScalingMode);
}
@Override
public @C.VideoScalingMode int getVideoScalingMode() {
verifyApplicationThread();
return videoScalingMode;
}
@Override
public void setVideoChangeFrameRateStrategy(
@C.VideoChangeFrameRateStrategy int videoChangeFrameRateStrategy) {
verifyApplicationThread();
if (this.videoChangeFrameRateStrategy == videoChangeFrameRateStrategy) {
return;
}
this.videoChangeFrameRateStrategy = videoChangeFrameRateStrategy;
sendRendererMessage(
TRACK_TYPE_VIDEO, MSG_SET_CHANGE_FRAME_RATE_STRATEGY, videoChangeFrameRateStrategy);
}
@Override
public @C.VideoChangeFrameRateStrategy int getVideoChangeFrameRateStrategy() {
verifyApplicationThread();
return videoChangeFrameRateStrategy;
}
@Override
public VideoSize getVideoSize() {
verifyApplicationThread();
return videoSize;
}
@Override
public Size getSurfaceSize() {
verifyApplicationThread();
return surfaceSize;
}
@Override
public void clearVideoSurface() {
verifyApplicationThread();
removeSurfaceCallbacks();
setVideoOutputInternal(/* videoOutput= */ null);
maybeNotifySurfaceSizeChanged(/* width= */ 0, /* height= */ 0);
}
@Override
public void clearVideoSurface(@Nullable Surface surface) {
verifyApplicationThread();
if (surface != null && surface == videoOutput) {
clearVideoSurface();
}
}
@Override
public void setVideoSurface(@Nullable Surface surface) {
verifyApplicationThread();
removeSurfaceCallbacks();
setVideoOutputInternal(surface);
int newSurfaceSize = surface == null ? 0 : C.LENGTH_UNSET;
maybeNotifySurfaceSizeChanged(/* width= */ newSurfaceSize, /* height= */ newSurfaceSize);
}
@Override
public void setVideoSurfaceHolder(@Nullable SurfaceHolder surfaceHolder) {
verifyApplicationThread();
if (surfaceHolder == null) {
clearVideoSurface();
} else {
removeSurfaceCallbacks();
this.surfaceHolderSurfaceIsVideoOutput = true;
this.surfaceHolder = surfaceHolder;
surfaceHolder.addCallback(componentListener);
Surface surface = surfaceHolder.getSurface();
if (surface != null && surface.isValid()) {
setVideoOutputInternal(surface);
Rect surfaceSize = surfaceHolder.getSurfaceFrame();
maybeNotifySurfaceSizeChanged(surfaceSize.width(), surfaceSize.height());
} else {
setVideoOutputInternal(/* videoOutput= */ null);
maybeNotifySurfaceSizeChanged(/* width= */ 0, /* height= */ 0);
}
}
}
@Override
public void clearVideoSurfaceHolder(@Nullable SurfaceHolder surfaceHolder) {
verifyApplicationThread();
if (surfaceHolder != null && surfaceHolder == this.surfaceHolder) {
clearVideoSurface();
}
}
@Override
public void setVideoSurfaceView(@Nullable SurfaceView surfaceView) {
verifyApplicationThread();
if (surfaceView instanceof VideoDecoderOutputBufferRenderer) {
removeSurfaceCallbacks();
setVideoOutputInternal(surfaceView);
setNonVideoOutputSurfaceHolderInternal(surfaceView.getHolder());
} else if (surfaceView instanceof SphericalGLSurfaceView) {
removeSurfaceCallbacks();
sphericalGLSurfaceView = (SphericalGLSurfaceView) surfaceView;
createMessageInternal(frameMetadataListener)
.setType(FrameMetadataListener.MSG_SET_SPHERICAL_SURFACE_VIEW)
.setPayload(sphericalGLSurfaceView)
.send();
sphericalGLSurfaceView.addVideoSurfaceListener(componentListener);
setVideoOutputInternal(sphericalGLSurfaceView.getVideoSurface());
setNonVideoOutputSurfaceHolderInternal(surfaceView.getHolder());
} else {
setVideoSurfaceHolder(surfaceView == null ? null : surfaceView.getHolder());
}
}
@Override
public void clearVideoSurfaceView(@Nullable SurfaceView surfaceView) {
verifyApplicationThread();
clearVideoSurfaceHolder(surfaceView == null ? null : surfaceView.getHolder());
}
@Override
public void setVideoTextureView(@Nullable TextureView textureView) {
verifyApplicationThread();
if (textureView == null) {
clearVideoSurface();
} else {
removeSurfaceCallbacks();
this.textureView = textureView;
if (textureView.getSurfaceTextureListener() != null) {
Log.w(TAG, "Replacing existing SurfaceTextureListener.");
}
textureView.setSurfaceTextureListener(componentListener);
@Nullable
SurfaceTexture surfaceTexture =
textureView.isAvailable() ? textureView.getSurfaceTexture() : null;
if (surfaceTexture == null) {
setVideoOutputInternal(/* videoOutput= */ null);
maybeNotifySurfaceSizeChanged(/* width= */ 0, /* height= */ 0);
} else {
setSurfaceTextureInternal(surfaceTexture);
maybeNotifySurfaceSizeChanged(textureView.getWidth(), textureView.getHeight());
}
}
}
@Override
public void clearVideoTextureView(@Nullable TextureView textureView) {
verifyApplicationThread();
if (textureView != null && textureView == this.textureView) {
clearVideoSurface();
}
}
@Override
public void setAudioAttributes(AudioAttributes newAudioAttributes, boolean handleAudioFocus) {
verifyApplicationThread();
if (playerReleased) {
return;
}
if (!Util.areEqual(this.audioAttributes, newAudioAttributes)) {
this.audioAttributes = newAudioAttributes;
sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_AUDIO_ATTRIBUTES, newAudioAttributes);
streamVolumeManager.setStreamType(Util.getStreamTypeForAudioUsage(newAudioAttributes.usage));
// Queue event only and flush after updating playWhenReady in case both events are triggered.
listeners.queueEvent(
EVENT_AUDIO_ATTRIBUTES_CHANGED,
listener -> listener.onAudioAttributesChanged(newAudioAttributes));
}
audioFocusManager.setAudioAttributes(handleAudioFocus ? newAudioAttributes : null);
trackSelector.setAudioAttributes(newAudioAttributes);
boolean playWhenReady = getPlayWhenReady();
@AudioFocusManager.PlayerCommand
int playerCommand = audioFocusManager.updateAudioFocus(playWhenReady, getPlaybackState());
updatePlayWhenReady(
playWhenReady, playerCommand, getPlayWhenReadyChangeReason(playWhenReady, playerCommand));
listeners.flushEvents();
}
@Override
public AudioAttributes getAudioAttributes() {
verifyApplicationThread();
return audioAttributes;
}
@Override
public void setAudioSessionId(int audioSessionId) {
verifyApplicationThread();
if (this.audioSessionId == audioSessionId) {
return;
}
if (audioSessionId == C.AUDIO_SESSION_ID_UNSET) {
if (Util.SDK_INT < 21) {
audioSessionId = initializeKeepSessionIdAudioTrack(C.AUDIO_SESSION_ID_UNSET);
} else {
audioSessionId = Util.generateAudioSessionIdV21(applicationContext);
}
} else if (Util.SDK_INT < 21) {
// We need to re-initialize keepSessionIdAudioTrack to make sure the session is kept alive for
// as long as the player is using it.
initializeKeepSessionIdAudioTrack(audioSessionId);
}
this.audioSessionId = audioSessionId;
sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_AUDIO_SESSION_ID, audioSessionId);
sendRendererMessage(TRACK_TYPE_VIDEO, MSG_SET_AUDIO_SESSION_ID, audioSessionId);
int finalAudioSessionId = audioSessionId;
listeners.sendEvent(
EVENT_AUDIO_SESSION_ID, listener -> listener.onAudioSessionIdChanged(finalAudioSessionId));
}
@Override
public int getAudioSessionId() {
verifyApplicationThread();
return audioSessionId;
}
@Override
public void setAuxEffectInfo(AuxEffectInfo auxEffectInfo) {
verifyApplicationThread();
sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_AUX_EFFECT_INFO, auxEffectInfo);
}
@Override
public void clearAuxEffectInfo() {
verifyApplicationThread();
setAuxEffectInfo(new AuxEffectInfo(AuxEffectInfo.NO_AUX_EFFECT_ID, /* sendLevel= */ 0f));
}
@RequiresApi(23)
@Override
public void setPreferredAudioDevice(@Nullable AudioDeviceInfo audioDeviceInfo) {
verifyApplicationThread();
sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_PREFERRED_AUDIO_DEVICE, audioDeviceInfo);
}
@Override
public void setVolume(float volume) {
verifyApplicationThread();
volume = Util.constrainValue(volume, /* min= */ 0, /* max= */ 1);
if (this.volume == volume) {
return;
}
this.volume = volume;
sendVolumeToRenderers();
float finalVolume = volume;
listeners.sendEvent(EVENT_VOLUME_CHANGED, listener -> listener.onVolumeChanged(finalVolume));
}
@Override
public float getVolume() {
verifyApplicationThread();
return volume;
}
@Override
public boolean getSkipSilenceEnabled() {
verifyApplicationThread();
return skipSilenceEnabled;
}
@Override
public void setSkipSilenceEnabled(boolean newSkipSilenceEnabled) {
verifyApplicationThread();
if (skipSilenceEnabled == newSkipSilenceEnabled) {
return;
}
skipSilenceEnabled = newSkipSilenceEnabled;
sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_SKIP_SILENCE_ENABLED, newSkipSilenceEnabled);
listeners.sendEvent(
EVENT_SKIP_SILENCE_ENABLED_CHANGED,
listener -> listener.onSkipSilenceEnabledChanged(newSkipSilenceEnabled));
}
@Override
public AnalyticsCollector getAnalyticsCollector() {
verifyApplicationThread();
return analyticsCollector;
}
@Override
public void addAnalyticsListener(AnalyticsListener listener) {
// Don't verify application thread. We allow calls to this method from any thread.
analyticsCollector.addListener(checkNotNull(listener));
}
@Override
public void removeAnalyticsListener(AnalyticsListener listener) {
verifyApplicationThread();
analyticsCollector.removeListener(checkNotNull(listener));
}
@Override
public void setHandleAudioBecomingNoisy(boolean handleAudioBecomingNoisy) {
verifyApplicationThread();
if (playerReleased) {
return;
}
audioBecomingNoisyManager.setEnabled(handleAudioBecomingNoisy);
}
@Override
public void setPriorityTaskManager(@Nullable PriorityTaskManager priorityTaskManager) {
verifyApplicationThread();
if (Util.areEqual(this.priorityTaskManager, priorityTaskManager)) {
return;
}
if (isPriorityTaskManagerRegistered) {
checkNotNull(this.priorityTaskManager).remove(C.PRIORITY_PLAYBACK);
}
if (priorityTaskManager != null && isLoading()) {
priorityTaskManager.add(C.PRIORITY_PLAYBACK);
isPriorityTaskManagerRegistered = true;
} else {
isPriorityTaskManagerRegistered = false;
}
this.priorityTaskManager = priorityTaskManager;
}
@Override
@Nullable
public Format getVideoFormat() {
verifyApplicationThread();
return videoFormat;
}
@Override
@Nullable
public Format getAudioFormat() {
verifyApplicationThread();
return audioFormat;
}
@Override
@Nullable
public DecoderCounters getVideoDecoderCounters() {
verifyApplicationThread();
return videoDecoderCounters;
}
@Override
@Nullable
public DecoderCounters getAudioDecoderCounters() {
verifyApplicationThread();
return audioDecoderCounters;
}
@Override
public void setVideoFrameMetadataListener(VideoFrameMetadataListener listener) {
verifyApplicationThread();
videoFrameMetadataListener = listener;
createMessageInternal(frameMetadataListener)
.setType(FrameMetadataListener.MSG_SET_VIDEO_FRAME_METADATA_LISTENER)
.setPayload(listener)
.send();
}
@Override
public void clearVideoFrameMetadataListener(VideoFrameMetadataListener listener) {
verifyApplicationThread();
if (videoFrameMetadataListener != listener) {
return;
}
createMessageInternal(frameMetadataListener)
.setType(FrameMetadataListener.MSG_SET_VIDEO_FRAME_METADATA_LISTENER)
.setPayload(null)
.send();
}
@Override
public void setCameraMotionListener(CameraMotionListener listener) {
verifyApplicationThread();
cameraMotionListener = listener;
createMessageInternal(frameMetadataListener)
.setType(FrameMetadataListener.MSG_SET_CAMERA_MOTION_LISTENER)
.setPayload(listener)
.send();
}
@Override
public void clearCameraMotionListener(CameraMotionListener listener) {
verifyApplicationThread();
if (cameraMotionListener != listener) {
return;
}
createMessageInternal(frameMetadataListener)
.setType(FrameMetadataListener.MSG_SET_CAMERA_MOTION_LISTENER)
.setPayload(null)
.send();
}
@Override
public CueGroup getCurrentCues() {
verifyApplicationThread();
return currentCueGroup;
}
@Override
public void addListener(Listener listener) {
// Don't verify application thread. We allow calls to this method from any thread.
listeners.add(checkNotNull(listener));
}
@Override
public void removeListener(Listener listener) {
verifyApplicationThread();
listeners.remove(checkNotNull(listener));
}
@Override
public void setHandleWakeLock(boolean handleWakeLock) {
verifyApplicationThread();
setWakeMode(handleWakeLock ? C.WAKE_MODE_LOCAL : C.WAKE_MODE_NONE);
}
@Override
public void setWakeMode(@C.WakeMode int wakeMode) {
verifyApplicationThread();
switch (wakeMode) {
case C.WAKE_MODE_NONE:
wakeLockManager.setEnabled(false);
wifiLockManager.setEnabled(false);
break;
case C.WAKE_MODE_LOCAL:
wakeLockManager.setEnabled(true);
wifiLockManager.setEnabled(false);
break;
case C.WAKE_MODE_NETWORK:
wakeLockManager.setEnabled(true);
wifiLockManager.setEnabled(true);
break;
default:
break;
}
}
@Override
public DeviceInfo getDeviceInfo() {
verifyApplicationThread();
return deviceInfo;
}
@Override
public int getDeviceVolume() {
verifyApplicationThread();
return streamVolumeManager.getVolume();
}
@Override
public boolean isDeviceMuted() {
verifyApplicationThread();
return streamVolumeManager.isMuted();
}
@Override
public void setDeviceVolume(int volume) {
verifyApplicationThread();
streamVolumeManager.setVolume(volume);
}
@Override
public void increaseDeviceVolume() {
verifyApplicationThread();
streamVolumeManager.increaseVolume();
}
@Override
public void decreaseDeviceVolume() {
verifyApplicationThread();
streamVolumeManager.decreaseVolume();
}
@Override
public void setDeviceMuted(boolean muted) {
verifyApplicationThread();
streamVolumeManager.setMuted(muted);
}
@Override
public boolean isTunnelingEnabled() {
verifyApplicationThread();
for (RendererConfiguration config : playbackInfo.trackSelectorResult.rendererConfigurations) {
if (config.tunneling) {
return true;
}
}
return false;
}
@SuppressWarnings("deprecation") // Calling deprecated methods.
/* package */ void setThrowsWhenUsingWrongThread(boolean throwsWhenUsingWrongThread) {
this.throwsWhenUsingWrongThread = throwsWhenUsingWrongThread;
listeners.setThrowsWhenUsingWrongThread(throwsWhenUsingWrongThread);
if (analyticsCollector instanceof DefaultAnalyticsCollector) {
((DefaultAnalyticsCollector) analyticsCollector)
.setThrowsWhenUsingWrongThread(throwsWhenUsingWrongThread);
}
}
/**
* Stops the player.
*
* @param reset Whether the playlist should be cleared and whether the playback position and
* playback error should be reset.
* @param error An optional {@link ExoPlaybackException} to set.
*/
private void stopInternal(boolean reset, @Nullable ExoPlaybackException error) {
PlaybackInfo playbackInfo;
if (reset) {
playbackInfo =
removeMediaItemsInternal(
/* fromIndex= */ 0, /* toIndex= */ mediaSourceHolderSnapshots.size());
playbackInfo = playbackInfo.copyWithPlaybackError(null);
} else {
playbackInfo = this.playbackInfo.copyWithLoadingMediaPeriodId(this.playbackInfo.periodId);
playbackInfo.bufferedPositionUs = playbackInfo.positionUs;
playbackInfo.totalBufferedDurationUs = 0;
}
playbackInfo = playbackInfo.copyWithPlaybackState(Player.STATE_IDLE);
if (error != null) {
playbackInfo = playbackInfo.copyWithPlaybackError(error);
}
pendingOperationAcks++;
internalPlayer.stop();
boolean positionDiscontinuity =
playbackInfo.timeline.isEmpty() && !this.playbackInfo.timeline.isEmpty();
updatePlaybackInfo(
playbackInfo,
TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED,
/* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST,
/* seekProcessed= */ false,
positionDiscontinuity,
DISCONTINUITY_REASON_REMOVE,
/* discontinuityWindowStartPositionUs= */ getCurrentPositionUsInternal(playbackInfo),
/* ignored */ C.INDEX_UNSET,
/* repeatCurrentMediaItem= */ false);
}
private int getCurrentWindowIndexInternal() {
if (playbackInfo.timeline.isEmpty()) {
return maskingWindowIndex;
} else {
return playbackInfo.timeline.getPeriodByUid(playbackInfo.periodId.periodUid, period)
.windowIndex;
}
}
private long getCurrentPositionUsInternal(PlaybackInfo playbackInfo) {
if (playbackInfo.timeline.isEmpty()) {
return Util.msToUs(maskingWindowPositionMs);
} else if (playbackInfo.periodId.isAd()) {
return playbackInfo.positionUs;
} else {
return periodPositionUsToWindowPositionUs(
playbackInfo.timeline, playbackInfo.periodId, playbackInfo.positionUs);
}
}
private List<MediaSource> createMediaSources(List<MediaItem> mediaItems) {
List<MediaSource> mediaSources = new ArrayList<>();
for (int i = 0; i < mediaItems.size(); i++) {
mediaSources.add(mediaSourceFactory.createMediaSource(mediaItems.get(i)));
}
return mediaSources;
}
private void handlePlaybackInfo(ExoPlayerImplInternal.PlaybackInfoUpdate playbackInfoUpdate) {
pendingOperationAcks -= playbackInfoUpdate.operationAcks;
if (playbackInfoUpdate.positionDiscontinuity) {
pendingDiscontinuityReason = playbackInfoUpdate.discontinuityReason;
pendingDiscontinuity = true;
}
if (playbackInfoUpdate.hasPlayWhenReadyChangeReason) {
pendingPlayWhenReadyChangeReason = playbackInfoUpdate.playWhenReadyChangeReason;
}
if (pendingOperationAcks == 0) {
Timeline newTimeline = playbackInfoUpdate.playbackInfo.timeline;
if (!this.playbackInfo.timeline.isEmpty() && newTimeline.isEmpty()) {
// Update the masking variables, which are used when the timeline becomes empty because a
// ConcatenatingMediaSource has been cleared.
maskingWindowIndex = C.INDEX_UNSET;
maskingWindowPositionMs = 0;
maskingPeriodIndex = 0;
}
if (!newTimeline.isEmpty()) {
List<Timeline> timelines = ((PlaylistTimeline) newTimeline).getChildTimelines();
checkState(timelines.size() == mediaSourceHolderSnapshots.size());
for (int i = 0; i < timelines.size(); i++) {
mediaSourceHolderSnapshots.get(i).timeline = timelines.get(i);
}
}
boolean positionDiscontinuity = false;
long discontinuityWindowStartPositionUs = C.TIME_UNSET;
if (pendingDiscontinuity) {
positionDiscontinuity =
!playbackInfoUpdate.playbackInfo.periodId.equals(playbackInfo.periodId)
|| playbackInfoUpdate.playbackInfo.discontinuityStartPositionUs
!= playbackInfo.positionUs;
if (positionDiscontinuity) {
discontinuityWindowStartPositionUs =
newTimeline.isEmpty() || playbackInfoUpdate.playbackInfo.periodId.isAd()
? playbackInfoUpdate.playbackInfo.discontinuityStartPositionUs
: periodPositionUsToWindowPositionUs(
newTimeline,
playbackInfoUpdate.playbackInfo.periodId,
playbackInfoUpdate.playbackInfo.discontinuityStartPositionUs);
}
}
pendingDiscontinuity = false;
updatePlaybackInfo(
playbackInfoUpdate.playbackInfo,
TIMELINE_CHANGE_REASON_SOURCE_UPDATE,
pendingPlayWhenReadyChangeReason,
/* seekProcessed= */ false,
positionDiscontinuity,
pendingDiscontinuityReason,
discontinuityWindowStartPositionUs,
/* ignored */ C.INDEX_UNSET,
/* repeatCurrentMediaItem= */ false);
}
}
// Calling deprecated listeners.
@SuppressWarnings("deprecation")
private void updatePlaybackInfo(
PlaybackInfo playbackInfo,
@TimelineChangeReason int timelineChangeReason,
@PlayWhenReadyChangeReason int playWhenReadyChangeReason,
boolean seekProcessed,
boolean positionDiscontinuity,
@DiscontinuityReason int positionDiscontinuityReason,
long discontinuityWindowStartPositionUs,
int oldMaskingMediaItemIndex,
boolean repeatCurrentMediaItem) {
// Assign playback info immediately such that all getters return the right values, but keep
// snapshot of previous and new state so that listener invocations are triggered correctly.
PlaybackInfo previousPlaybackInfo = this.playbackInfo;
PlaybackInfo newPlaybackInfo = playbackInfo;
this.playbackInfo = playbackInfo;
boolean timelineChanged = !previousPlaybackInfo.timeline.equals(newPlaybackInfo.timeline);
Pair<Boolean, Integer> mediaItemTransitionInfo =
evaluateMediaItemTransitionReason(
newPlaybackInfo,
previousPlaybackInfo,
positionDiscontinuity,
positionDiscontinuityReason,
timelineChanged,
repeatCurrentMediaItem);
boolean mediaItemTransitioned = mediaItemTransitionInfo.first;
int mediaItemTransitionReason = mediaItemTransitionInfo.second;
MediaMetadata newMediaMetadata = mediaMetadata;
@Nullable MediaItem mediaItem = null;
if (mediaItemTransitioned) {
if (!newPlaybackInfo.timeline.isEmpty()) {
int windowIndex =
newPlaybackInfo.timeline.getPeriodByUid(newPlaybackInfo.periodId.periodUid, period)
.windowIndex;
mediaItem = newPlaybackInfo.timeline.getWindow(windowIndex, window).mediaItem;
}
staticAndDynamicMediaMetadata = MediaMetadata.EMPTY;
}
if (mediaItemTransitioned
|| !previousPlaybackInfo.staticMetadata.equals(newPlaybackInfo.staticMetadata)) {
staticAndDynamicMediaMetadata =
staticAndDynamicMediaMetadata
.buildUpon()
.populateFromMetadata(newPlaybackInfo.staticMetadata)
.build();
newMediaMetadata = buildUpdatedMediaMetadata();
}
boolean metadataChanged = !newMediaMetadata.equals(mediaMetadata);
mediaMetadata = newMediaMetadata;
boolean playWhenReadyChanged =
previousPlaybackInfo.playWhenReady != newPlaybackInfo.playWhenReady;
boolean playbackStateChanged =
previousPlaybackInfo.playbackState != newPlaybackInfo.playbackState;
if (playbackStateChanged || playWhenReadyChanged) {
updateWakeAndWifiLock();
}
boolean isLoadingChanged = previousPlaybackInfo.isLoading != newPlaybackInfo.isLoading;
if (isLoadingChanged) {
updatePriorityTaskManagerForIsLoadingChange(newPlaybackInfo.isLoading);
}
if (timelineChanged) {
listeners.queueEvent(
Player.EVENT_TIMELINE_CHANGED,
listener -> listener.onTimelineChanged(newPlaybackInfo.timeline, timelineChangeReason));
}
if (positionDiscontinuity) {
PositionInfo previousPositionInfo =
getPreviousPositionInfo(
positionDiscontinuityReason, previousPlaybackInfo, oldMaskingMediaItemIndex);
PositionInfo positionInfo = getPositionInfo(discontinuityWindowStartPositionUs);
listeners.queueEvent(
Player.EVENT_POSITION_DISCONTINUITY,
listener -> {
listener.onPositionDiscontinuity(positionDiscontinuityReason);
listener.onPositionDiscontinuity(
previousPositionInfo, positionInfo, positionDiscontinuityReason);
});
}
if (mediaItemTransitioned) {
@Nullable final MediaItem finalMediaItem = mediaItem;
listeners.queueEvent(
Player.EVENT_MEDIA_ITEM_TRANSITION,
listener -> listener.onMediaItemTransition(finalMediaItem, mediaItemTransitionReason));
}
if (previousPlaybackInfo.playbackError != newPlaybackInfo.playbackError) {
listeners.queueEvent(
Player.EVENT_PLAYER_ERROR,
listener -> listener.onPlayerErrorChanged(newPlaybackInfo.playbackError));
if (newPlaybackInfo.playbackError != null) {
listeners.queueEvent(
Player.EVENT_PLAYER_ERROR,
listener -> listener.onPlayerError(newPlaybackInfo.playbackError));
}
}
if (previousPlaybackInfo.trackSelectorResult != newPlaybackInfo.trackSelectorResult) {
trackSelector.onSelectionActivated(newPlaybackInfo.trackSelectorResult.info);
listeners.queueEvent(
Player.EVENT_TRACKS_CHANGED,
listener -> listener.onTracksChanged(newPlaybackInfo.trackSelectorResult.tracks));
}
if (metadataChanged) {
final MediaMetadata finalMediaMetadata = mediaMetadata;
listeners.queueEvent(
EVENT_MEDIA_METADATA_CHANGED,
listener -> listener.onMediaMetadataChanged(finalMediaMetadata));
}
if (isLoadingChanged) {
listeners.queueEvent(
Player.EVENT_IS_LOADING_CHANGED,
listener -> {
listener.onLoadingChanged(newPlaybackInfo.isLoading);
listener.onIsLoadingChanged(newPlaybackInfo.isLoading);
});
}
if (playbackStateChanged || playWhenReadyChanged) {
listeners.queueEvent(
/* eventFlag= */ C.INDEX_UNSET,
listener ->
listener.onPlayerStateChanged(
newPlaybackInfo.playWhenReady, newPlaybackInfo.playbackState));
}
if (playbackStateChanged) {
listeners.queueEvent(
Player.EVENT_PLAYBACK_STATE_CHANGED,
listener -> listener.onPlaybackStateChanged(newPlaybackInfo.playbackState));
}
if (playWhenReadyChanged) {
listeners.queueEvent(
Player.EVENT_PLAY_WHEN_READY_CHANGED,
listener ->
listener.onPlayWhenReadyChanged(
newPlaybackInfo.playWhenReady, playWhenReadyChangeReason));
}
if (previousPlaybackInfo.playbackSuppressionReason
!= newPlaybackInfo.playbackSuppressionReason) {
listeners.queueEvent(
Player.EVENT_PLAYBACK_SUPPRESSION_REASON_CHANGED,
listener ->
listener.onPlaybackSuppressionReasonChanged(
newPlaybackInfo.playbackSuppressionReason));
}
if (isPlaying(previousPlaybackInfo) != isPlaying(newPlaybackInfo)) {
listeners.queueEvent(
Player.EVENT_IS_PLAYING_CHANGED,
listener -> listener.onIsPlayingChanged(isPlaying(newPlaybackInfo)));
}
if (!previousPlaybackInfo.playbackParameters.equals(newPlaybackInfo.playbackParameters)) {
listeners.queueEvent(
Player.EVENT_PLAYBACK_PARAMETERS_CHANGED,
listener -> listener.onPlaybackParametersChanged(newPlaybackInfo.playbackParameters));
}
if (seekProcessed) {
listeners.queueEvent(/* eventFlag= */ C.INDEX_UNSET, Listener::onSeekProcessed);
}
updateAvailableCommands();
listeners.flushEvents();
if (previousPlaybackInfo.sleepingForOffload != newPlaybackInfo.sleepingForOffload) {
for (AudioOffloadListener listener : audioOffloadListeners) {
listener.onExperimentalSleepingForOffloadChanged(newPlaybackInfo.sleepingForOffload);
}
}
}
private PositionInfo getPreviousPositionInfo(
@DiscontinuityReason int positionDiscontinuityReason,
PlaybackInfo oldPlaybackInfo,
int oldMaskingMediaItemIndex) {
@Nullable Object oldWindowUid = null;
@Nullable Object oldPeriodUid = null;
int oldMediaItemIndex = oldMaskingMediaItemIndex;
int oldPeriodIndex = C.INDEX_UNSET;
@Nullable MediaItem oldMediaItem = null;
Timeline.Period oldPeriod = new Timeline.Period();
if (!oldPlaybackInfo.timeline.isEmpty()) {
oldPeriodUid = oldPlaybackInfo.periodId.periodUid;
oldPlaybackInfo.timeline.getPeriodByUid(oldPeriodUid, oldPeriod);
oldMediaItemIndex = oldPeriod.windowIndex;
oldPeriodIndex = oldPlaybackInfo.timeline.getIndexOfPeriod(oldPeriodUid);
oldWindowUid = oldPlaybackInfo.timeline.getWindow(oldMediaItemIndex, window).uid;
oldMediaItem = window.mediaItem;
}
long oldPositionUs;
long oldContentPositionUs;
if (positionDiscontinuityReason == DISCONTINUITY_REASON_AUTO_TRANSITION) {
if (oldPlaybackInfo.periodId.isAd()) {
// The old position is the end of the previous ad.
oldPositionUs =
oldPeriod.getAdDurationUs(
oldPlaybackInfo.periodId.adGroupIndex, oldPlaybackInfo.periodId.adIndexInAdGroup);
// The ad cue point is stored in the old requested content position.
oldContentPositionUs = getRequestedContentPositionUs(oldPlaybackInfo);
} else if (oldPlaybackInfo.periodId.nextAdGroupIndex != C.INDEX_UNSET) {
// The old position is the end of a clipped content before an ad group. Use the exact ad
// cue point as the transition position.
oldPositionUs = getRequestedContentPositionUs(playbackInfo);
oldContentPositionUs = oldPositionUs;
} else {
// The old position is the end of a Timeline period. Use the exact duration.
oldPositionUs = oldPeriod.positionInWindowUs + oldPeriod.durationUs;
oldContentPositionUs = oldPositionUs;
}
} else if (oldPlaybackInfo.periodId.isAd()) {
oldPositionUs = oldPlaybackInfo.positionUs;
oldContentPositionUs = getRequestedContentPositionUs(oldPlaybackInfo);
} else {
oldPositionUs = oldPeriod.positionInWindowUs + oldPlaybackInfo.positionUs;
oldContentPositionUs = oldPositionUs;
}
return new PositionInfo(
oldWindowUid,
oldMediaItemIndex,
oldMediaItem,
oldPeriodUid,
oldPeriodIndex,
Util.usToMs(oldPositionUs),
Util.usToMs(oldContentPositionUs),
oldPlaybackInfo.periodId.adGroupIndex,
oldPlaybackInfo.periodId.adIndexInAdGroup);
}
private PositionInfo getPositionInfo(long discontinuityWindowStartPositionUs) {
@Nullable Object newWindowUid = null;
@Nullable Object newPeriodUid = null;
int newMediaItemIndex = getCurrentMediaItemIndex();
int newPeriodIndex = C.INDEX_UNSET;
@Nullable MediaItem newMediaItem = null;
if (!playbackInfo.timeline.isEmpty()) {
newPeriodUid = playbackInfo.periodId.periodUid;
playbackInfo.timeline.getPeriodByUid(newPeriodUid, period);
newPeriodIndex = playbackInfo.timeline.getIndexOfPeriod(newPeriodUid);
newWindowUid = playbackInfo.timeline.getWindow(newMediaItemIndex, window).uid;
newMediaItem = window.mediaItem;
}
long positionMs = Util.usToMs(discontinuityWindowStartPositionUs);
return new PositionInfo(
newWindowUid,
newMediaItemIndex,
newMediaItem,
newPeriodUid,
newPeriodIndex,
positionMs,
/* contentPositionMs= */ playbackInfo.periodId.isAd()
? Util.usToMs(getRequestedContentPositionUs(playbackInfo))
: positionMs,
playbackInfo.periodId.adGroupIndex,
playbackInfo.periodId.adIndexInAdGroup);
}
private static long getRequestedContentPositionUs(PlaybackInfo playbackInfo) {
Timeline.Window window = new Timeline.Window();
Timeline.Period period = new Timeline.Period();
playbackInfo.timeline.getPeriodByUid(playbackInfo.periodId.periodUid, period);
return playbackInfo.requestedContentPositionUs == C.TIME_UNSET
? playbackInfo.timeline.getWindow(period.windowIndex, window).getDefaultPositionUs()
: period.getPositionInWindowUs() + playbackInfo.requestedContentPositionUs;
}
private Pair<Boolean, Integer> evaluateMediaItemTransitionReason(
PlaybackInfo playbackInfo,
PlaybackInfo oldPlaybackInfo,
boolean positionDiscontinuity,
@DiscontinuityReason int positionDiscontinuityReason,
boolean timelineChanged,
boolean repeatCurrentMediaItem) {
Timeline oldTimeline = oldPlaybackInfo.timeline;
Timeline newTimeline = playbackInfo.timeline;
if (newTimeline.isEmpty() && oldTimeline.isEmpty()) {
return new Pair<>(/* isTransitioning */ false, /* mediaItemTransitionReason */ C.INDEX_UNSET);
} else if (newTimeline.isEmpty() != oldTimeline.isEmpty()) {
return new Pair<>(/* isTransitioning */ true, MEDIA_ITEM_TRANSITION_REASON_PLAYLIST_CHANGED);
}
int oldWindowIndex =
oldTimeline.getPeriodByUid(oldPlaybackInfo.periodId.periodUid, period).windowIndex;
Object oldWindowUid = oldTimeline.getWindow(oldWindowIndex, window).uid;
int newWindowIndex =
newTimeline.getPeriodByUid(playbackInfo.periodId.periodUid, period).windowIndex;
Object newWindowUid = newTimeline.getWindow(newWindowIndex, window).uid;
if (!oldWindowUid.equals(newWindowUid)) {
@Player.MediaItemTransitionReason int transitionReason;
if (positionDiscontinuity
&& positionDiscontinuityReason == DISCONTINUITY_REASON_AUTO_TRANSITION) {
transitionReason = MEDIA_ITEM_TRANSITION_REASON_AUTO;
} else if (positionDiscontinuity
&& positionDiscontinuityReason == DISCONTINUITY_REASON_SEEK) {
transitionReason = MEDIA_ITEM_TRANSITION_REASON_SEEK;
} else if (timelineChanged) {
transitionReason = MEDIA_ITEM_TRANSITION_REASON_PLAYLIST_CHANGED;
} else {
// A change in window uid must be justified by one of the reasons above.
throw new IllegalStateException();
}
return new Pair<>(/* isTransitioning */ true, transitionReason);
} else {
// Only mark changes within the current item as a transition if we are repeating automatically
// or via a seek to next/previous.
if (positionDiscontinuity
&& positionDiscontinuityReason == DISCONTINUITY_REASON_AUTO_TRANSITION
&& oldPlaybackInfo.periodId.windowSequenceNumber
< playbackInfo.periodId.windowSequenceNumber) {
return new Pair<>(/* isTransitioning */ true, MEDIA_ITEM_TRANSITION_REASON_REPEAT);
}
if (positionDiscontinuity
&& positionDiscontinuityReason == DISCONTINUITY_REASON_SEEK
&& repeatCurrentMediaItem) {
return new Pair<>(/* isTransitioning */ true, MEDIA_ITEM_TRANSITION_REASON_SEEK);
}
}
return new Pair<>(/* isTransitioning */ false, /* mediaItemTransitionReason */ C.INDEX_UNSET);
}
private void updateAvailableCommands() {
Commands previousAvailableCommands = availableCommands;
availableCommands = Util.getAvailableCommands(wrappingPlayer, permanentAvailableCommands);
if (!availableCommands.equals(previousAvailableCommands)) {
listeners.queueEvent(
Player.EVENT_AVAILABLE_COMMANDS_CHANGED,
listener -> listener.onAvailableCommandsChanged(availableCommands));
}
}
private void setMediaSourcesInternal(
List<MediaSource> mediaSources,
int startWindowIndex,
long startPositionMs,
boolean resetToDefaultPosition) {
int currentWindowIndex = getCurrentWindowIndexInternal();
long currentPositionMs = getCurrentPosition();
pendingOperationAcks++;
if (!mediaSourceHolderSnapshots.isEmpty()) {
removeMediaSourceHolders(
/* fromIndex= */ 0, /* toIndexExclusive= */ mediaSourceHolderSnapshots.size());
}
List<MediaSourceList.MediaSourceHolder> holders =
addMediaSourceHolders(/* index= */ 0, mediaSources);
Timeline timeline = createMaskingTimeline();
if (!timeline.isEmpty() && startWindowIndex >= timeline.getWindowCount()) {
throw new IllegalSeekPositionException(timeline, startWindowIndex, startPositionMs);
}
// Evaluate the actual start position.
if (resetToDefaultPosition) {
startWindowIndex = timeline.getFirstWindowIndex(shuffleModeEnabled);
startPositionMs = C.TIME_UNSET;
} else if (startWindowIndex == C.INDEX_UNSET) {
startWindowIndex = currentWindowIndex;
startPositionMs = currentPositionMs;
}
PlaybackInfo newPlaybackInfo =
maskTimelineAndPosition(
playbackInfo,
timeline,
maskWindowPositionMsOrGetPeriodPositionUs(timeline, startWindowIndex, startPositionMs));
// Mask the playback state.
int maskingPlaybackState = newPlaybackInfo.playbackState;
if (startWindowIndex != C.INDEX_UNSET && newPlaybackInfo.playbackState != STATE_IDLE) {
// Position reset to startWindowIndex (results in pending initial seek).
if (timeline.isEmpty() || startWindowIndex >= timeline.getWindowCount()) {
// Setting an empty timeline or invalid seek transitions to ended.
maskingPlaybackState = STATE_ENDED;
} else {
maskingPlaybackState = STATE_BUFFERING;
}
}
newPlaybackInfo = newPlaybackInfo.copyWithPlaybackState(maskingPlaybackState);
internalPlayer.setMediaSources(
holders, startWindowIndex, Util.msToUs(startPositionMs), shuffleOrder);
boolean positionDiscontinuity =
!playbackInfo.periodId.periodUid.equals(newPlaybackInfo.periodId.periodUid)
&& !playbackInfo.timeline.isEmpty();
updatePlaybackInfo(
newPlaybackInfo,
/* timelineChangeReason= */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED,
/* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST,
/* seekProcessed= */ false,
/* positionDiscontinuity= */ positionDiscontinuity,
DISCONTINUITY_REASON_REMOVE,
/* discontinuityWindowStartPositionUs= */ getCurrentPositionUsInternal(newPlaybackInfo),
/* ignored */ C.INDEX_UNSET,
/* repeatCurrentMediaItem= */ false);
}
private List<MediaSourceList.MediaSourceHolder> addMediaSourceHolders(
int index, List<MediaSource> mediaSources) {
List<MediaSourceList.MediaSourceHolder> holders = new ArrayList<>();
for (int i = 0; i < mediaSources.size(); i++) {
MediaSourceList.MediaSourceHolder holder =
new MediaSourceList.MediaSourceHolder(mediaSources.get(i), useLazyPreparation);
holders.add(holder);
mediaSourceHolderSnapshots.add(
i + index, new MediaSourceHolderSnapshot(holder.uid, holder.mediaSource.getTimeline()));
}
shuffleOrder =
shuffleOrder.cloneAndInsert(
/* insertionIndex= */ index, /* insertionCount= */ holders.size());
return holders;
}
private PlaybackInfo removeMediaItemsInternal(int fromIndex, int toIndex) {
int currentIndex = getCurrentMediaItemIndex();
Timeline oldTimeline = getCurrentTimeline();
int currentMediaSourceCount = mediaSourceHolderSnapshots.size();
pendingOperationAcks++;
removeMediaSourceHolders(fromIndex, /* toIndexExclusive= */ toIndex);
Timeline newTimeline = createMaskingTimeline();
PlaybackInfo newPlaybackInfo =
maskTimelineAndPosition(
playbackInfo,
newTimeline,
getPeriodPositionUsAfterTimelineChanged(oldTimeline, newTimeline));
// Player transitions to STATE_ENDED if the current index is part of the removed tail.
final boolean transitionsToEnded =
newPlaybackInfo.playbackState != STATE_IDLE
&& newPlaybackInfo.playbackState != STATE_ENDED
&& fromIndex < toIndex
&& toIndex == currentMediaSourceCount
&& currentIndex >= newPlaybackInfo.timeline.getWindowCount();
if (transitionsToEnded) {
newPlaybackInfo = newPlaybackInfo.copyWithPlaybackState(STATE_ENDED);
}
internalPlayer.removeMediaSources(fromIndex, toIndex, shuffleOrder);
return newPlaybackInfo;
}
private void removeMediaSourceHolders(int fromIndex, int toIndexExclusive) {
for (int i = toIndexExclusive - 1; i >= fromIndex; i--) {
mediaSourceHolderSnapshots.remove(i);
}
shuffleOrder = shuffleOrder.cloneAndRemove(fromIndex, toIndexExclusive);
}
private Timeline createMaskingTimeline() {
return new PlaylistTimeline(mediaSourceHolderSnapshots, shuffleOrder);
}
private PlaybackInfo maskTimelineAndPosition(
PlaybackInfo playbackInfo, Timeline timeline, @Nullable Pair<Object, Long> periodPositionUs) {
checkArgument(timeline.isEmpty() || periodPositionUs != null);
Timeline oldTimeline = playbackInfo.timeline;
// Mask the timeline.
playbackInfo = playbackInfo.copyWithTimeline(timeline);
if (timeline.isEmpty()) {
// Reset periodId and loadingPeriodId.
MediaPeriodId dummyMediaPeriodId = PlaybackInfo.getDummyPeriodForEmptyTimeline();
long positionUs = Util.msToUs(maskingWindowPositionMs);
playbackInfo =
playbackInfo.copyWithNewPosition(
dummyMediaPeriodId,
positionUs,
/* requestedContentPositionUs= */ positionUs,
/* discontinuityStartPositionUs= */ positionUs,
/* totalBufferedDurationUs= */ 0,
TrackGroupArray.EMPTY,
emptyTrackSelectorResult,
/* staticMetadata= */ ImmutableList.of());
playbackInfo = playbackInfo.copyWithLoadingMediaPeriodId(dummyMediaPeriodId);
playbackInfo.bufferedPositionUs = playbackInfo.positionUs;
return playbackInfo;
}
Object oldPeriodUid = playbackInfo.periodId.periodUid;
boolean playingPeriodChanged = !oldPeriodUid.equals(castNonNull(periodPositionUs).first);
MediaPeriodId newPeriodId =
playingPeriodChanged ? new MediaPeriodId(periodPositionUs.first) : playbackInfo.periodId;
long newContentPositionUs = periodPositionUs.second;
long oldContentPositionUs = Util.msToUs(getContentPosition());
if (!oldTimeline.isEmpty()) {
oldContentPositionUs -=
oldTimeline.getPeriodByUid(oldPeriodUid, period).getPositionInWindowUs();
}
if (playingPeriodChanged || newContentPositionUs < oldContentPositionUs) {
checkState(!newPeriodId.isAd());
// The playing period changes or a backwards seek within the playing period occurs.
playbackInfo =
playbackInfo.copyWithNewPosition(
newPeriodId,
/* positionUs= */ newContentPositionUs,
/* requestedContentPositionUs= */ newContentPositionUs,
/* discontinuityStartPositionUs= */ newContentPositionUs,
/* totalBufferedDurationUs= */ 0,
playingPeriodChanged ? TrackGroupArray.EMPTY : playbackInfo.trackGroups,
playingPeriodChanged ? emptyTrackSelectorResult : playbackInfo.trackSelectorResult,
playingPeriodChanged ? ImmutableList.of() : playbackInfo.staticMetadata);
playbackInfo = playbackInfo.copyWithLoadingMediaPeriodId(newPeriodId);
playbackInfo.bufferedPositionUs = newContentPositionUs;
} else if (newContentPositionUs == oldContentPositionUs) {
// Period position remains unchanged.
int loadingPeriodIndex =
timeline.getIndexOfPeriod(playbackInfo.loadingMediaPeriodId.periodUid);
if (loadingPeriodIndex == C.INDEX_UNSET
|| timeline.getPeriod(loadingPeriodIndex, period).windowIndex
!= timeline.getPeriodByUid(newPeriodId.periodUid, period).windowIndex) {
// Discard periods after the playing period, if the loading period is discarded or the
// playing and loading period are not in the same window.
timeline.getPeriodByUid(newPeriodId.periodUid, period);
long maskedBufferedPositionUs =
newPeriodId.isAd()
? period.getAdDurationUs(newPeriodId.adGroupIndex, newPeriodId.adIndexInAdGroup)
: period.durationUs;
playbackInfo =
playbackInfo.copyWithNewPosition(
newPeriodId,
/* positionUs= */ playbackInfo.positionUs,
/* requestedContentPositionUs= */ playbackInfo.positionUs,
playbackInfo.discontinuityStartPositionUs,
/* totalBufferedDurationUs= */ maskedBufferedPositionUs - playbackInfo.positionUs,
playbackInfo.trackGroups,
playbackInfo.trackSelectorResult,
playbackInfo.staticMetadata);
playbackInfo = playbackInfo.copyWithLoadingMediaPeriodId(newPeriodId);
playbackInfo.bufferedPositionUs = maskedBufferedPositionUs;
}
} else {
checkState(!newPeriodId.isAd());
// A forward seek within the playing period (timeline did not change).
long maskedTotalBufferedDurationUs =
max(
0,
playbackInfo.totalBufferedDurationUs - (newContentPositionUs - oldContentPositionUs));
long maskedBufferedPositionUs = playbackInfo.bufferedPositionUs;
if (playbackInfo.loadingMediaPeriodId.equals(playbackInfo.periodId)) {
maskedBufferedPositionUs = newContentPositionUs + maskedTotalBufferedDurationUs;
}
playbackInfo =
playbackInfo.copyWithNewPosition(
newPeriodId,
/* positionUs= */ newContentPositionUs,
/* requestedContentPositionUs= */ newContentPositionUs,
/* discontinuityStartPositionUs= */ newContentPositionUs,
maskedTotalBufferedDurationUs,
playbackInfo.trackGroups,
playbackInfo.trackSelectorResult,
playbackInfo.staticMetadata);
playbackInfo.bufferedPositionUs = maskedBufferedPositionUs;
}
return playbackInfo;
}
@Nullable
private Pair<Object, Long> getPeriodPositionUsAfterTimelineChanged(
Timeline oldTimeline, Timeline newTimeline) {
long currentPositionMs = getContentPosition();
if (oldTimeline.isEmpty() || newTimeline.isEmpty()) {
boolean isCleared = !oldTimeline.isEmpty() && newTimeline.isEmpty();
return maskWindowPositionMsOrGetPeriodPositionUs(
newTimeline,
isCleared ? C.INDEX_UNSET : getCurrentWindowIndexInternal(),
isCleared ? C.TIME_UNSET : currentPositionMs);
}
int currentMediaItemIndex = getCurrentMediaItemIndex();
@Nullable
Pair<Object, Long> oldPeriodPositionUs =
oldTimeline.getPeriodPositionUs(
window, period, currentMediaItemIndex, Util.msToUs(currentPositionMs));
Object periodUid = castNonNull(oldPeriodPositionUs).first;
if (newTimeline.getIndexOfPeriod(periodUid) != C.INDEX_UNSET) {
// The old period position is still available in the new timeline.
return oldPeriodPositionUs;
}
// Period uid not found in new timeline. Try to get subsequent period.
@Nullable
Object nextPeriodUid =
ExoPlayerImplInternal.resolveSubsequentPeriod(
window, period, repeatMode, shuffleModeEnabled, periodUid, oldTimeline, newTimeline);
if (nextPeriodUid != null) {
// Reset position to the default position of the window of the subsequent period.
newTimeline.getPeriodByUid(nextPeriodUid, period);
return maskWindowPositionMsOrGetPeriodPositionUs(
newTimeline,
period.windowIndex,
newTimeline.getWindow(period.windowIndex, window).getDefaultPositionMs());
} else {
// No subsequent period found and the new timeline is not empty. Use the default position.
return maskWindowPositionMsOrGetPeriodPositionUs(
newTimeline, /* windowIndex= */ C.INDEX_UNSET, /* windowPositionMs= */ C.TIME_UNSET);
}
}
@Nullable
private Pair<Object, Long> maskWindowPositionMsOrGetPeriodPositionUs(
Timeline timeline, int windowIndex, long windowPositionMs) {
if (timeline.isEmpty()) {
// If empty we store the initial seek in the masking variables.
maskingWindowIndex = windowIndex;
maskingWindowPositionMs = windowPositionMs == C.TIME_UNSET ? 0 : windowPositionMs;
maskingPeriodIndex = 0;
return null;
}
if (windowIndex == C.INDEX_UNSET || windowIndex >= timeline.getWindowCount()) {
// Use default position of timeline if window index still unset or if a previous initial seek
// now turns out to be invalid.
windowIndex = timeline.getFirstWindowIndex(shuffleModeEnabled);
windowPositionMs = timeline.getWindow(windowIndex, window).getDefaultPositionMs();
}
return timeline.getPeriodPositionUs(window, period, windowIndex, Util.msToUs(windowPositionMs));
}
private long periodPositionUsToWindowPositionUs(
Timeline timeline, MediaPeriodId periodId, long positionUs) {
timeline.getPeriodByUid(periodId.periodUid, period);
positionUs += period.getPositionInWindowUs();
return positionUs;
}
private PlayerMessage createMessageInternal(Target target) {
int currentWindowIndex = getCurrentWindowIndexInternal();
return new PlayerMessage(
internalPlayer,
target,
playbackInfo.timeline,
currentWindowIndex == C.INDEX_UNSET ? 0 : currentWindowIndex,
clock,
internalPlayer.getPlaybackLooper());
}
/**
* Builds a {@link MediaMetadata} from the main sources.
*
* <p>{@link MediaItem} {@link MediaMetadata} is prioritized, with any gaps/missing fields
* populated by metadata from static ({@link TrackGroup} {@link Format}) and dynamic ({@link
* MetadataOutput#onMetadata(Metadata)}) sources.
*/
private MediaMetadata buildUpdatedMediaMetadata() {
Timeline timeline = getCurrentTimeline();
if (timeline.isEmpty()) {
return staticAndDynamicMediaMetadata;
}
MediaItem mediaItem = timeline.getWindow(getCurrentMediaItemIndex(), window).mediaItem;
// MediaItem metadata is prioritized over metadata within the media.
return staticAndDynamicMediaMetadata.buildUpon().populate(mediaItem.mediaMetadata).build();
}
private void removeSurfaceCallbacks() {
if (sphericalGLSurfaceView != null) {
createMessageInternal(frameMetadataListener)
.setType(FrameMetadataListener.MSG_SET_SPHERICAL_SURFACE_VIEW)
.setPayload(null)
.send();
sphericalGLSurfaceView.removeVideoSurfaceListener(componentListener);
sphericalGLSurfaceView = null;
}
if (textureView != null) {
if (textureView.getSurfaceTextureListener() != componentListener) {
Log.w(TAG, "SurfaceTextureListener already unset or replaced.");
} else {
textureView.setSurfaceTextureListener(null);
}
textureView = null;
}
if (surfaceHolder != null) {
surfaceHolder.removeCallback(componentListener);
surfaceHolder = null;
}
}
private void setSurfaceTextureInternal(SurfaceTexture surfaceTexture) {
Surface surface = new Surface(surfaceTexture);
setVideoOutputInternal(surface);
ownedSurface = surface;
}
private void setVideoOutputInternal(@Nullable Object videoOutput) {
// Note: We don't turn this method into a no-op if the output is being replaced with itself so
// as to ensure onRenderedFirstFrame callbacks are still called in this case.
List<PlayerMessage> messages = new ArrayList<>();
for (Renderer renderer : renderers) {
if (renderer.getTrackType() == TRACK_TYPE_VIDEO) {
messages.add(
createMessageInternal(renderer)
.setType(MSG_SET_VIDEO_OUTPUT)
.setPayload(videoOutput)
.send());
}
}
boolean messageDeliveryTimedOut = false;
if (this.videoOutput != null && this.videoOutput != videoOutput) {
// We're replacing an output. Block to ensure that this output will not be accessed by the
// renderers after this method returns.
try {
for (PlayerMessage message : messages) {
message.blockUntilDelivered(detachSurfaceTimeoutMs);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (TimeoutException e) {
messageDeliveryTimedOut = true;
}
if (this.videoOutput == ownedSurface) {
// We're replacing a surface that we are responsible for releasing.
try {
ownedSurface.release();
} catch (Throwable e) {
}
ownedSurface = null;
}
}
this.videoOutput = videoOutput;
if (messageDeliveryTimedOut) {
stopInternal(
/* reset= */ false,
ExoPlaybackException.createForUnexpected(
new ExoTimeoutException(ExoTimeoutException.TIMEOUT_OPERATION_DETACH_SURFACE),
PlaybackException.ERROR_CODE_TIMEOUT));
}
}
/**
* Sets the holder of the surface that will be displayed to the user, but which should
* <em>not</em> be the output for video renderers. This case occurs when video frames need to be
* rendered to an intermediate surface (which is not the one held by the provided holder).
*
* @param nonVideoOutputSurfaceHolder The holder of the surface that will eventually be displayed
* to the user.
*/
private void setNonVideoOutputSurfaceHolderInternal(SurfaceHolder nonVideoOutputSurfaceHolder) {
// Although we won't use the view's surface directly as the video output, still use the holder
// to query the surface size, to be informed in changes to the size via componentListener, and
// for equality checking in clearVideoSurfaceHolder.
surfaceHolderSurfaceIsVideoOutput = false;
surfaceHolder = nonVideoOutputSurfaceHolder;
surfaceHolder.addCallback(componentListener);
Surface surface = surfaceHolder.getSurface();
if (surface != null && surface.isValid()) {
Rect surfaceSize = surfaceHolder.getSurfaceFrame();
maybeNotifySurfaceSizeChanged(surfaceSize.width(), surfaceSize.height());
} else {
maybeNotifySurfaceSizeChanged(/* width= */ 0, /* height= */ 0);
}
}
private void maybeNotifySurfaceSizeChanged(int width, int height) {
if (width != surfaceSize.getWidth() || height != surfaceSize.getHeight()) {
surfaceSize = new Size(width, height);
if (workerQueue != null) {
workerQueue.postRunnable(() -> {
listeners.sendEvent(
EVENT_SURFACE_SIZE_CHANGED, listener -> listener.onSurfaceSizeChanged(width, height));
});
} else {
listeners.sendEvent(
EVENT_SURFACE_SIZE_CHANGED, listener -> listener.onSurfaceSizeChanged(width, height));
}
}
}
private void sendVolumeToRenderers() {
float scaledVolume = volume * audioFocusManager.getVolumeMultiplier();
sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_VOLUME, scaledVolume);
}
private void updatePlayWhenReady(
boolean playWhenReady,
@AudioFocusManager.PlayerCommand int playerCommand,
@Player.PlayWhenReadyChangeReason int playWhenReadyChangeReason) {
playWhenReady = playWhenReady && playerCommand != AudioFocusManager.PLAYER_COMMAND_DO_NOT_PLAY;
@PlaybackSuppressionReason
int playbackSuppressionReason =
playWhenReady && playerCommand != AudioFocusManager.PLAYER_COMMAND_PLAY_WHEN_READY
? Player.PLAYBACK_SUPPRESSION_REASON_TRANSIENT_AUDIO_FOCUS_LOSS
: Player.PLAYBACK_SUPPRESSION_REASON_NONE;
if (playbackInfo.playWhenReady == playWhenReady
&& playbackInfo.playbackSuppressionReason == playbackSuppressionReason) {
return;
}
pendingOperationAcks++;
PlaybackInfo playbackInfo =
this.playbackInfo.copyWithPlayWhenReady(playWhenReady, playbackSuppressionReason);
internalPlayer.setPlayWhenReady(playWhenReady, playbackSuppressionReason);
updatePlaybackInfo(
playbackInfo,
/* ignored */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED,
playWhenReadyChangeReason,
/* seekProcessed= */ false,
/* positionDiscontinuity= */ false,
/* ignored */ DISCONTINUITY_REASON_INTERNAL,
/* ignored */ C.TIME_UNSET,
/* ignored */ C.INDEX_UNSET,
/* repeatCurrentMediaItem= */ false);
}
private void updateWakeAndWifiLock() {
@State int playbackState = getPlaybackState();
switch (playbackState) {
case Player.STATE_READY:
case Player.STATE_BUFFERING:
boolean isSleeping = experimentalIsSleepingForOffload();
wakeLockManager.setStayAwake(getPlayWhenReady() && !isSleeping);
// The wifi lock is not released while sleeping to avoid interrupting downloads.
wifiLockManager.setStayAwake(getPlayWhenReady());
break;
case Player.STATE_ENDED:
case Player.STATE_IDLE:
wakeLockManager.setStayAwake(false);
wifiLockManager.setStayAwake(false);
break;
default:
throw new IllegalStateException();
}
}
private void verifyApplicationThread() {
// The constructor may be executed on a background thread. Wait with accessing the player from
// the app thread until the constructor finished executing.
constructorFinished.blockUninterruptible();
if (Thread.currentThread() != getApplicationLooper().getThread()) {
String message =
Util.formatInvariant(
"Player is accessed on the wrong thread.\n"
+ "Current thread: '%s'\n"
+ "Expected thread: '%s'\n"
+ "See https://exoplayer.dev/issues/player-accessed-on-wrong-thread",
Thread.currentThread().getName(), getApplicationLooper().getThread().getName());
if (throwsWhenUsingWrongThread) {
throw new IllegalStateException(message);
}
Log.w(TAG, message, hasNotifiedFullWrongThreadWarning ? null : new IllegalStateException());
hasNotifiedFullWrongThreadWarning = true;
}
}
private void sendRendererMessage(
@C.TrackType int trackType, int messageType, @Nullable Object payload) {
for (Renderer renderer : renderers) {
if (renderer.getTrackType() == trackType) {
createMessageInternal(renderer).setType(messageType).setPayload(payload).send();
}
}
}
/**
* Initializes {@link #keepSessionIdAudioTrack} to keep an audio session ID alive. If the audio
* session ID is {@link C#AUDIO_SESSION_ID_UNSET} then a new audio session ID is generated.
*
* <p>Use of this method is only required on API level 21 and earlier.
*
* @param audioSessionId The audio session ID, or {@link C#AUDIO_SESSION_ID_UNSET} to generate a
* new one.
* @return The audio session ID.
*/
private int initializeKeepSessionIdAudioTrack(int audioSessionId) {
if (keepSessionIdAudioTrack != null
&& keepSessionIdAudioTrack.getAudioSessionId() != audioSessionId) {
keepSessionIdAudioTrack.release();
keepSessionIdAudioTrack = null;
}
if (keepSessionIdAudioTrack == null) {
int sampleRate = 4000; // Minimum sample rate supported by the platform.
int channelConfig = AudioFormat.CHANNEL_OUT_MONO;
@C.PcmEncoding int encoding = C.ENCODING_PCM_16BIT;
int bufferSize = 2; // Use a two byte buffer, as it is not actually used for playback.
keepSessionIdAudioTrack =
new AudioTrack(
C.STREAM_TYPE_DEFAULT,
sampleRate,
channelConfig,
encoding,
bufferSize,
AudioTrack.MODE_STATIC,
audioSessionId);
}
return keepSessionIdAudioTrack.getAudioSessionId();
}
private void updatePriorityTaskManagerForIsLoadingChange(boolean isLoading) {
if (priorityTaskManager != null) {
if (isLoading && !isPriorityTaskManagerRegistered) {
priorityTaskManager.add(C.PRIORITY_PLAYBACK);
isPriorityTaskManagerRegistered = true;
} else if (!isLoading && isPriorityTaskManagerRegistered) {
priorityTaskManager.remove(C.PRIORITY_PLAYBACK);
isPriorityTaskManagerRegistered = false;
}
}
}
private static DeviceInfo createDeviceInfo(StreamVolumeManager streamVolumeManager) {
return new DeviceInfo(
DeviceInfo.PLAYBACK_TYPE_LOCAL,
streamVolumeManager.getMinVolume(),
streamVolumeManager.getMaxVolume());
}
private static int getPlayWhenReadyChangeReason(boolean playWhenReady, int playerCommand) {
return playWhenReady && playerCommand != AudioFocusManager.PLAYER_COMMAND_PLAY_WHEN_READY
? PLAY_WHEN_READY_CHANGE_REASON_AUDIO_FOCUS_LOSS
: PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST;
}
private static boolean isPlaying(PlaybackInfo playbackInfo) {
return playbackInfo.playbackState == Player.STATE_READY
&& playbackInfo.playWhenReady
&& playbackInfo.playbackSuppressionReason == PLAYBACK_SUPPRESSION_REASON_NONE;
}
private static final class MediaSourceHolderSnapshot implements MediaSourceInfoHolder {
private final Object uid;
private Timeline timeline;
public MediaSourceHolderSnapshot(Object uid, Timeline timeline) {
this.uid = uid;
this.timeline = timeline;
}
@Override
public Object getUid() {
return uid;
}
@Override
public Timeline getTimeline() {
return timeline;
}
}
private final class ComponentListener
implements VideoRendererEventListener,
AudioRendererEventListener,
TextOutput,
MetadataOutput,
SurfaceHolder.Callback,
TextureView.SurfaceTextureListener,
SphericalGLSurfaceView.VideoSurfaceListener,
AudioFocusManager.PlayerControl,
AudioBecomingNoisyManager.EventListener,
StreamVolumeManager.Listener,
AudioOffloadListener {
// VideoRendererEventListener implementation
@Override
public void onVideoEnabled(DecoderCounters counters) {
videoDecoderCounters = counters;
analyticsCollector.onVideoEnabled(counters);
}
@Override
public void onVideoDecoderInitialized(
String decoderName, long initializedTimestampMs, long initializationDurationMs) {
analyticsCollector.onVideoDecoderInitialized(
decoderName, initializedTimestampMs, initializationDurationMs);
}
@Override
public void onVideoInputFormatChanged(
Format format, @Nullable DecoderReuseEvaluation decoderReuseEvaluation) {
videoFormat = format;
analyticsCollector.onVideoInputFormatChanged(format, decoderReuseEvaluation);
}
@Override
public void onDroppedFrames(int count, long elapsed) {
analyticsCollector.onDroppedFrames(count, elapsed);
}
@Override
public void onVideoSizeChanged(VideoSize newVideoSize) {
videoSize = newVideoSize;
listeners.sendEvent(
EVENT_VIDEO_SIZE_CHANGED, listener -> listener.onVideoSizeChanged(newVideoSize));
}
@Override
public void onRenderedFirstFrame(Object output, long renderTimeMs) {
analyticsCollector.onRenderedFirstFrame(output, renderTimeMs);
if (videoOutput == output) {
listeners.sendEvent(EVENT_RENDERED_FIRST_FRAME, Listener::onRenderedFirstFrame);
}
}
@Override
public void onVideoDecoderReleased(String decoderName) {
analyticsCollector.onVideoDecoderReleased(decoderName);
}
@Override
public void onVideoDisabled(DecoderCounters counters) {
analyticsCollector.onVideoDisabled(counters);
videoFormat = null;
videoDecoderCounters = null;
}
@Override
public void onVideoFrameProcessingOffset(long totalProcessingOffsetUs, int frameCount) {
analyticsCollector.onVideoFrameProcessingOffset(totalProcessingOffsetUs, frameCount);
}
@Override
public void onVideoCodecError(Exception videoCodecError) {
analyticsCollector.onVideoCodecError(videoCodecError);
}
// AudioRendererEventListener implementation
@Override
public void onAudioEnabled(DecoderCounters counters) {
audioDecoderCounters = counters;
analyticsCollector.onAudioEnabled(counters);
}
@Override
public void onAudioDecoderInitialized(
String decoderName, long initializedTimestampMs, long initializationDurationMs) {
analyticsCollector.onAudioDecoderInitialized(
decoderName, initializedTimestampMs, initializationDurationMs);
}
@Override
public void onAudioInputFormatChanged(
Format format, @Nullable DecoderReuseEvaluation decoderReuseEvaluation) {
audioFormat = format;
analyticsCollector.onAudioInputFormatChanged(format, decoderReuseEvaluation);
}
@Override
public void onAudioPositionAdvancing(long playoutStartSystemTimeMs) {
analyticsCollector.onAudioPositionAdvancing(playoutStartSystemTimeMs);
}
@Override
public void onAudioUnderrun(int bufferSize, long bufferSizeMs, long elapsedSinceLastFeedMs) {
analyticsCollector.onAudioUnderrun(bufferSize, bufferSizeMs, elapsedSinceLastFeedMs);
}
@Override
public void onAudioDecoderReleased(String decoderName) {
analyticsCollector.onAudioDecoderReleased(decoderName);
}
@Override
public void onAudioDisabled(DecoderCounters counters) {
analyticsCollector.onAudioDisabled(counters);
audioFormat = null;
audioDecoderCounters = null;
}
@Override
public void onSkipSilenceEnabledChanged(boolean newSkipSilenceEnabled) {
if (skipSilenceEnabled == newSkipSilenceEnabled) {
return;
}
skipSilenceEnabled = newSkipSilenceEnabled;
listeners.sendEvent(
EVENT_SKIP_SILENCE_ENABLED_CHANGED,
listener -> listener.onSkipSilenceEnabledChanged(newSkipSilenceEnabled));
}
@Override
public void onAudioSinkError(Exception audioSinkError) {
analyticsCollector.onAudioSinkError(audioSinkError);
}
@Override
public void onAudioCodecError(Exception audioCodecError) {
analyticsCollector.onAudioCodecError(audioCodecError);
}
// TextOutput implementation
@Override
public void onCues(List<Cue> cues) {
listeners.sendEvent(EVENT_CUES, listener -> listener.onCues(cues));
}
@Override
public void onCues(CueGroup cueGroup) {
currentCueGroup = cueGroup;
listeners.sendEvent(EVENT_CUES, listener -> listener.onCues(cueGroup));
}
// MetadataOutput implementation
@Override
public void onMetadata(Metadata metadata) {
staticAndDynamicMediaMetadata =
staticAndDynamicMediaMetadata.buildUpon().populateFromMetadata(metadata).build();
MediaMetadata newMediaMetadata = buildUpdatedMediaMetadata();
if (!newMediaMetadata.equals(mediaMetadata)) {
mediaMetadata = newMediaMetadata;
listeners.queueEvent(
EVENT_MEDIA_METADATA_CHANGED,
listener -> listener.onMediaMetadataChanged(mediaMetadata));
}
listeners.queueEvent(EVENT_METADATA, listener -> listener.onMetadata(metadata));
listeners.flushEvents();
}
// SurfaceHolder.Callback implementation
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (surfaceHolderSurfaceIsVideoOutput) {
setVideoOutputInternal(holder.getSurface());
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
maybeNotifySurfaceSizeChanged(width, height);
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (surfaceHolderSurfaceIsVideoOutput) {
setVideoOutputInternal(/* videoOutput= */ null);
}
maybeNotifySurfaceSizeChanged(/* width= */ 0, /* height= */ 0);
}
// TextureView.SurfaceTextureListener implementation
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
if (workerQueue != null) {
workerQueue.postRunnable(() -> {
onSurfaceTextureAvailableInternal(surfaceTexture, width, height);
});
} else {
onSurfaceTextureAvailableInternal(surfaceTexture, width, height);
}
}
public void onSurfaceTextureAvailableInternal(SurfaceTexture surfaceTexture, int width, int height) {
setSurfaceTextureInternal(surfaceTexture);
maybeNotifySurfaceSizeChanged(width, height);
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int width, int height) {
if (workerQueue != null) {
workerQueue.postRunnable(() -> {
onSurfaceTextureSizeChangedInternal(surfaceTexture, width, height);
});
} else {
onSurfaceTextureSizeChangedInternal(surfaceTexture, width, height);
}
}
public void onSurfaceTextureSizeChangedInternal(SurfaceTexture surfaceTexture, int width, int height) {
maybeNotifySurfaceSizeChanged(width, height);
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
for (com.google.android.exoplayer2.video.VideoListener videoListener : videoListeners) {
if (videoListener.onSurfaceDestroyed(surfaceTexture)) {
return false;
}
}
if (workerQueue != null) {
workerQueue.postRunnable(() -> {
onSurfaceTextureDestroyedInternal(surfaceTexture);
});
} else {
onSurfaceTextureDestroyedInternal(surfaceTexture);
}
return true;
}
public void onSurfaceTextureDestroyedInternal(SurfaceTexture surfaceTexture) {
setVideoOutputInternal(/* videoOutput= */ null);
maybeNotifySurfaceSizeChanged(/* width= */ 0, /* height= */ 0);
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
if (workerQueue != null) {
workerQueue.postRunnable(() -> {
onSurfaceTextureUpdatedInternal(surfaceTexture);
});
} else {
onSurfaceTextureUpdatedInternal(surfaceTexture);
}
}
public void onSurfaceTextureUpdatedInternal(SurfaceTexture surfaceTexture) {
for (com.google.android.exoplayer2.video.VideoListener videoListener : videoListeners) {
videoListener.onSurfaceTextureUpdated(surfaceTexture);
}
// Do nothing.
}
// SphericalGLSurfaceView.VideoSurfaceListener
@Override
public void onVideoSurfaceCreated(Surface surface) {
setVideoOutputInternal(surface);
}
@Override
public void onVideoSurfaceDestroyed(Surface surface) {
setVideoOutputInternal(/* videoOutput= */ null);
}
// AudioFocusManager.PlayerControl implementation
@Override
public void setVolumeMultiplier(float volumeMultiplier) {
sendVolumeToRenderers();
}
@Override
public void executePlayerCommand(@AudioFocusManager.PlayerCommand int playerCommand) {
boolean playWhenReady = getPlayWhenReady();
updatePlayWhenReady(
playWhenReady, playerCommand, getPlayWhenReadyChangeReason(playWhenReady, playerCommand));
}
// AudioBecomingNoisyManager.EventListener implementation.
@Override
public void onAudioBecomingNoisy() {
updatePlayWhenReady(
/* playWhenReady= */ false,
AudioFocusManager.PLAYER_COMMAND_DO_NOT_PLAY,
Player.PLAY_WHEN_READY_CHANGE_REASON_AUDIO_BECOMING_NOISY);
}
// StreamVolumeManager.Listener implementation.
@Override
public void onStreamTypeChanged(@C.StreamType int streamType) {
DeviceInfo newDeviceInfo = createDeviceInfo(streamVolumeManager);
if (!newDeviceInfo.equals(deviceInfo)) {
deviceInfo = newDeviceInfo;
listeners.sendEvent(
EVENT_DEVICE_INFO_CHANGED, listener -> listener.onDeviceInfoChanged(newDeviceInfo));
}
}
@Override
public void onStreamVolumeChanged(int streamVolume, boolean streamMuted) {
listeners.sendEvent(
EVENT_DEVICE_VOLUME_CHANGED,
listener -> listener.onDeviceVolumeChanged(streamVolume, streamMuted));
}
// Player.AudioOffloadListener implementation.
@Override
public void onExperimentalSleepingForOffloadChanged(boolean sleepingForOffload) {
updateWakeAndWifiLock();
}
}
/** Listeners that are called on the playback thread. */
private static final class FrameMetadataListener
implements VideoFrameMetadataListener, CameraMotionListener, PlayerMessage.Target {
public static final @MessageType int MSG_SET_VIDEO_FRAME_METADATA_LISTENER =
Renderer.MSG_SET_VIDEO_FRAME_METADATA_LISTENER;
public static final @MessageType int MSG_SET_CAMERA_MOTION_LISTENER =
Renderer.MSG_SET_CAMERA_MOTION_LISTENER;
public static final @MessageType int MSG_SET_SPHERICAL_SURFACE_VIEW = Renderer.MSG_CUSTOM_BASE;
@Nullable private VideoFrameMetadataListener videoFrameMetadataListener;
@Nullable private CameraMotionListener cameraMotionListener;
@Nullable private VideoFrameMetadataListener internalVideoFrameMetadataListener;
@Nullable private CameraMotionListener internalCameraMotionListener;
@Override
public void handleMessage(@MessageType int messageType, @Nullable Object message) {
switch (messageType) {
case MSG_SET_VIDEO_FRAME_METADATA_LISTENER:
videoFrameMetadataListener = (VideoFrameMetadataListener) message;
break;
case MSG_SET_CAMERA_MOTION_LISTENER:
cameraMotionListener = (CameraMotionListener) message;
break;
case MSG_SET_SPHERICAL_SURFACE_VIEW:
@Nullable SphericalGLSurfaceView surfaceView = (SphericalGLSurfaceView) message;
if (surfaceView == null) {
internalVideoFrameMetadataListener = null;
internalCameraMotionListener = null;
} else {
internalVideoFrameMetadataListener = surfaceView.getVideoFrameMetadataListener();
internalCameraMotionListener = surfaceView.getCameraMotionListener();
}
break;
case Renderer.MSG_SET_AUDIO_ATTRIBUTES:
case Renderer.MSG_SET_AUDIO_SESSION_ID:
case Renderer.MSG_SET_AUX_EFFECT_INFO:
case Renderer.MSG_SET_CHANGE_FRAME_RATE_STRATEGY:
case Renderer.MSG_SET_SCALING_MODE:
case Renderer.MSG_SET_SKIP_SILENCE_ENABLED:
case Renderer.MSG_SET_VIDEO_OUTPUT:
case Renderer.MSG_SET_VOLUME:
case Renderer.MSG_SET_WAKEUP_LISTENER:
default:
break;
}
}
// VideoFrameMetadataListener
@Override
public void onVideoFrameAboutToBeRendered(
long presentationTimeUs,
long releaseTimeNs,
Format format,
@Nullable MediaFormat mediaFormat) {
if (internalVideoFrameMetadataListener != null) {
internalVideoFrameMetadataListener.onVideoFrameAboutToBeRendered(
presentationTimeUs, releaseTimeNs, format, mediaFormat);
}
if (videoFrameMetadataListener != null) {
videoFrameMetadataListener.onVideoFrameAboutToBeRendered(
presentationTimeUs, releaseTimeNs, format, mediaFormat);
}
}
// CameraMotionListener
@Override
public void onCameraMotion(long timeUs, float[] rotation) {
if (internalCameraMotionListener != null) {
internalCameraMotionListener.onCameraMotion(timeUs, rotation);
}
if (cameraMotionListener != null) {
cameraMotionListener.onCameraMotion(timeUs, rotation);
}
}
@Override
public void onCameraMotionReset() {
if (internalCameraMotionListener != null) {
internalCameraMotionListener.onCameraMotionReset();
}
if (cameraMotionListener != null) {
cameraMotionListener.onCameraMotionReset();
}
}
}
@RequiresApi(31)
private static final class Api31 {
private Api31() {}
@DoNotInline
public static PlayerId registerMediaMetricsListener(
Context context, ExoPlayerImpl player, boolean usePlatformDiagnostics) {
@Nullable MediaMetricsListener listener = MediaMetricsListener.create(context);
if (listener == null) {
Log.w(TAG, "MediaMetricsService unavailable.");
return new PlayerId(LogSessionId.LOG_SESSION_ID_NONE);
}
if (usePlatformDiagnostics) {
player.addAnalyticsListener(listener);
}
return new PlayerId(listener.getLogSessionId());
}
}
}
| Telegram-FOSS-Team/Telegram-FOSS | TMessagesProj/src/main/java/com/google/android/exoplayer2/ExoPlayerImpl.java |
2,775 | /*
* Scala (https://www.scala-lang.org)
*
* Copyright EPFL and Lightbend, Inc.
*
* Licensed under Apache License 2.0
* (http://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/
package scala.collection.concurrent;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
abstract class CNodeBase<K, V> extends MainNode<K, V> {
@SuppressWarnings("unchecked")
public static final AtomicIntegerFieldUpdater<CNodeBase<?, ?>> updater =
AtomicIntegerFieldUpdater.newUpdater((Class<CNodeBase<?, ?>>) (Class<?>) CNodeBase.class, "csize");
public volatile int csize = -1;
public boolean CAS_SIZE(int oldval, int nval) {
return updater.compareAndSet(this, oldval, nval);
}
public void WRITE_SIZE(int nval) {
updater.set(this, nval);
}
public int READ_SIZE() {
return updater.get(this);
}
}
| scala/scala | src/library/scala/collection/concurrent/CNodeBase.java |
2,776 | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2024 DBeaver Corp and others
*
* 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 org.jkiss.dbeaver.ui;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.model.runtime.RunnableWithResult;
import org.jkiss.dbeaver.runtime.DBWorkbench;
public abstract class UITask<RESULT> extends RunnableWithResult<RESULT> {
@Override
public final RESULT runWithResult() throws DBException {
return runTask();
}
protected abstract RESULT runTask() throws DBException;
public RESULT execute() {
return UIUtils.syncExec(this);
}
public interface TaskExecutor <T> {
T run() throws DBException;
}
public static <T> T run(TaskExecutor <T> runnable) {
return new UITask<T>() {
@Override
protected T runTask() {
try {
return runnable.run();
} catch (Exception e) {
DBWorkbench.getPlatformUI().showError("Task error", "Internal error: task " + runnable + "' failed", e);
return null;
}
}
}.execute();
}
} | dbeaver/dbeaver | plugins/org.jkiss.dbeaver.ui/src/org/jkiss/dbeaver/ui/UITask.java |
2,777 | package com.winterbe.java8.samples.concurrent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.StampedLock;
/**
* @author Benjamin Winterberg
*/
public class Lock5 {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);
StampedLock lock = new StampedLock();
executor.submit(() -> {
long stamp = lock.tryOptimisticRead();
try {
System.out.println("Optimistic Lock Valid: " + lock.validate(stamp));
ConcurrentUtils.sleep(1);
System.out.println("Optimistic Lock Valid: " + lock.validate(stamp));
ConcurrentUtils.sleep(2);
System.out.println("Optimistic Lock Valid: " + lock.validate(stamp));
} finally {
lock.unlock(stamp);
}
});
executor.submit(() -> {
long stamp = lock.writeLock();
try {
System.out.println("Write Lock acquired");
ConcurrentUtils.sleep(2);
} finally {
lock.unlock(stamp);
System.out.println("Write done");
}
});
ConcurrentUtils.stop(executor);
}
}
| winterbe/java8-tutorial | src/com/winterbe/java8/samples/concurrent/Lock5.java |
2,778 | /*
* Copyright 2017 The gRPC Authors
*
* 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 io.grpc;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
/** Read benchmark. */
public class ReadBenchmark {
@State(Scope.Benchmark)
public static class ContextState {
List<Context.Key<Object>> keys = new ArrayList<>();
List<Context> contexts = new ArrayList<>();
@Setup
public void setup() {
for (int i = 0; i < 8; i++) {
keys.add(Context.key("Key" + i));
}
contexts.add(Context.ROOT.withValue(keys.get(0), new Object()));
contexts.add(Context.ROOT.withValues(keys.get(0), new Object(), keys.get(1), new Object()));
contexts.add(
Context.ROOT.withValues(
keys.get(0), new Object(), keys.get(1), new Object(), keys.get(2), new Object()));
contexts.add(
Context.ROOT.withValues(
keys.get(0),
new Object(),
keys.get(1),
new Object(),
keys.get(2),
new Object(),
keys.get(3),
new Object()));
contexts.add(contexts.get(0).withValue(keys.get(1), new Object()));
contexts.add(
contexts.get(1).withValues(keys.get(2), new Object(), keys.get(3), new Object()));
contexts.add(
contexts
.get(2)
.withValues(
keys.get(3), new Object(), keys.get(4), new Object(), keys.get(5), new Object()));
contexts.add(
contexts
.get(3)
.withValues(
keys.get(4),
new Object(),
keys.get(5),
new Object(),
keys.get(6),
new Object(),
keys.get(7),
new Object()));
}
}
/** Perform the read operation. */
@Benchmark
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void testContextLookup(ContextState state, Blackhole bh) {
for (Context.Key<?> key : state.keys) {
for (Context ctx : state.contexts) {
bh.consume(key.get(ctx));
}
}
}
}
| grpc/grpc-java | api/src/jmh/java/io/grpc/ReadBenchmark.java |
2,779 | // Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package com.example.macrobenchmarks;
import io.flutter.embedding.android.FlutterActivity;
public class MainActivity extends FlutterActivity {
}
| flutter/flutter | dev/benchmarks/macrobenchmarks/android/app/src/main/java/com/example/macrobenchmarks/MainActivity.java |
2,780 | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2024 DBeaver Corp and others
*
* 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 org.jkiss.dbeaver.ui;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.e4.ui.css.swt.internal.theme.BootstrapTheme3x;
import org.eclipse.e4.ui.css.swt.theme.IThemeEngine;
import org.eclipse.e4.ui.css.swt.theme.IThemeManager;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.internal.IWorkbenchThemeConstants;
import org.eclipse.ui.preferences.ScopedPreferenceStore;
import org.jkiss.dbeaver.Log;
import org.jkiss.utils.CommonUtils;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;
/**
* UI Utils
*/
public class UIStyles {
private static final Log log = Log.getLog(UIStyles.class);
private static final String THEME_HIGH_CONTRAST_ID = "org.eclipse.e4.ui.css.theme.high-contrast";
static IPreferenceStore EDITORS_PREFERENCE_STORE;
static IThemeEngine themeEngine = null;
public static synchronized IPreferenceStore getEditorsPreferenceStore() {
if (EDITORS_PREFERENCE_STORE == null) {
EDITORS_PREFERENCE_STORE = new ScopedPreferenceStore(InstanceScope.INSTANCE, "org.eclipse.ui.editors");
}
return EDITORS_PREFERENCE_STORE;
}
public static boolean isDarkTheme() {
return UIUtils.isDark(getDefaultTextBackground().getRGB()) || isDarkHighContrastTheme();
}
private static IThemeEngine getThemeEngine() {
if (themeEngine == null) {
Bundle bundle = FrameworkUtil.getBundle(BootstrapTheme3x.class);
if (bundle != null) {
BundleContext context = bundle.getBundleContext();
if (context != null) {
ServiceReference<IThemeManager> ref = context.getServiceReference(IThemeManager.class);
if (ref != null) {
IThemeManager manager = context.getService(ref);
if (manager != null) {
themeEngine = manager.getEngineForDisplay(Display.getDefault());
}
}
}
}
}
return themeEngine;
}
public static boolean isHighContrastTheme() {
IThemeEngine themeEngine = getThemeEngine();
org.eclipse.e4.ui.css.swt.theme.ITheme theme = null;
if (themeEngine != null) {
theme = themeEngine.getActiveTheme();
} else {
themeEngine = PlatformUI.getWorkbench().getService(IThemeEngine.class);
if (themeEngine != null) {
theme = themeEngine.getActiveTheme();
}
}
if (theme != null) {
return theme.getId().equals(THEME_HIGH_CONTRAST_ID);
}
return false;
}
public static boolean isDarkHighContrastTheme() {
return isHighContrastTheme() && UIUtils.isDark(getDefaultWidgetBackground().getRGB());
}
public static Color getDefaultWidgetBackground() {
org.eclipse.ui.themes.ITheme theme = PlatformUI.getWorkbench().getThemeManager().getCurrentTheme();
Color color = theme.getColorRegistry().get(IWorkbenchThemeConstants.INACTIVE_TAB_BG_START);
if (color == null) {
color = Display.getCurrent().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND);
}
return color;
}
public static Color getDefaultTextBackground() {
return getDefaultTextColor("AbstractTextEditor.Color.Background", SWT.COLOR_LIST_BACKGROUND);
}
public static Color getDefaultTextForeground() {
return getDefaultTextColor("AbstractTextEditor.Color.Foreground", SWT.COLOR_LIST_FOREGROUND);
}
public static Color getDefaultTextSelectionBackground() {
return getDefaultTextColor("AbstractTextEditor.Color.SelectionBackground", SWT.COLOR_LIST_SELECTION);
}
public static Color getDefaultTextSelectionForeground() {
return getDefaultTextColor("AbstractTextEditor.Color.SelectionForeground", SWT.COLOR_LIST_SELECTION_TEXT);
}
public static Color getDefaultTextColor(String id, int defSWT) {
IPreferenceStore preferenceStore = getEditorsPreferenceStore();
String fgRGB = preferenceStore == null ? null : preferenceStore.getString(id);
return CommonUtils.isEmpty(fgRGB) ? Display.getDefault().getSystemColor(defSWT) : UIUtils.getSharedColor(fgRGB);
}
public static Color getErrorTextForeground() {
return getDefaultTextColor("AbstractTextEditor.Error.Color.Foreground", SWT.COLOR_RED);
}
}
| dbeaver/dbeaver | plugins/org.jkiss.dbeaver.ui/src/org/jkiss/dbeaver/ui/UIStyles.java |
2,781 | /*
* Copyright (C) 2012 The Guava Authors
*
* 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 com.google.common.testing;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.CharMatcher;
import com.google.common.base.Charsets;
import com.google.common.base.Defaults;
import com.google.common.base.Equivalence;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.base.Splitter;
import com.google.common.base.Stopwatch;
import com.google.common.base.Ticker;
import com.google.common.collect.BiMap;
import com.google.common.collect.ClassToInstanceMap;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableClassToInstanceMap;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableMultiset;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.ImmutableSortedMultiset;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.ImmutableTable;
import com.google.common.collect.Iterators;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.MapDifference;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Multiset;
import com.google.common.collect.Ordering;
import com.google.common.collect.PeekingIterator;
import com.google.common.collect.Range;
import com.google.common.collect.RowSortedTable;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.Sets;
import com.google.common.collect.SortedMapDifference;
import com.google.common.collect.SortedMultiset;
import com.google.common.collect.SortedSetMultimap;
import com.google.common.collect.Table;
import com.google.common.collect.Tables;
import com.google.common.collect.TreeBasedTable;
import com.google.common.collect.TreeMultimap;
import com.google.common.io.ByteSink;
import com.google.common.io.ByteSource;
import com.google.common.io.ByteStreams;
import com.google.common.io.CharSink;
import com.google.common.io.CharSource;
import com.google.common.primitives.Primitives;
import com.google.common.primitives.UnsignedInteger;
import com.google.common.primitives.UnsignedLong;
import com.google.errorprone.annotations.Keep;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Serializable;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.GenericDeclaration;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import java.nio.ShortBuffer;
import java.nio.charset.Charset;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Currency;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
import java.util.Map;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.UUID;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Supplies an arbitrary "default" instance for a wide range of types, often useful in testing
* utilities.
*
* <p>Covers arrays, enums and common types defined in {@code java.lang}, {@code java.lang.reflect},
* {@code java.io}, {@code java.nio}, {@code java.math}, {@code java.util}, {@code
* java.util.concurrent}, {@code java.util.regex}, {@code com.google.common.base}, {@code
* com.google.common.collect} and {@code com.google.common.primitives}. In addition, if the type
* exposes at least one public static final constant of the same type, one of the constants will be
* used; or if the class exposes a public parameter-less constructor then it will be "new"d and
* returned.
*
* <p>All default instances returned by {@link #get} are generics-safe. Clients won't get type
* errors for using {@code get(Comparator.class)} as a {@code Comparator<Foo>}, for example.
* Immutable empty instances are returned for collection types; {@code ""} for string; {@code 0} for
* number types; reasonable default instance for other stateless types. For mutable types, a fresh
* instance is created each time {@code get()} is called.
*
* @author Kevin Bourrillion
* @author Ben Yu
* @since 12.0
*/
@GwtIncompatible
@J2ktIncompatible
@ElementTypesAreNonnullByDefault
public final class ArbitraryInstances {
private static final Ordering<Field> BY_FIELD_NAME =
new Ordering<Field>() {
@Override
public int compare(Field left, Field right) {
return left.getName().compareTo(right.getName());
}
};
/**
* Returns a new {@code MatchResult} that corresponds to a successful match. Apache Harmony (used
* in Android) requires a successful match in order to generate a {@code MatchResult}:
* http://goo.gl/5VQFmC
*/
private static MatchResult createMatchResult() {
Matcher matcher = Pattern.compile(".").matcher("X");
matcher.find();
return matcher.toMatchResult();
}
private static final ClassToInstanceMap<Object> DEFAULTS =
ImmutableClassToInstanceMap.builder()
// primitives
.put(Object.class, "")
.put(Number.class, 0)
.put(UnsignedInteger.class, UnsignedInteger.ZERO)
.put(UnsignedLong.class, UnsignedLong.ZERO)
.put(BigInteger.class, BigInteger.ZERO)
.put(BigDecimal.class, BigDecimal.ZERO)
.put(CharSequence.class, "")
.put(String.class, "")
.put(Pattern.class, Pattern.compile(""))
.put(MatchResult.class, createMatchResult())
.put(TimeUnit.class, TimeUnit.SECONDS)
.put(Charset.class, Charsets.UTF_8)
.put(Currency.class, Currency.getInstance(Locale.US))
.put(Locale.class, Locale.US)
.put(UUID.class, UUID.randomUUID())
// common.base
.put(CharMatcher.class, CharMatcher.none())
.put(Joiner.class, Joiner.on(','))
.put(Splitter.class, Splitter.on(','))
.put(com.google.common.base.Optional.class, com.google.common.base.Optional.absent())
.put(Predicate.class, Predicates.alwaysTrue())
.put(Equivalence.class, Equivalence.equals())
.put(Ticker.class, Ticker.systemTicker())
.put(Stopwatch.class, Stopwatch.createUnstarted())
// io types
.put(InputStream.class, new ByteArrayInputStream(new byte[0]))
.put(ByteArrayInputStream.class, new ByteArrayInputStream(new byte[0]))
.put(Readable.class, new StringReader(""))
.put(Reader.class, new StringReader(""))
.put(StringReader.class, new StringReader(""))
.put(Buffer.class, ByteBuffer.allocate(0))
.put(CharBuffer.class, CharBuffer.allocate(0))
.put(ByteBuffer.class, ByteBuffer.allocate(0))
.put(ShortBuffer.class, ShortBuffer.allocate(0))
.put(IntBuffer.class, IntBuffer.allocate(0))
.put(LongBuffer.class, LongBuffer.allocate(0))
.put(FloatBuffer.class, FloatBuffer.allocate(0))
.put(DoubleBuffer.class, DoubleBuffer.allocate(0))
.put(File.class, new File(""))
.put(ByteSource.class, ByteSource.empty())
.put(CharSource.class, CharSource.empty())
.put(ByteSink.class, NullByteSink.INSTANCE)
.put(CharSink.class, NullByteSink.INSTANCE.asCharSink(Charsets.UTF_8))
// All collections are immutable empty. So safe for any type parameter.
.put(Iterator.class, ImmutableSet.of().iterator())
.put(PeekingIterator.class, Iterators.peekingIterator(ImmutableSet.of().iterator()))
.put(ListIterator.class, ImmutableList.of().listIterator())
.put(Iterable.class, ImmutableSet.of())
.put(Collection.class, ImmutableList.of())
.put(ImmutableCollection.class, ImmutableList.of())
.put(List.class, ImmutableList.of())
.put(ImmutableList.class, ImmutableList.of())
.put(Set.class, ImmutableSet.of())
.put(ImmutableSet.class, ImmutableSet.of())
.put(SortedSet.class, ImmutableSortedSet.of())
.put(ImmutableSortedSet.class, ImmutableSortedSet.of())
.put(NavigableSet.class, Sets.unmodifiableNavigableSet(Sets.newTreeSet()))
.put(Map.class, ImmutableMap.of())
.put(ImmutableMap.class, ImmutableMap.of())
.put(SortedMap.class, ImmutableSortedMap.of())
.put(ImmutableSortedMap.class, ImmutableSortedMap.of())
.put(NavigableMap.class, Maps.unmodifiableNavigableMap(Maps.newTreeMap()))
.put(Multimap.class, ImmutableMultimap.of())
.put(ImmutableMultimap.class, ImmutableMultimap.of())
.put(ListMultimap.class, ImmutableListMultimap.of())
.put(ImmutableListMultimap.class, ImmutableListMultimap.of())
.put(SetMultimap.class, ImmutableSetMultimap.of())
.put(ImmutableSetMultimap.class, ImmutableSetMultimap.of())
.put(
SortedSetMultimap.class,
Multimaps.unmodifiableSortedSetMultimap(TreeMultimap.create()))
.put(Multiset.class, ImmutableMultiset.of())
.put(ImmutableMultiset.class, ImmutableMultiset.of())
.put(SortedMultiset.class, ImmutableSortedMultiset.of())
.put(ImmutableSortedMultiset.class, ImmutableSortedMultiset.of())
.put(BiMap.class, ImmutableBiMap.of())
.put(ImmutableBiMap.class, ImmutableBiMap.of())
.put(Table.class, ImmutableTable.of())
.put(ImmutableTable.class, ImmutableTable.of())
.put(RowSortedTable.class, Tables.unmodifiableRowSortedTable(TreeBasedTable.create()))
.put(ClassToInstanceMap.class, ImmutableClassToInstanceMap.builder().build())
.put(ImmutableClassToInstanceMap.class, ImmutableClassToInstanceMap.builder().build())
.put(Comparable.class, ByToString.INSTANCE)
.put(Comparator.class, AlwaysEqual.INSTANCE)
.put(Ordering.class, AlwaysEqual.INSTANCE)
.put(Range.class, Range.all())
.put(MapDifference.class, Maps.difference(ImmutableMap.of(), ImmutableMap.of()))
.put(
SortedMapDifference.class,
Maps.difference(ImmutableSortedMap.of(), ImmutableSortedMap.of()))
// reflect
.put(AnnotatedElement.class, Object.class)
.put(GenericDeclaration.class, Object.class)
.put(Type.class, Object.class)
.build();
/**
* type → implementation. Inherently mutable interfaces and abstract classes are mapped to their
* default implementations and are "new"d upon get().
*/
private static final ConcurrentMap<Class<?>, Class<?>> implementations = Maps.newConcurrentMap();
private static <T> void setImplementation(Class<T> type, Class<? extends T> implementation) {
checkArgument(type != implementation, "Don't register %s to itself!", type);
checkArgument(
!DEFAULTS.containsKey(type), "A default value was already registered for %s", type);
checkArgument(
implementations.put(type, implementation) == null,
"Implementation for %s was already registered",
type);
}
static {
setImplementation(Appendable.class, StringBuilder.class);
setImplementation(BlockingQueue.class, LinkedBlockingDeque.class);
setImplementation(BlockingDeque.class, LinkedBlockingDeque.class);
setImplementation(ConcurrentMap.class, ConcurrentHashMap.class);
setImplementation(ConcurrentNavigableMap.class, ConcurrentSkipListMap.class);
setImplementation(CountDownLatch.class, Dummies.DummyCountDownLatch.class);
setImplementation(Deque.class, ArrayDeque.class);
setImplementation(OutputStream.class, ByteArrayOutputStream.class);
setImplementation(PrintStream.class, Dummies.InMemoryPrintStream.class);
setImplementation(PrintWriter.class, Dummies.InMemoryPrintWriter.class);
setImplementation(Queue.class, ArrayDeque.class);
setImplementation(Random.class, Dummies.DeterministicRandom.class);
setImplementation(
ScheduledThreadPoolExecutor.class, Dummies.DummyScheduledThreadPoolExecutor.class);
setImplementation(ThreadPoolExecutor.class, Dummies.DummyScheduledThreadPoolExecutor.class);
setImplementation(Writer.class, StringWriter.class);
setImplementation(Runnable.class, Dummies.DummyRunnable.class);
setImplementation(ThreadFactory.class, Dummies.DummyThreadFactory.class);
setImplementation(Executor.class, Dummies.DummyExecutor.class);
}
@SuppressWarnings("unchecked") // it's a subtype map
private static <T> @Nullable Class<? extends T> getImplementation(Class<T> type) {
return (Class<? extends T>) implementations.get(type);
}
private static final Logger logger = Logger.getLogger(ArbitraryInstances.class.getName());
/**
* Returns an arbitrary instance for {@code type}, or {@code null} if no arbitrary instance can be
* determined.
*/
public static <T> @Nullable T get(Class<T> type) {
T defaultValue = DEFAULTS.getInstance(type);
if (defaultValue != null) {
return defaultValue;
}
Class<? extends T> implementation = getImplementation(type);
if (implementation != null) {
return get(implementation);
}
if (type.isEnum()) {
T[] enumConstants = type.getEnumConstants();
return (enumConstants == null || enumConstants.length == 0) ? null : enumConstants[0];
}
if (type.isArray()) {
return createEmptyArray(type);
}
T jvmDefault = Defaults.defaultValue(Primitives.unwrap(type));
if (jvmDefault != null) {
return jvmDefault;
}
if (Modifier.isAbstract(type.getModifiers()) || !Modifier.isPublic(type.getModifiers())) {
return arbitraryConstantInstanceOrNull(type);
}
final Constructor<T> constructor;
try {
constructor = type.getConstructor();
} catch (NoSuchMethodException e) {
return arbitraryConstantInstanceOrNull(type);
}
constructor.setAccessible(true); // accessibility check is too slow
try {
return constructor.newInstance();
} catch (InstantiationException | IllegalAccessException impossible) {
throw new AssertionError(impossible);
} catch (InvocationTargetException e) {
logger.log(Level.WARNING, "Exception while invoking default constructor.", e.getCause());
return arbitraryConstantInstanceOrNull(type);
}
}
private static <T> @Nullable T arbitraryConstantInstanceOrNull(Class<T> type) {
Field[] fields = type.getDeclaredFields();
Arrays.sort(fields, BY_FIELD_NAME);
for (Field field : fields) {
if (Modifier.isPublic(field.getModifiers())
&& Modifier.isStatic(field.getModifiers())
&& Modifier.isFinal(field.getModifiers())) {
if (field.getGenericType() == field.getType() && type.isAssignableFrom(field.getType())) {
field.setAccessible(true);
try {
T constant = type.cast(field.get(null));
if (constant != null) {
return constant;
}
} catch (IllegalAccessException impossible) {
throw new AssertionError(impossible);
}
}
}
}
return null;
}
private static <T> T createEmptyArray(Class<T> arrayType) {
// getComponentType() is non-null because we call createEmptyArray only with an array type.
return arrayType.cast(Array.newInstance(requireNonNull(arrayType.getComponentType()), 0));
}
// Internal implementations of some classes, with public default constructor that get() needs.
private static final class Dummies {
public static final class InMemoryPrintStream extends PrintStream {
public InMemoryPrintStream() {
super(new ByteArrayOutputStream());
}
}
public static final class InMemoryPrintWriter extends PrintWriter {
public InMemoryPrintWriter() {
super(new StringWriter());
}
}
public static final class DeterministicRandom extends Random {
@Keep
public DeterministicRandom() {
super(0);
}
}
public static final class DummyScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor {
public DummyScheduledThreadPoolExecutor() {
super(1);
}
}
public static final class DummyCountDownLatch extends CountDownLatch {
public DummyCountDownLatch() {
super(0);
}
}
public static final class DummyRunnable implements Runnable, Serializable {
@Override
public void run() {}
}
public static final class DummyThreadFactory implements ThreadFactory, Serializable {
@Override
public Thread newThread(Runnable r) {
return new Thread(r);
}
}
public static final class DummyExecutor implements Executor, Serializable {
@Override
public void execute(Runnable command) {}
}
}
private static final class NullByteSink extends ByteSink implements Serializable {
private static final NullByteSink INSTANCE = new NullByteSink();
@Override
public OutputStream openStream() {
return ByteStreams.nullOutputStream();
}
}
// Compare by toString() to satisfy 2 properties:
// 1. compareTo(null) should throw NullPointerException
// 2. the order is deterministic and easy to understand, for debugging purpose.
@SuppressWarnings("ComparableType")
private static final class ByToString implements Comparable<Object>, Serializable {
private static final ByToString INSTANCE = new ByToString();
@Override
public int compareTo(Object o) {
return toString().compareTo(o.toString());
}
@Override
public String toString() {
return "BY_TO_STRING";
}
private Object readResolve() {
return INSTANCE;
}
}
// Always equal is a valid total ordering. And it works for any Object.
private static final class AlwaysEqual extends Ordering<@Nullable Object>
implements Serializable {
private static final AlwaysEqual INSTANCE = new AlwaysEqual();
@Override
public int compare(@Nullable Object o1, @Nullable Object o2) {
return 0;
}
@Override
public String toString() {
return "ALWAYS_EQUAL";
}
private Object readResolve() {
return INSTANCE;
}
}
private ArbitraryInstances() {}
}
| google/guava | android/guava-testlib/src/com/google/common/testing/ArbitraryInstances.java |
2,782 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you 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:
*
* https://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 io.netty.handler.codec.compression;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.SystemPropertyUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
/**
* Creates a new {@link ZlibEncoder} and a new {@link ZlibDecoder}.
*/
public final class ZlibCodecFactory {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(ZlibCodecFactory.class);
private static final int DEFAULT_JDK_WINDOW_SIZE = 15;
private static final int DEFAULT_JDK_MEM_LEVEL = 8;
private static final boolean noJdkZlibDecoder;
private static final boolean noJdkZlibEncoder;
private static final boolean supportsWindowSizeAndMemLevel;
static {
noJdkZlibDecoder = SystemPropertyUtil.getBoolean("io.netty.noJdkZlibDecoder",
PlatformDependent.javaVersion() < 7);
logger.debug("-Dio.netty.noJdkZlibDecoder: {}", noJdkZlibDecoder);
noJdkZlibEncoder = SystemPropertyUtil.getBoolean("io.netty.noJdkZlibEncoder", false);
logger.debug("-Dio.netty.noJdkZlibEncoder: {}", noJdkZlibEncoder);
supportsWindowSizeAndMemLevel = noJdkZlibDecoder || PlatformDependent.javaVersion() >= 7;
}
/**
* Returns {@code true} if specify a custom window size and mem level is supported.
*/
public static boolean isSupportingWindowSizeAndMemLevel() {
return supportsWindowSizeAndMemLevel;
}
public static ZlibEncoder newZlibEncoder(int compressionLevel) {
if (PlatformDependent.javaVersion() < 7 || noJdkZlibEncoder) {
return new JZlibEncoder(compressionLevel);
} else {
return new JdkZlibEncoder(compressionLevel);
}
}
public static ZlibEncoder newZlibEncoder(ZlibWrapper wrapper) {
if (PlatformDependent.javaVersion() < 7 || noJdkZlibEncoder) {
return new JZlibEncoder(wrapper);
} else {
return new JdkZlibEncoder(wrapper);
}
}
public static ZlibEncoder newZlibEncoder(ZlibWrapper wrapper, int compressionLevel) {
if (PlatformDependent.javaVersion() < 7 || noJdkZlibEncoder) {
return new JZlibEncoder(wrapper, compressionLevel);
} else {
return new JdkZlibEncoder(wrapper, compressionLevel);
}
}
public static ZlibEncoder newZlibEncoder(ZlibWrapper wrapper, int compressionLevel, int windowBits, int memLevel) {
if (PlatformDependent.javaVersion() < 7 || noJdkZlibEncoder ||
windowBits != DEFAULT_JDK_WINDOW_SIZE || memLevel != DEFAULT_JDK_MEM_LEVEL) {
return new JZlibEncoder(wrapper, compressionLevel, windowBits, memLevel);
} else {
return new JdkZlibEncoder(wrapper, compressionLevel);
}
}
public static ZlibEncoder newZlibEncoder(byte[] dictionary) {
if (PlatformDependent.javaVersion() < 7 || noJdkZlibEncoder) {
return new JZlibEncoder(dictionary);
} else {
return new JdkZlibEncoder(dictionary);
}
}
public static ZlibEncoder newZlibEncoder(int compressionLevel, byte[] dictionary) {
if (PlatformDependent.javaVersion() < 7 || noJdkZlibEncoder) {
return new JZlibEncoder(compressionLevel, dictionary);
} else {
return new JdkZlibEncoder(compressionLevel, dictionary);
}
}
public static ZlibEncoder newZlibEncoder(int compressionLevel, int windowBits, int memLevel, byte[] dictionary) {
if (PlatformDependent.javaVersion() < 7 || noJdkZlibEncoder ||
windowBits != DEFAULT_JDK_WINDOW_SIZE || memLevel != DEFAULT_JDK_MEM_LEVEL) {
return new JZlibEncoder(compressionLevel, windowBits, memLevel, dictionary);
} else {
return new JdkZlibEncoder(compressionLevel, dictionary);
}
}
public static ZlibDecoder newZlibDecoder() {
if (PlatformDependent.javaVersion() < 7 || noJdkZlibDecoder) {
return new JZlibDecoder();
} else {
return new JdkZlibDecoder(true);
}
}
public static ZlibDecoder newZlibDecoder(ZlibWrapper wrapper) {
if (PlatformDependent.javaVersion() < 7 || noJdkZlibDecoder) {
return new JZlibDecoder(wrapper);
} else {
return new JdkZlibDecoder(wrapper, true);
}
}
public static ZlibDecoder newZlibDecoder(byte[] dictionary) {
if (PlatformDependent.javaVersion() < 7 || noJdkZlibDecoder) {
return new JZlibDecoder(dictionary);
} else {
return new JdkZlibDecoder(dictionary);
}
}
private ZlibCodecFactory() {
// Unused
}
}
| netty/netty | codec/src/main/java/io/netty/handler/codec/compression/ZlibCodecFactory.java |
2,783 | /* Copyright (c) 2007-2013 Timothy Wall, All Rights Reserved
*
* The contents of this file is dual-licensed under 2
* alternative Open Source/Free licenses: LGPL 2.1 or later and
* Apache License 2.0. (starting with JNA version 4.0.0).
*
* You can freely decide which license you want to apply to
* the project.
*
* You may obtain a copy of the LGPL License at:
*
* http://www.gnu.org/licenses/licenses.html
*
* A copy is also included in the downloadable source code package
* containing JNA, in file "LGPL2.1".
*
* You may obtain a copy of the Apache License at:
*
* http://www.apache.org/licenses/
*
* A copy is also included in the downloadable source code package
* containing JNA, in file "AL2.0".
*/
package com.sun.jna;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.nio.Buffer;
import java.util.AbstractCollection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Represents a native structure with a Java peer class. When used as a
* function parameter or return value, this class corresponds to
* <code>struct*</code>. When used as a field within another
* <code>Structure</code>, it corresponds to <code>struct</code>. The
* tagging interfaces {@link ByReference} and {@link ByValue} may be used
* to alter the default behavior. Structures may have variable size, but only
* by providing an array field (e.g. byte[]).
* <p>
* See the <a href={@docRoot}/overview-summary.html>overview</a> for supported
* type mappings for struct fields.
* <p>
* Structure alignment and type mappings are derived by default from the
* enclosing interface definition (if any) by using
* {@link Native#getStructureAlignment} and {@link Native#getTypeMapper}.
* Alternatively you can explicitly provide alignment, field order, or type
* mapping by calling the respective Structure functions in your subclass's
* constructor.
* </p>
* <p>Structure fields corresponding to native struct fields <em>must</em> be
* public. If your structure is to have no fields of its own, it must be
* declared abstract.
* </p>
* <p>You <em>must</em> annotate the class with {@link FieldOrder} or implement
* {@link #getFieldOrder}, whichever you choose it must contain the field names
* (Strings) indicating the proper order of the fields. If you chose to implement
* {@link #getFieldOrder} notice that when dealing with multiple levels of
* subclasses of Structure, you must add to the list provided by the superclass
* {@link #getFieldOrder} the fields defined in the current class.
* </p>
* <p>In the past, most VMs would return them in a predictable order, but the JVM
* spec does not require it, so {@link #getFieldOrder} is now required to
* ensure JNA knows the proper order).
* </p>
* <p>Structure fields may additionally have the following modifiers:</p>
* <ul>
* <li><code>volatile</code> JNA will not write the field unless specifically
* instructed to do so via {@link #writeField(String)}. This allows you to
* prevent inadvertently overwriting memory that may be updated in real time
* on another (possibly native) thread.
* <li><code>final</code> JNA will overwrite the field via {@link #read()},
* but otherwise the field is not modifiable from Java. Take care when using
* this option, since the compiler will usually assume <em>all</em> accesses
* to the field (for a given Structure instance) have the same value. This
* modifier is invalid to use on J2ME.
* </ul>
* <p>NOTE: Strings are used to represent native C strings because usage of
* <code>char *</code> is generally more common than <code>wchar_t *</code>.
* You may provide a type mapper ({@link com.sun.jna.win32.W32APITypeMapper
* example here)} if you prefer to use String in place of {@link WString} if
* your native code predominantly uses <code>wchar_t *</code>.
* </p>
* <p>NOTE: In general, instances of this class are <em>not</em> synchronized.
* </p>
*
* @author Todd Fast, [email protected]
* @author [email protected]
*/
public abstract class Structure {
private static final Logger LOG = Logger.getLogger(Structure.class.getName());
/** Tagging interface to indicate the value of an instance of the
* <code>Structure</code> type is to be used in function invocations rather
* than its address. The default behavior is to treat
* <code>Structure</code> function parameters and return values as by
* reference, meaning the address of the structure is used.
*/
public interface ByValue { }
/** Tagging interface to indicate the address of an instance of the
* Structure type is to be used within a <code>Structure</code> definition
* rather than nesting the full Structure contents. The default behavior
* is to inline <code>Structure</code> fields.
*/
public interface ByReference { }
/** A class to keep NativeString instances alive and avoid writing the same value again and again */
private static class NativeStringTracking {
private final Object value;
private NativeString peer;
NativeStringTracking(Object lastValue) {
this.value = lastValue;
}
}
/** Use the platform default alignment. */
public static final int ALIGN_DEFAULT = 0;
/** No alignment, place all fields on nearest 1-byte boundary */
public static final int ALIGN_NONE = 1;
/** validated for 32-bit x86 linux/gcc; align field size, max 4 bytes */
public static final int ALIGN_GNUC = 2;
/** validated for w32/msvc; align on field size */
public static final int ALIGN_MSVC = 3;
/** Align to a 2-byte boundary. */
//public static final int ALIGN_2 = 4;
/** Align to a 4-byte boundary. */
//public static final int ALIGN_4 = 5;
/** Align to an 8-byte boundary. */
//public static final int ALIGN_8 = 6;
protected static final int CALCULATE_SIZE = -1;
static final Map<Class<?>, LayoutInfo> layoutInfo = new WeakHashMap<>();
static final Map<Class<?>, List<String>> fieldOrder = new WeakHashMap<>();
// This field is accessed by native code
private Pointer memory;
private int size = CALCULATE_SIZE;
private int alignType;
private String encoding;
private int actualAlignType;
private int structAlignment;
private Map<String, StructField> structFields;
// Keep track of native C strings which have been allocated,
// corresponding to String fields of this Structure
private final Map<String, NativeStringTracking> nativeStrings = new HashMap<>(8);
private TypeMapper typeMapper;
// This field is accessed by native code
private long typeInfo;
private boolean autoRead = true;
private boolean autoWrite = true;
// Keep a reference when this structure is mapped to an array
private Structure[] array;
private boolean readCalled;
protected Structure() {
this(ALIGN_DEFAULT);
}
protected Structure(TypeMapper mapper) {
this(null, ALIGN_DEFAULT, mapper);
}
protected Structure(int alignType) {
this(null, alignType);
}
protected Structure(int alignType, TypeMapper mapper) {
this(null, alignType, mapper);
}
/** Create a structure cast onto pre-allocated memory. */
protected Structure(Pointer p) {
this(p, ALIGN_DEFAULT);
}
protected Structure(Pointer p, int alignType) {
this(p, alignType, null);
}
protected Structure(Pointer p, int alignType, TypeMapper mapper) {
setAlignType(alignType);
setStringEncoding(Native.getStringEncoding(getClass()));
initializeTypeMapper(mapper);
validateFields();
if (p != null) {
useMemory(p, 0, true);
}
else {
allocateMemory(CALCULATE_SIZE);
}
initializeFields();
}
/** Return all fields in this structure (ordered). This represents the
* layout of the structure, and will be shared among Structures of the
* same class except when the Structure can have a variable size.
* NOTE: {@link #ensureAllocated()} <em>must</em> be called prior to
* calling this method.
* @return {@link Map} of field names to field representations.
*/
Map<String, StructField> fields() {
return structFields;
}
/**
* @return the type mapper in effect for this Structure.
*/
TypeMapper getTypeMapper() {
return typeMapper;
}
/** Initialize the type mapper for this structure.
* If <code>null</code>, the default mapper for the
* defining class will be used.
* @param mapper Find the type mapper appropriate for this structure's
* context if none was explicitly set.
*/
private void initializeTypeMapper(TypeMapper mapper) {
if (mapper == null) {
mapper = Native.getTypeMapper(getClass());
}
this.typeMapper = mapper;
layoutChanged();
}
/** Call whenever a Structure setting is changed which might affect its
* memory layout.
*/
private void layoutChanged() {
if (this.size != CALCULATE_SIZE) {
this.size = CALCULATE_SIZE;
if (this.memory instanceof AutoAllocated) {
this.memory = null;
}
// recalculate layout, since it was done once already
ensureAllocated();
}
}
/** Set the desired encoding to use when writing String fields to native
* memory.
* @param encoding desired encoding
*/
protected void setStringEncoding(String encoding) {
this.encoding = encoding;
}
/** Encoding to use to convert {@link String} to native <code>const
* char*</code>. Defaults to {@link Native#getDefaultStringEncoding()}.
* @return Current encoding
*/
protected String getStringEncoding() {
return this.encoding;
}
/** Change the alignment of this structure. Re-allocates memory if
* necessary. If alignment is {@link #ALIGN_DEFAULT}, the default
* alignment for the defining class will be used.
* @param alignType desired alignment type
*/
protected void setAlignType(int alignType) {
this.alignType = alignType;
if (alignType == ALIGN_DEFAULT) {
alignType = Native.getStructureAlignment(getClass());
if (alignType == ALIGN_DEFAULT) {
if (Platform.isWindows())
alignType = ALIGN_MSVC;
else
alignType = ALIGN_GNUC;
}
}
this.actualAlignType = alignType;
layoutChanged();
}
/**
* Obtain auto-allocated memory for use with struct represenations.
* @param size desired size
* @return newly-allocated memory
*/
protected Memory autoAllocate(int size) {
return new AutoAllocated(size);
}
/** Set the memory used by this structure. This method is used to
* indicate the given structure is nested within another or otherwise
* overlaid on some other memory block and thus does not own its own
* memory.
* @param m Memory to with which to back this {@link Structure}.
*/
protected void useMemory(Pointer m) {
useMemory(m, 0);
}
/** Set the memory used by this structure. This method is used to
* indicate the given structure is based on natively-allocated data,
* nested within another, or otherwise overlaid on existing memory and
* thus does not own its own memory allocation.
* @param m Base memory to use to back this structure.
* @param offset offset into provided memory where structure mapping
* should start.
*/
protected void useMemory(Pointer m, int offset) {
useMemory(m, offset, false);
}
/** Set the memory used by this structure. This method is used to
* indicate the given structure is based on natively-allocated data,
* nested within another, or otherwise overlaid on existing memory and
* thus does not own its own memory allocation.
* @param m Native pointer
* @param offset offset from pointer to use
* @param force ByValue structures normally ignore requests to use a
* different memory offset; this input is set <code>true</code> when
* setting a ByValue struct that is nested within another struct.
*/
void useMemory(Pointer m, int offset, boolean force) {
try {
// Clear any local cache
nativeStrings.clear();
if (this instanceof ByValue && !force) {
// ByValue parameters always use dedicated memory, so only
// copy the contents of the original
byte[] buf = new byte[size()];
m.read(0, buf, 0, buf.length);
this.memory.write(0, buf, 0, buf.length);
}
else {
if (size == CALCULATE_SIZE) {
size = calculateSize(false);
}
if (size != CALCULATE_SIZE) {
this.memory = m.share(offset, size);
} else {
// Ensure our memory pointer is initialized, even if we can't
// yet figure out a proper size/layout
this.memory = m.share(offset);
}
}
this.array = null;
this.readCalled = false;
}
catch(IndexOutOfBoundsException e) {
throw new IllegalArgumentException("Structure exceeds provided memory bounds", e);
}
}
/** Ensure this memory has its size and layout calculated and its
memory allocated. */
protected void ensureAllocated() {
ensureAllocated(false);
}
/** Ensure this memory has its size and layout calculated and its
memory allocated.
@param avoidFFIType used when computing FFI type information
to avoid recursion
*/
private void ensureAllocated(boolean avoidFFIType) {
if (memory == null) {
allocateMemory(avoidFFIType);
}
else if (size == CALCULATE_SIZE) {
this.size = calculateSize(true, avoidFFIType);
if (!(this.memory instanceof AutoAllocated)) {
// Ensure we've set bounds on the shared memory used
try {
this.memory = this.memory.share(0, this.size);
}
catch(IndexOutOfBoundsException e) {
throw new IllegalArgumentException("Structure exceeds provided memory bounds", e);
}
}
}
}
/** Attempt to allocate memory if sufficient information is available.
* Returns whether the operation was successful.
*/
protected void allocateMemory() {
allocateMemory(false);
}
private void allocateMemory(boolean avoidFFIType) {
allocateMemory(calculateSize(true, avoidFFIType));
}
/** Provided for derived classes to indicate a different
* size than the default. Returns whether the operation was successful.
* Will leave memory untouched if it is non-null and not allocated
* by this class.
* @param size how much memory to allocate
*/
protected void allocateMemory(int size) {
if (size == CALCULATE_SIZE) {
// Analyze the struct, but don't worry if we can't yet do it
size = calculateSize(false);
}
else if (size <= 0) {
throw new IllegalArgumentException("Structure size must be greater than zero: " + size);
}
// May need to defer size calculation if derived class not fully
// initialized
if (size != CALCULATE_SIZE) {
if (this.memory == null
|| this.memory instanceof AutoAllocated) {
this.memory = autoAllocate(size);
}
this.size = size;
}
}
/** Returns the size in memory occupied by this Structure.
* @return Native size of this structure, in bytes.
*/
public int size() {
ensureAllocated();
return this.size;
}
/** Clears the native memory associated with this Structure. */
public void clear() {
ensureAllocated();
// ensure the memory is released and the values are written again
nativeStrings.clear();
memory.clear(size());
}
/** Return a {@link Pointer} object to this structure. Note that if you
* use the structure's pointer as a function argument, you are responsible
* for calling {@link #write()} prior to the call and {@link #read()}
* after the call. These calls are normally handled automatically by the
* {@link Function} object when it encounters a {@link Structure} argument
* or return value.
* The returned pointer may not have meaning for {@link Structure.ByValue}
* structure representations.
* @return Native pointer representation of this structure.
*/
public Pointer getPointer() {
ensureAllocated();
return memory;
}
//////////////////////////////////////////////////////////////////////////
// Data synchronization methods
//////////////////////////////////////////////////////////////////////////
// Keep track of ByReference reads to avoid redundant reads of the same
// address
private static final ThreadLocal<Map<Pointer, Structure>> reads = new ThreadLocal<Map<Pointer, Structure>>() {
@Override
protected synchronized Map<Pointer, Structure> initialValue() {
return new HashMap<>();
}
};
// Keep track of what is currently being read/written to avoid redundant
// reads (avoids problems with circular references).
private static final ThreadLocal<Set<Structure>> busy = new ThreadLocal<Set<Structure>>() {
@Override
protected synchronized Set<Structure> initialValue() {
return new StructureSet();
}
};
/** Avoid using a hash-based implementation since the hash code
for a Structure is not immutable.
*/
static class StructureSet extends AbstractCollection<Structure> implements Set<Structure> {
Structure[] elements;
private int count;
private void ensureCapacity(int size) {
if (elements == null) {
elements = new Structure[size*3/2];
}
else if (elements.length < size) {
Structure[] e = new Structure[size*3/2];
System.arraycopy(elements, 0, e, 0, elements.length);
elements = e;
}
}
public Structure[] getElements() {
return elements;
}
@Override
public int size() { return count; }
@Override
public boolean contains(Object o) {
return indexOf((Structure) o) != -1;
}
@Override
public boolean add(Structure o) {
if (!contains(o)) {
ensureCapacity(count+1);
elements[count++] = o;
return true;
}
return false;
}
private int indexOf(Structure s1) {
for (int i=0;i < count;i++) {
Structure s2 = elements[i];
if (s1 == s2
|| (s1.getClass() == s2.getClass()
&& s1.size() == s2.size()
&& s1.getPointer().equals(s2.getPointer()))) {
return i;
}
}
return -1;
}
@Override
public boolean remove(Object o) {
int idx = indexOf((Structure) o);
if (idx != -1) {
if (--count >= 0) {
elements[idx] = elements[count];
elements[count] = null;
}
return true;
}
return false;
}
/** Simple implementation so that toString() doesn't break.
Provides an iterator over a snapshot of this Set.
*/
@Override
public Iterator<Structure> iterator() {
Structure[] e = new Structure[count];
if (count > 0) {
System.arraycopy(elements, 0, e, 0, count);
}
return Arrays.asList(e).iterator();
}
}
static Set<Structure> busy() {
return busy.get();
}
static Map<Pointer, Structure> reading() {
return reads.get();
}
/** Performs auto-read only if uninitialized. */
void conditionalAutoRead() {
if (!readCalled) {
autoRead();
}
}
/**
* Reads the fields of the struct from native memory
*/
public void read() {
// Avoid reading from a null pointer
if (memory == PLACEHOLDER_MEMORY) {
return;
}
readCalled = true;
// convenience: allocate memory and/or calculate size if it hasn't
// been already; this allows structures to do field-based
// initialization of arrays and not have to explicitly call
// allocateMemory in a ctor
ensureAllocated();
// Avoid redundant reads
if (!busy().add(this)) {
return;
}
if (this instanceof Structure.ByReference) {
reading().put(getPointer(), this);
}
try {
for (StructField structField : fields().values()) {
readField(structField);
}
}
finally {
busy().remove(this);
if (this instanceof Structure.ByReference && reading().get(getPointer()) == this) {
reading().remove(getPointer());
}
}
}
/** Returns the calculated offset of the given field.
* @param name field to examine
* @return return offset of the given field
*/
protected int fieldOffset(String name) {
ensureAllocated();
StructField f = fields().get(name);
if (f == null) {
throw new IllegalArgumentException("No such field: " + name);
}
return f.offset;
}
/** Force a read of the given field from native memory. The Java field
* will be updated from the current contents of native memory.
* @param name field to be read
* @return the new field value, after updating
* @throws IllegalArgumentException if no field exists with the given name
*/
public Object readField(String name) {
ensureAllocated();
StructField f = fields().get(name);
if (f == null)
throw new IllegalArgumentException("No such field: " + name);
return readField(f);
}
/** Obtain the value currently in the Java field. Does not read from
* native memory.
* @param field field to look up
* @return current field value (Java-side only)
*/
Object getFieldValue(Field field) {
try {
return field.get(this);
}
catch (Exception e) {
throw new Error("Exception reading field '" + field.getName() + "' in " + getClass(), e);
}
}
/**
* @param field field to set
* @param value value to set
*/
void setFieldValue(Field field, Object value) {
setFieldValue(field, value, false);
}
private void setFieldValue(Field field, Object value, boolean overrideFinal) {
try {
field.set(this, value);
}
catch(IllegalAccessException e) {
int modifiers = field.getModifiers();
if (Modifier.isFinal(modifiers)) {
if (overrideFinal) {
// WARNING: setAccessible(true) on J2ME does *not* allow
// overwriting of a final field.
throw new UnsupportedOperationException("This VM does not support Structures with final fields (field '" + field.getName() + "' within " + getClass() + ")", e);
}
throw new UnsupportedOperationException("Attempt to write to read-only field '" + field.getName() + "' within " + getClass(), e);
}
throw new Error("Unexpectedly unable to write to field '" + field.getName() + "' within " + getClass(), e);
}
}
/** Only keep the original structure if its native address is unchanged.
* Otherwise replace it with a new object.
* @param type Structure subclass
* @param s Original Structure object
* @param address the native <code>struct *</code>
* @return Updated <code>Structure.ByReference</code> object
*/
static <T extends Structure> T updateStructureByReference(Class<T> type, T s, Pointer address) {
if (address == null) {
s = null;
}
else {
if (s == null || !address.equals(s.getPointer())) {
Structure s1 = reading().get(address);
if (s1 != null && type.equals(s1.getClass())) {
s = (T) s1;
s.autoRead();
}
else {
s = newInstance(type, address);
s.conditionalAutoRead();
}
}
else {
s.autoRead();
}
}
return s;
}
/** Read the given field and return its value. The Java field will be
* updated from the contents of native memory.
* @param structField field to be read
* @return value of the requested field
*/
// TODO: make overridable method with calculated native type, offset, etc
protected Object readField(StructField structField) {
// Get the offset of the field
int offset = structField.offset;
// Determine the type of the field
Class<?> fieldType = structField.type;
FromNativeConverter readConverter = structField.readConverter;
if (readConverter != null) {
fieldType = readConverter.nativeType();
}
// Get the current value only for types which might need to be preserved
Object currentValue = (Structure.class.isAssignableFrom(fieldType)
|| Callback.class.isAssignableFrom(fieldType)
|| (Platform.HAS_BUFFERS && Buffer.class.isAssignableFrom(fieldType))
|| Pointer.class.isAssignableFrom(fieldType)
|| NativeMapped.class.isAssignableFrom(fieldType)
|| fieldType.isArray())
? getFieldValue(structField.field) : null;
Object result;
if (fieldType == String.class) {
Pointer p = memory.getPointer(offset);
result = p == null ? null : p.getString(0, encoding);
}
else {
result = memory.getValue(offset, fieldType, currentValue);
}
if (readConverter != null) {
result = readConverter.fromNative(result, structField.context);
if (currentValue != null && currentValue.equals(result)) {
result = currentValue;
}
}
if (fieldType.equals(String.class)
|| fieldType.equals(WString.class)) {
if (result != null) {
NativeStringTracking current = new NativeStringTracking(result);
NativeStringTracking previous = nativeStrings.put(structField.name, current);
if (previous != null) {
// regardless of value changed or not, keep the old native string alive
current.peer = previous.peer;
}
} else {
// the value is cleared, we don't need to keep the native string alive
nativeStrings.remove(structField.name);
}
}
// Update the value on the Java field
setFieldValue(structField.field, result, true);
return result;
}
/**
* Writes the fields of the struct to native memory
*/
public void write() {
// Avoid writing to a null pointer
if (memory == PLACEHOLDER_MEMORY) {
return;
}
// convenience: allocate memory if it hasn't been already; this
// allows structures to do field-based initialization of arrays and not
// have to explicitly call allocateMemory in a ctor
ensureAllocated();
// Update native FFI type information, if needed
if (this instanceof ByValue) {
getTypeInfo();
}
// Avoid redundant writes
if (!busy().add(this)) {
return;
}
try {
// Write all fields, except those marked 'volatile'
for (StructField sf : fields().values()) {
if (!sf.isVolatile) {
writeField(sf);
}
}
}
finally {
busy().remove(this);
}
}
/** Write the given field to native memory. The current value in the Java
* field will be translated into native memory.
* @param name which field to synch
* @throws IllegalArgumentException if no field exists with the given name
*/
public void writeField(String name) {
ensureAllocated();
StructField f = fields().get(name);
if (f == null)
throw new IllegalArgumentException("No such field: " + name);
writeField(f);
}
/** Write the given field value to the field and native memory. The
* given value will be written both to the Java field and the
* corresponding native memory.
* @param name field to write
* @param value value to write
* @throws IllegalArgumentException if no field exists with the given name
*/
public void writeField(String name, Object value) {
ensureAllocated();
StructField structField = fields().get(name);
if (structField == null)
throw new IllegalArgumentException("No such field: " + name);
setFieldValue(structField.field, value);
writeField(structField, value);
}
/**
* @param structField internal field representation to synch to native memory
*/
protected void writeField(StructField structField) {
if (structField.isReadOnly)
return;
// Get the value from the field
Object value = getFieldValue(structField.field);
writeField(structField, value);
}
/**
* @param structField internal field representation to synch to native memory
* @param value value to write
*/
private void writeField(StructField structField, Object value) {
// Get the offset of the field
int offset = structField.offset;
// Determine the type of the field
Class<?> fieldType = structField.type;
ToNativeConverter converter = structField.writeConverter;
if (converter != null) {
value = converter.toNative(value, new StructureWriteContext(this, structField.field));
fieldType = converter.nativeType();
}
// Java strings get converted to C strings, where a Pointer is used
if (String.class == fieldType
|| WString.class == fieldType) {
if (value != null) {
NativeStringTracking current = new NativeStringTracking(value);
NativeStringTracking previous = nativeStrings.put(structField.name, current);
// If we've already allocated a native string here, and the
// string value is unchanged, leave it alone
if (previous != null && value.equals(previous.value)) {
// value is unchanged, keep the old native string alive
current.peer = previous.peer;
return;
}
// Allocate a new string in memory
boolean wide = fieldType == WString.class;
NativeString nativeString = wide
? new NativeString(value.toString(), true)
: new NativeString(value.toString(), encoding);
// value is changed, keep the new native string alive
current.peer = nativeString;
value = nativeString.getPointer();
}
else {
nativeStrings.remove(structField.name);
}
}
try {
memory.setValue(offset, value, fieldType);
}
catch(IllegalArgumentException e) {
String msg = "Structure field \"" + structField.name
+ "\" was declared as " + structField.type
+ (structField.type == fieldType
? "" : " (native type " + fieldType + ")")
+ ", which is not supported within a Structure";
throw new IllegalArgumentException(msg, e);
}
}
/** Used to declare fields order as metadata instead of method.
* example:
* <pre><code>
* // New
* {@literal @}FieldOrder({ "n", "s" })
* class Parent extends Structure {
* public int n;
* public String s;
* }
* {@literal @}FieldOrder({ "d", "c" })
* class Son extends Parent {
* public double d;
* public char c;
* }
* // Old
* class Parent extends Structure {
* public int n;
* public String s;
* protected List<String> getFieldOrder() {
* return Arrays.asList("n", "s");
* }
* }
* class Son extends Parent {
* public double d;
* public char c;
* protected List<String> getFieldOrder() {
* List<String> fields = new LinkedList<String>(super.getFieldOrder());
* fields.addAll(Arrays.asList("d", "c"));
* return fields;
* }
* }
* </code></pre>
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface FieldOrder {
String[] value();
}
/** Returns this Structure's field names in their proper order.<br>
*
* When defining a new {@link Structure} you shouldn't override this
* method, but use {@link FieldOrder} annotation to define your field
* order(this also works with inheritance)<br>
*
* If you want to do something non-standard you can override the method
* and define it as followed
* <pre><code>
* protected List<String> getFieldOrder() {
* return Arrays.asList(...);
* }
* </code></pre>
* <strong>IMPORTANT</strong>
* When deriving from an existing Structure subclass, ensure that
* you augment the list provided by the superclass, e.g.
* <pre><code>
* protected List<String> getFieldOrder() {
* List<String> fields = new LinkedList<String>(super.getFieldOrder());
* fields.addAll(Arrays.asList(...));
* return fields;
* }
* </code></pre>
*
* Field order must be explicitly indicated, since the
* field order as returned by {@link Class#getFields()} is not
* guaranteed to be predictable.
* @return ordered list of field names
*/
// TODO(idosu 28 Apr 2018): Maybe deprecate this method to let users know they should use @FieldOrder
protected List<String> getFieldOrder() {
List<String> fields = new LinkedList<>();
for (Class<?> clazz = getClass(); clazz != Structure.class; clazz = clazz.getSuperclass()) {
FieldOrder order = clazz.getAnnotation(FieldOrder.class);
if (order != null) {
fields.addAll(0, Arrays.asList(order.value()));
}
}
// fields.isEmpty() can be true because it is check somewhere else
return Collections.unmodifiableList(fields);
}
/** Sort the structure fields according to the given array of names.
* @param fields list of fields to be sorted
* @param names list of names representing the desired sort order
*/
protected void sortFields(List<Field> fields, List<String> names) {
for (int i=0;i < names.size();i++) {
String name = names.get(i);
for (int f=0;f < fields.size();f++) {
Field field = fields.get(f);
if (name.equals(field.getName())) {
Collections.swap(fields, i, f);
break;
}
}
}
}
/** Look up all fields in this class and superclasses.
* @return ordered list of public {@link java.lang.reflect.Field} available on
* this {@link Structure} class.
*/
protected List<Field> getFieldList() {
List<Field> flist = new ArrayList<>();
for (Class<?> cls = getClass();
!cls.equals(Structure.class);
cls = cls.getSuperclass()) {
List<Field> classFields = new ArrayList<>();
Field[] fields = cls.getDeclaredFields();
for (int i=0;i < fields.length;i++) {
int modifiers = fields[i].getModifiers();
if (Modifier.isStatic(modifiers) || !Modifier.isPublic(modifiers)) {
continue;
}
classFields.add(fields[i]);
}
flist.addAll(0, classFields);
}
return flist;
}
/** Cache field order per-class.
* @return (cached) ordered list of fields
*/
private List<String> fieldOrder() {
Class<?> clazz = getClass();
synchronized(fieldOrder) {
List<String> list = fieldOrder.get(clazz);
if (list == null) {
list = getFieldOrder();
fieldOrder.put(clazz, list);
}
return list;
}
}
public static List<String> createFieldsOrder(List<String> baseFields, String ... extraFields) {
return createFieldsOrder(baseFields, Arrays.asList(extraFields));
}
public static List<String> createFieldsOrder(List<String> baseFields, List<String> extraFields) {
List<String> fields = new ArrayList<>(baseFields.size() + extraFields.size());
fields.addAll(baseFields);
fields.addAll(extraFields);
return Collections.unmodifiableList(fields);
}
/**
* @param field The (single) field name
* @return @return An <U>un-modifiable</U> list containing the field name
*/
public static List<String> createFieldsOrder(String field) {
return Collections.unmodifiableList(Collections.singletonList(field));
}
/**
* @param fields The structure field names in correct order
* @return An <U>un-modifiable</U> list of the fields
*/
public static List<String> createFieldsOrder(String ... fields) {
return Collections.unmodifiableList(Arrays.asList(fields));
}
private static <T extends Comparable<T>> List<T> sort(Collection<? extends T> c) {
List<T> list = new ArrayList<>(c);
Collections.sort(list);
return list;
}
/** Returns all field names (sorted) provided so far by
{@link #getFieldOrder}
@param force set if results are required immediately
@return null if not yet able to provide fields, and force is false.
@throws Error if force is true and field order data not yet specified
and can't be generated automatically.
**/
protected List<Field> getFields(boolean force) {
List<Field> flist = getFieldList();
Set<String> names = new HashSet<>();
for (Field f : flist) {
names.add(f.getName());
}
List<String> fieldOrder = fieldOrder();
if (fieldOrder.size() != flist.size() && flist.size() > 1) {
if (force) {
throw new Error("Structure.getFieldOrder() on " + getClass()
+ (fieldOrder.size() < flist.size()
? " does not provide enough"
: " provides too many")
+ " names [" + fieldOrder.size()
+ "] ("
+ sort(fieldOrder)
+ ") to match declared fields [" + flist.size()
+ "] ("
+ sort(names)
+ ")");
}
return null;
}
Set<String> orderedNames = new HashSet<>(fieldOrder);
if (!orderedNames.equals(names)) {
throw new Error("Structure.getFieldOrder() on " + getClass()
+ " returns names ("
+ sort(fieldOrder)
+ ") which do not match declared field names ("
+ sort(names) + ")");
}
sortFields(flist, fieldOrder);
return flist;
}
/** Calculate the amount of native memory required for this structure.
* May return {@link #CALCULATE_SIZE} if the size can not yet be
* determined (usually due to fields in the derived class not yet
* being initialized).
* If the <code>force</code> parameter is <code>true</code> will throw
* an {@link IllegalStateException} if the size can not be determined.
* @param force whether to force size calculation
* @return calculated size, or {@link #CALCULATE_SIZE} if the size can not
* yet be determined.
* @throws IllegalStateException an array field is not initialized or the
* size can not be determined while <code>force</code> is <code>true</code>.
* @throws IllegalArgumentException when an unsupported field type is
* encountered
*/
protected int calculateSize(boolean force) {
return calculateSize(force, false);
}
/** Efficiently calculate the size of the given Structure subclass.
* @param type Structure subclass to check
* @return native size of the given Structure subclass
*/
static int size(Class<? extends Structure> type) {
return size(type, null);
}
/** Efficiently calculate the size of the given Structure subclass.
* @param type Structure subclass to check
* @param value optional instance of the given class
* @return native size of the Structure subclass
*/
static <T extends Structure> int size(Class<T> type, T value) {
LayoutInfo info;
synchronized(layoutInfo) {
info = layoutInfo.get(type);
}
int sz = (info != null && !info.variable) ? info.size : CALCULATE_SIZE;
if (sz == CALCULATE_SIZE) {
if (value == null) {
value = newInstance(type, PLACEHOLDER_MEMORY);
}
sz = value.size();
}
return sz;
}
/**
* @param force whether to force size calculation.
* @param avoidFFIType set false in certain situations to avoid recursive
* type lookup.
* @return calculated size, or {@link #CALCULATE_SIZE} if there is not yet
* enough information to perform the size calculation.
*/
int calculateSize(boolean force, boolean avoidFFIType) {
int size = CALCULATE_SIZE;
Class<?> clazz = getClass();
LayoutInfo info;
synchronized(layoutInfo) {
info = layoutInfo.get(clazz);
}
if (info == null
|| this.alignType != info.alignType
|| this.typeMapper != info.typeMapper) {
info = deriveLayout(force, avoidFFIType);
}
if (info != null) {
this.structAlignment = info.alignment;
this.structFields = info.fields;
if (!info.variable) {
synchronized(layoutInfo) {
// If we've already cached it, only override layout if
// we're using non-default values for alignment and/or
// type mapper; this way we don't override the cache
// prematurely when processing subclasses that call
// setAlignType() or setTypeMapper() in the constructor
if (!layoutInfo.containsKey(clazz)
|| this.alignType != ALIGN_DEFAULT
|| this.typeMapper != null) {
layoutInfo.put(clazz, info);
}
}
}
size = info.size;
}
return size;
}
/** Keep track of structure layout information. Alignment type, type
mapper, and explicit field order will affect this information.
*/
private static class LayoutInfo {
private int size = CALCULATE_SIZE;
private int alignment = 1;
private final Map<String, StructField> fields = Collections.synchronizedMap(new LinkedHashMap<String, StructField>());
private int alignType = ALIGN_DEFAULT;
private TypeMapper typeMapper;
private boolean variable;
}
private void validateField(String name, Class<?> type) {
if (typeMapper != null) {
ToNativeConverter toNative = typeMapper.getToNativeConverter(type);
if (toNative != null) {
validateField(name, toNative.nativeType());
return;
}
}
if (type.isArray()) {
validateField(name, type.getComponentType());
}
else {
try {
getNativeSize(type);
}
catch(IllegalArgumentException e) {
String msg = "Invalid Structure field in " + getClass() + ", field name '" + name + "' (" + type + "): " + e.getMessage();
throw new IllegalArgumentException(msg, e);
}
}
}
/** ensure all fields are of valid type. */
private void validateFields() {
List<Field> fields = getFieldList();
for (Field f : fields) {
validateField(f.getName(), f.getType());
}
}
/** Calculates the size, alignment, and field layout of this structure.
Also initializes any null-valued Structure or NativeMapped
members.
*/
private LayoutInfo deriveLayout(boolean force, boolean avoidFFIType) {
int calculatedSize = 0;
List<Field> fields = getFields(force);
if (fields == null) {
return null;
}
LayoutInfo info = new LayoutInfo();
info.alignType = this.alignType;
info.typeMapper = this.typeMapper;
boolean firstField = true;
for (Iterator<Field> i=fields.iterator();i.hasNext();firstField=false) {
Field field = i.next();
int modifiers = field.getModifiers();
Class<?> type = field.getType();
if (type.isArray()) {
info.variable = true;
}
StructField structField = new StructField();
structField.isVolatile = Modifier.isVolatile(modifiers);
structField.isReadOnly = Modifier.isFinal(modifiers);
if (structField.isReadOnly) {
if (!Platform.RO_FIELDS) {
throw new IllegalArgumentException("This VM does not support read-only fields (field '"
+ field.getName() + "' within " + getClass() + ")");
}
// In J2SE VMs, this allows overriding the value of final
// fields
field.setAccessible(true);
}
structField.field = field;
structField.name = field.getName();
structField.type = type;
// Check for illegal field types
if (Callback.class.isAssignableFrom(type) && !type.isInterface()) {
throw new IllegalArgumentException("Structure Callback field '"
+ field.getName()
+ "' must be an interface");
}
if (type.isArray()
&& Structure.class.equals(type.getComponentType())) {
String msg = "Nested Structure arrays must use a "
+ "derived Structure type so that the size of "
+ "the elements can be determined";
throw new IllegalArgumentException(msg);
}
int fieldAlignment = 1;
if (!Modifier.isPublic(field.getModifiers())) {
continue;
}
Object value = getFieldValue(structField.field);
if (value == null && type.isArray()) {
if (force) {
throw new IllegalStateException("Array fields must be initialized");
}
// can't calculate size yet, defer until later
return null;
}
Class<?> nativeType = type;
if (NativeMapped.class.isAssignableFrom(type)) {
NativeMappedConverter tc = NativeMappedConverter.getInstance(type);
nativeType = tc.nativeType();
structField.writeConverter = tc;
structField.readConverter = tc;
structField.context = new StructureReadContext(this, field);
}
else if (typeMapper != null) {
ToNativeConverter writeConverter = typeMapper.getToNativeConverter(type);
FromNativeConverter readConverter = typeMapper.getFromNativeConverter(type);
if (writeConverter != null && readConverter != null) {
value = writeConverter.toNative(value,
new StructureWriteContext(this, structField.field));
nativeType = value != null ? value.getClass() : Pointer.class;
structField.writeConverter = writeConverter;
structField.readConverter = readConverter;
structField.context = new StructureReadContext(this, field);
}
else if (writeConverter != null || readConverter != null) {
String msg = "Structures require bidirectional type conversion for " + type;
throw new IllegalArgumentException(msg);
}
}
if (value == null) {
value = initializeField(structField.field, type);
}
try {
structField.size = getNativeSize(nativeType, value);
fieldAlignment = getNativeAlignment(nativeType, value, firstField);
}
catch(IllegalArgumentException e) {
// Might simply not yet have a type mapper set yet
if (!force && typeMapper == null) {
return null;
}
String msg = "Invalid Structure field in " + getClass() + ", field name '" + structField.name + "' (" + structField.type + "): " + e.getMessage();
throw new IllegalArgumentException(msg, e);
}
// Align fields as appropriate
if (fieldAlignment == 0) {
throw new Error("Field alignment is zero for field '" + structField.name + "' within " + getClass());
}
info.alignment = Math.max(info.alignment, fieldAlignment);
if ((calculatedSize % fieldAlignment) != 0) {
calculatedSize += fieldAlignment - (calculatedSize % fieldAlignment);
}
if (this instanceof Union) {
structField.offset = 0;
calculatedSize = Math.max(calculatedSize, structField.size);
}
else {
structField.offset = calculatedSize;
calculatedSize += structField.size;
}
// Save the field in our list
info.fields.put(structField.name, structField);
}
if (calculatedSize > 0) {
int size = addPadding(calculatedSize, info.alignment);
// Update native FFI type information, if needed
if (this instanceof ByValue && !avoidFFIType) {
getTypeInfo();
}
info.size = size;
return info;
}
throw new IllegalArgumentException("Structure " + getClass()
+ " has unknown or zero size (ensure "
+ "all fields are public)");
}
/**
* Initialize any null-valued fields that should have a non-null default
* value.
*/
@SuppressWarnings("UseSpecificCatch")
private void initializeFields() {
// Get the full field list, don't care about sorting
List<Field> flist = getFieldList();
for (Field f : flist) {
try {
Object o = f.get(this);
if (o == null) {
initializeField(f, f.getType());
}
}
catch (Exception e) {
throw new Error("Exception reading field '" + f.getName() + "' in " + getClass(), e);
}
}
}
private Object initializeField(Field field, Class<?> type) {
Object value = null;
if (Structure.class.isAssignableFrom(type)
&& !(ByReference.class.isAssignableFrom(type))) {
try {
value = newInstance((Class<? extends Structure>) type, PLACEHOLDER_MEMORY);
setFieldValue(field, value);
}
catch(IllegalArgumentException e) {
String msg = "Can't determine size of nested structure";
throw new IllegalArgumentException(msg, e);
}
}
else if (NativeMapped.class.isAssignableFrom(type)) {
NativeMappedConverter tc = NativeMappedConverter.getInstance(type);
value = tc.defaultValue();
setFieldValue(field, value);
}
return value;
}
private int addPadding(int calculatedSize) {
return addPadding(calculatedSize, structAlignment);
}
private int addPadding(int calculatedSize, int alignment) {
// Structure size must be an integral multiple of its alignment,
// add padding if necessary.
if (actualAlignType != ALIGN_NONE) {
if ((calculatedSize % alignment) != 0) {
calculatedSize += alignment - (calculatedSize % alignment);
}
}
return calculatedSize;
}
/**
* @return current alignment setting for this structure
*/
protected int getStructAlignment() {
if (size == CALCULATE_SIZE) {
// calculate size, but don't allocate memory
calculateSize(true);
}
return structAlignment;
}
/** Overridable in subclasses.
* Calculate the appropriate alignment for a field of a given type within this struct.
* @param type field type
* @param value field value, if available
* @param isFirstElement is this field the first element in the struct?
* @return the native byte alignment
*/
// TODO: write getNaturalAlignment(stack/alloc) + getEmbeddedAlignment(structs)
// TODO: move this into a native call which detects default alignment
// automatically
protected int getNativeAlignment(Class<?> type, Object value, boolean isFirstElement) {
int alignment = 1;
if (NativeMapped.class.isAssignableFrom(type)) {
NativeMappedConverter tc = NativeMappedConverter.getInstance(type);
type = tc.nativeType();
value = tc.toNative(value, new ToNativeContext());
}
int size = Native.getNativeSize(type, value);
if (type.isPrimitive() || Long.class == type || Integer.class == type
|| Short.class == type || Character.class == type
|| Byte.class == type || Boolean.class == type
|| Float.class == type || Double.class == type) {
alignment = size;
}
else if ((Pointer.class.isAssignableFrom(type) && !Function.class.isAssignableFrom(type))
|| (Platform.HAS_BUFFERS && Buffer.class.isAssignableFrom(type))
|| Callback.class.isAssignableFrom(type)
|| WString.class == type
|| String.class == type) {
alignment = Native.POINTER_SIZE;
}
else if (Structure.class.isAssignableFrom(type)) {
if (ByReference.class.isAssignableFrom(type)) {
alignment = Native.POINTER_SIZE;
}
else {
if (value == null)
value = newInstance((Class<? extends Structure>) type, PLACEHOLDER_MEMORY);
alignment = ((Structure)value).getStructAlignment();
}
}
else if (type.isArray()) {
alignment = getNativeAlignment(type.getComponentType(), null, isFirstElement);
}
else {
throw new IllegalArgumentException("Type " + type + " has unknown "
+ "native alignment");
}
if (actualAlignType == ALIGN_NONE) {
alignment = 1;
}
else if (actualAlignType == ALIGN_MSVC) {
alignment = Math.min(8, alignment);
}
else if (actualAlignType == ALIGN_GNUC) {
// NOTE this is published ABI for 32-bit gcc/linux/x86, osx/x86,
// and osx/ppc. osx/ppc special-cases the first element
if (!isFirstElement || !(Platform.isMac() && Platform.isPPC())) {
alignment = Math.min(Native.MAX_ALIGNMENT, alignment);
}
if (!isFirstElement && Platform.isAIX() && (type == double.class || type == Double.class)) {
alignment = 4;
}
}
return alignment;
}
/**
* If <code>jna.dump_memory</code> is true, will include a native memory dump
* of the Structure's backing memory.
* @return String representation of this object.
*/
@Override
public String toString() {
return toString(Boolean.getBoolean("jna.dump_memory"));
}
/**
* @param debug If true, will include a native memory dump of the
* Structure's backing memory.
* @return String representation of this object.
*/
public String toString(boolean debug) {
return toString(0, true, debug);
}
private String format(Class<?> type) {
String s = type.getName();
int dot = s.lastIndexOf(".");
return s.substring(dot + 1);
}
private String toString(int indent, boolean showContents, boolean dumpMemory) {
ensureAllocated();
String LS = System.lineSeparator();
String name = format(getClass()) + "(" + getPointer() + ")";
if (!(getPointer() instanceof Memory)) {
name += " (" + size() + " bytes)";
}
String prefix = "";
for (int idx=0;idx < indent;idx++) {
prefix += " ";
}
String contents = LS;
if (!showContents) {
contents = "...}";
} else {
for (Iterator<StructField> i = fields().values().iterator(); i.hasNext();) {
StructField sf = i.next();
Object value = getFieldValue(sf.field);
String type = format(sf.type);
String index = "";
contents += prefix;
if (sf.type.isArray() && value != null) {
type = format(sf.type.getComponentType());
index = "[" + Array.getLength(value) + "]";
}
contents += String.format(" %s %s%s@0x%X", type, sf.name, index, sf.offset);
if (value instanceof Structure) {
value = ((Structure)value).toString(indent + 1, !(value instanceof Structure.ByReference), dumpMemory);
}
contents += "=";
if (value instanceof Long) {
contents += String.format("0x%08X", (Long) value);
}
else if (value instanceof Integer) {
contents += String.format("0x%04X", (Integer) value);
}
else if (value instanceof Short) {
contents += String.format("0x%02X", (Short) value);
}
else if (value instanceof Byte) {
contents += String.format("0x%01X", (Byte) value);
}
else {
contents += String.valueOf(value).trim();
}
contents += LS;
if (!i.hasNext())
contents += prefix + "}";
}
}
if (indent == 0 && dumpMemory) {
final int BYTES_PER_ROW = 4;
contents += LS + "memory dump" + LS;
byte[] buf = getPointer().getByteArray(0, size());
for (int i=0;i < buf.length;i++) {
if ((i % BYTES_PER_ROW) == 0) contents += "[";
if (buf[i] >=0 && buf[i] < 16)
contents += "0";
contents += Integer.toHexString(buf[i] & 0xFF);
if ((i % BYTES_PER_ROW) == BYTES_PER_ROW-1 && i < buf.length-1)
contents += "]" + LS;
}
contents += "]";
}
return name + " {" + contents;
}
/** Returns a view of this structure's memory as an array of structures.
* Note that this <code>Structure</code> must have a public, no-arg
* constructor. If the structure is currently using auto-allocated
* {@link Memory} backing, the memory will be resized to fit the entire
* array.
* @param array Structure[] object to populate
* @return array of Structure mapped onto the available memory
*/
public Structure[] toArray(Structure[] array) {
ensureAllocated();
if (this.memory instanceof AutoAllocated) {
// reallocate if necessary
Memory m = (Memory)this.memory;
int requiredSize = array.length * size();
if (m.size() < requiredSize) {
useMemory(autoAllocate(requiredSize));
}
}
// TODO: optimize - check whether array already exists
array[0] = this;
int size = size();
for (int i=1;i < array.length;i++) {
array[i] = newInstance(getClass(), memory.share(i*size, size));
array[i].conditionalAutoRead();
}
if (!(this instanceof ByValue)) {
// keep track for later auto-read/writes
this.array = array;
}
return array;
}
/** Returns a view of this structure's memory as an array of structures.
* Note that this <code>Structure</code> must have a public, no-arg
* constructor. If the structure is currently using auto-allocated
* {@link Memory} backing, the memory will be resized to fit the entire
* array.
* @param size desired number of elements
* @return array of Structure (individual elements will be of the
* appropriate type, as will the Structure[]).
*/
public Structure[] toArray(int size) {
return toArray((Structure[])Array.newInstance(getClass(), size));
}
private Class<?> baseClass() {
if ((this instanceof Structure.ByReference
|| this instanceof Structure.ByValue)
&& Structure.class.isAssignableFrom(getClass().getSuperclass())) {
return getClass().getSuperclass();
}
return getClass();
}
/** Return whether the given Structure's native backing data is identical to
* this one.
* @param s Structure to compare
* @return equality result
*/
public boolean dataEquals(Structure s) {
return dataEquals(s, false);
}
/** Return whether the given Structure's backing data is identical to
* this one, optionally clearing and re-writing native memory before checking.
* @param s Structure to compare
* @param clear whether to clear native memory
* @return equality result
*/
public boolean dataEquals(Structure s, boolean clear) {
if (clear) {
s.getPointer().clear(s.size());
s.write();
getPointer().clear(size());
write();
}
byte[] data = s.getPointer().getByteArray(0, s.size());
byte[] ref = getPointer().getByteArray(0, size());
if (data.length == ref.length) {
for (int i=0;i < data.length;i++) {
if (data[i] != ref[i]) {
return false;
}
}
return true;
}
return false;
}
/**
* @return whether the given structure's type and pointer match.
*/
@Override
public boolean equals(Object o) {
return o instanceof Structure
&& o.getClass() == getClass()
&& ((Structure)o).getPointer().equals(getPointer());
}
/**
* @return hash code for this structure's pointer.
*/
@Override
public int hashCode() {
Pointer p = getPointer();
if (p != null) {
return getPointer().hashCode();
}
return getClass().hashCode();
}
/** Cache native type information for use in native code.
* @param p Native pointer to the type information
*/
protected void cacheTypeInfo(Pointer p) {
this.typeInfo = p.peer;
}
/** Override to supply native type information for the given field.
* @param f internal field representation
* @return Native pointer to the corresponding type information
*/
FFIType getFieldTypeInfo(StructField f) {
Class<?> type = f.type;
Object value = getFieldValue(f.field);
if (typeMapper != null) {
ToNativeConverter nc = typeMapper.getToNativeConverter(type);
if (nc != null) {
type = nc.nativeType();
value = nc.toNative(value, new ToNativeContext());
}
}
return FFIType.get(value, type);
}
/**
* @return native type information for this structure.
*/
Pointer getTypeInfo() {
Pointer p = getTypeInfo(this).getPointer();
cacheTypeInfo(p);
return p;
}
/** Set whether the structure is automatically synchronized to native memory
before and after a native function call. Convenience method for
<pre><code>
boolean auto = ...;
setAutoRead(auto);
setAutoWrite(auto);
</code></pre>
For extremely large or complex structures where you only need to
access a small number of fields, you may see a significant performance
benefit by avoiding automatic structure reads and writes. If
auto-read and -write are disabled, it is up to you to ensure that the
Java fields of interest are synched before and after native function
calls via {@link #readField(String)} and {@link
#writeField(String,Object)}.
This is typically most effective when a native call populates a large
structure and you only need a few fields out of it. After the native
call you can call {@link #readField(String)} on only the fields of
interest.
@param auto whether to automatically synch with native memory.
*/
public void setAutoSynch(boolean auto) {
setAutoRead(auto);
setAutoWrite(auto);
}
/** Set whether the structure is read from native memory after
* a native function call.
* @param auto whether to automatically synch from native memory.
*/
public void setAutoRead(boolean auto) {
this.autoRead = auto;
}
/** Returns whether the structure is read from native memory after
* a native function call.
* @return whether automatic synch from native memory is enabled.
*/
public boolean getAutoRead() {
return this.autoRead;
}
/** Set whether the structure is written to native memory prior to a native
* function call.
* @param auto whether to automatically synch to native memory.
*/
public void setAutoWrite(boolean auto) {
this.autoWrite = auto;
}
/** Returns whether the structure is written to native memory prior to a native
* function call.
* @return whether automatic synch to native memory is enabled.
*/
public boolean getAutoWrite() {
return this.autoWrite;
}
/** Exposed for testing purposes only.
* @param obj object to query
* @return native pointer to type information
*/
static FFIType getTypeInfo(Object obj) {
return FFIType.get(obj);
}
/** Called from native code only; same as {@link
* #newInstance(Class,Pointer)}, except that it additionally calls
* {@link #conditionalAutoRead()}.
*/
private static <T extends Structure> T newInstance(Class<T> type, long init) {
try {
T s = newInstance(type, init == 0 ? PLACEHOLDER_MEMORY : new Pointer(init));
if (init != 0) {
s.conditionalAutoRead();
}
return s;
}
catch(Throwable e) {
LOG.log(Level.WARNING, "JNA: Error creating structure", e);
return null;
}
}
/** Create a new Structure instance of the given type, initialized with
* the given memory.
* @param type desired Structure type
* @param init initial memory
* @return the new instance
* @throws IllegalArgumentException if the instantiation fails
*/
public static <T extends Structure> T newInstance(Class<T> type, Pointer init) throws IllegalArgumentException {
try {
Constructor<T> ctor = getPointerConstructor(type);
if (ctor != null) {
return ctor.newInstance(init);
}
// Not defined, fall back to the default
}
catch(SecurityException e) {
// Might as well try the fallback
}
catch(InstantiationException e) {
String msg = "Can't instantiate " + type;
throw new IllegalArgumentException(msg, e);
}
catch(IllegalAccessException e) {
String msg = "Instantiation of " + type + " (Pointer) not allowed, is it public?";
throw new IllegalArgumentException(msg, e);
}
catch(InvocationTargetException e) {
String msg = "Exception thrown while instantiating an instance of " + type;
throw new IllegalArgumentException(msg, e);
}
T s = newInstance(type);
if (init != PLACEHOLDER_MEMORY) {
s.useMemory(init);
}
return s;
}
/**
* Create a new Structure instance of the given type
* @param type desired Structure type
* @return the new instance
* @throws IllegalArgumentException if the instantiation fails
*/
public static <T extends Structure> T newInstance(Class<T> type) throws IllegalArgumentException {
T s = Klass.newInstance(type);
if (s instanceof ByValue) {
s.allocateMemory();
}
return s;
}
/**
* Returns a constructor for the given type with a single Pointer argument, null if no such constructor is found.
* @param type the class
* @param <T> the type
* @return a constructor with a single Pointer argument, null if none is found
*/
private static <T> Constructor<T> getPointerConstructor(Class<T> type) {
for (Constructor constructor : type.getConstructors()) {
Class[] parameterTypes = constructor.getParameterTypes();
if (parameterTypes.length == 1 && parameterTypes[0].equals(Pointer.class)) {
return constructor;
}
}
return null;
}
protected static class StructField extends Object {
public String name;
public Class<?> type;
public Field field;
public int size = -1;
public int offset = -1;
public boolean isVolatile;
public boolean isReadOnly;
public FromNativeConverter readConverter;
public ToNativeConverter writeConverter;
public FromNativeContext context;
@Override
public String toString() {
return name + "@" + offset + "[" + size + "] (" + type + ")";
}
}
/**
* This class auto-generates an ffi_type structure appropriate for a given
* structure for use by libffi. The lifecycle of this structure is easier
* to manage on the Java side than in native code.
*/
@FieldOrder({ "size", "alignment", "type", "elements" })
static class FFIType extends Structure {
public static class size_t extends IntegerType {
private static final long serialVersionUID = 1L;
public size_t() { this(0); }
public size_t(long value) { super(Native.SIZE_T_SIZE, value); }
}
private static final Map<Class, Map<Integer,FFIType>> typeInfoMap = new WeakHashMap<>();
private static final Map<Class, FFIType> unionHelper = new WeakHashMap<>();
private static final Map<Pointer, FFIType> ffiTypeInfo = new HashMap<>();
// Native.initIDs initializes these fields to their appropriate
// pointer values. These are in a separate class from FFIType so that
// they may be initialized prior to loading the FFIType class
private static class FFITypes {
private static Pointer ffi_type_void;
private static Pointer ffi_type_float;
private static Pointer ffi_type_double;
private static Pointer ffi_type_longdouble;
private static Pointer ffi_type_uint8;
private static Pointer ffi_type_sint8;
private static Pointer ffi_type_uint16;
private static Pointer ffi_type_sint16;
private static Pointer ffi_type_uint32;
private static Pointer ffi_type_sint32;
private static Pointer ffi_type_uint64;
private static Pointer ffi_type_sint64;
private static Pointer ffi_type_pointer;
}
private static boolean isIntegerType(FFIType type) {
Pointer typePointer = type.getPointer();
return typePointer.equals(FFITypes.ffi_type_uint8)
|| typePointer.equals(FFITypes.ffi_type_sint8)
|| typePointer.equals(FFITypes.ffi_type_uint16)
|| typePointer.equals(FFITypes.ffi_type_sint16)
|| typePointer.equals(FFITypes.ffi_type_uint32)
|| typePointer.equals(FFITypes.ffi_type_sint32)
|| typePointer.equals(FFITypes.ffi_type_uint64)
|| typePointer.equals(FFITypes.ffi_type_sint64)
|| typePointer.equals(FFITypes.ffi_type_pointer);
}
private static boolean isFloatType(FFIType type) {
Pointer typePointer = type.getPointer();
return typePointer.equals(FFITypes.ffi_type_float)
|| typePointer.equals(FFITypes.ffi_type_double);
}
static {
if (Native.POINTER_SIZE == 0)
throw new Error("Native library not initialized");
if (FFITypes.ffi_type_void == null)
throw new Error("FFI types not initialized");
ffiTypeInfo.put(FFITypes.ffi_type_void, Structure.newInstance(FFIType.class, FFITypes.ffi_type_void));
ffiTypeInfo.put(FFITypes.ffi_type_float, Structure.newInstance(FFIType.class, FFITypes.ffi_type_float));
ffiTypeInfo.put(FFITypes.ffi_type_double, Structure.newInstance(FFIType.class, FFITypes.ffi_type_double));
ffiTypeInfo.put(FFITypes.ffi_type_longdouble, Structure.newInstance(FFIType.class, FFITypes.ffi_type_longdouble));
ffiTypeInfo.put(FFITypes.ffi_type_uint8, Structure.newInstance(FFIType.class, FFITypes.ffi_type_uint8));
ffiTypeInfo.put(FFITypes.ffi_type_sint8, Structure.newInstance(FFIType.class, FFITypes.ffi_type_sint8));
ffiTypeInfo.put(FFITypes.ffi_type_uint16, Structure.newInstance(FFIType.class, FFITypes.ffi_type_uint16));
ffiTypeInfo.put(FFITypes.ffi_type_sint16, Structure.newInstance(FFIType.class, FFITypes.ffi_type_sint16));
ffiTypeInfo.put(FFITypes.ffi_type_uint32, Structure.newInstance(FFIType.class, FFITypes.ffi_type_uint32));
ffiTypeInfo.put(FFITypes.ffi_type_sint32, Structure.newInstance(FFIType.class, FFITypes.ffi_type_sint32));
ffiTypeInfo.put(FFITypes.ffi_type_uint64, Structure.newInstance(FFIType.class, FFITypes.ffi_type_uint64));
ffiTypeInfo.put(FFITypes.ffi_type_sint64, Structure.newInstance(FFIType.class, FFITypes.ffi_type_sint64));
ffiTypeInfo.put(FFITypes.ffi_type_pointer, Structure.newInstance(FFIType.class, FFITypes.ffi_type_pointer));
for(FFIType f: ffiTypeInfo.values()) {
f.read();
}
storeTypeInfo(void.class, ffiTypeInfo.get(FFITypes.ffi_type_void));
storeTypeInfo(Void.class, ffiTypeInfo.get(FFITypes.ffi_type_void));
storeTypeInfo(float.class, ffiTypeInfo.get(FFITypes.ffi_type_float));
storeTypeInfo(Float.class, ffiTypeInfo.get(FFITypes.ffi_type_float));
storeTypeInfo(double.class, ffiTypeInfo.get(FFITypes.ffi_type_double));
storeTypeInfo(Double.class, ffiTypeInfo.get(FFITypes.ffi_type_double));
storeTypeInfo(long.class, ffiTypeInfo.get(FFITypes.ffi_type_sint64));
storeTypeInfo(Long.class, ffiTypeInfo.get(FFITypes.ffi_type_sint64));
storeTypeInfo(int.class, ffiTypeInfo.get(FFITypes.ffi_type_sint32));
storeTypeInfo(Integer.class, ffiTypeInfo.get(FFITypes.ffi_type_sint32));
storeTypeInfo(short.class, ffiTypeInfo.get(FFITypes.ffi_type_sint16));
storeTypeInfo(Short.class, ffiTypeInfo.get(FFITypes.ffi_type_sint16));
FFIType ctype = Native.WCHAR_SIZE == 2
? ffiTypeInfo.get(FFITypes.ffi_type_uint16) : ffiTypeInfo.get(FFITypes.ffi_type_uint32);
storeTypeInfo(char.class, ctype);
storeTypeInfo(Character.class, ctype);
storeTypeInfo(byte.class, ffiTypeInfo.get(FFITypes.ffi_type_sint8));
storeTypeInfo(Byte.class, ffiTypeInfo.get(FFITypes.ffi_type_sint8));
storeTypeInfo(Pointer.class, ffiTypeInfo.get(FFITypes.ffi_type_pointer));
storeTypeInfo(String.class, ffiTypeInfo.get(FFITypes.ffi_type_pointer));
storeTypeInfo(WString.class, ffiTypeInfo.get(FFITypes.ffi_type_pointer));
storeTypeInfo(boolean.class, ffiTypeInfo.get(FFITypes.ffi_type_uint32));
storeTypeInfo(Boolean.class, ffiTypeInfo.get(FFITypes.ffi_type_uint32));
}
// From ffi.h
private static final int FFI_TYPE_STRUCT = 13;
// Structure fields
public size_t size;
public short alignment;
public short type = FFI_TYPE_STRUCT;
public Pointer elements;
public FFIType(FFIType reference) {
this.size = reference.size;
this.alignment = reference.alignment;
this.type = reference.type;
this.elements = reference.elements;
}
public FFIType() {}
public FFIType(Structure ref) {
Pointer[] els;
ref.ensureAllocated(true);
if (ref instanceof Union) {
FFIType unionType = null;
int size = 0;
boolean hasInteger = false;
for (StructField sf : ref.fields().values()) {
FFIType type = ref.getFieldTypeInfo(sf);
if (isIntegerType(type)) {
hasInteger = true;
}
if (unionType == null
|| size < sf.size
|| (size == sf.size
&& Structure.class.isAssignableFrom(sf.type))) {
unionType = type;
size = sf.size;
}
}
if ((Platform.isIntel() && Platform.is64Bit() && !Platform.isWindows())
|| Platform.isARM() || Platform.isLoongArch()) {
// System V x86-64 ABI requires, that in a union aggregate,
// that contains Integer and Double members, the parameters
// must be passed in the integer registers. I.e. in the case
// where the java side declares double and int members, the
// wrong FFI Type would be found, because the doubles size
// is larger than the int member, but the wrong parameter
// passing method would be used.
//
// It was observed, that the same behaviour is visible on
// arm/aarch64/loongarch64.
if(hasInteger && isFloatType(unionType)) {
unionType = new FFIType(unionType);
if(unionType.size.intValue() == 4) {
unionType.type = ffiTypeInfo.get(FFITypes.ffi_type_uint32).type;
} else if (unionType.size.intValue() == 8) {
unionType.type = ffiTypeInfo.get(FFITypes.ffi_type_uint64).type;
}
unionType.write();
}
}
els = new Pointer[] {
unionType.getPointer(),
null,
};
unionHelper.put(ref.getClass(), unionType);
}
else {
els = new Pointer[ref.fields().size() + 1];
int idx = 0;
for (StructField sf : ref.fields().values()) {
els[idx++] = ref.getFieldTypeInfo(sf).getPointer();
}
}
init(els);
write();
}
// Represent fixed-size arrays as structures of N identical elements
public FFIType(Object array, Class<?> type) {
int length = Array.getLength(array);
Pointer[] els = new Pointer[length+1];
Pointer p = get(null, type.getComponentType()).getPointer();
for (int i=0;i < length;i++) {
els[i] = p;
}
init(els);
write();
}
private void init(Pointer[] els) {
elements = new Memory(Native.POINTER_SIZE * els.length);
elements.write(0, els, 0, els.length);
write();
}
/** Obtain a pointer to the native FFI type descriptor for the given object. */
static FFIType get(Object obj) {
if (obj == null)
synchronized (typeInfoMap) {
return getTypeInfo(Pointer.class, 0);
}
if (obj instanceof Class)
return get(null, (Class<?>)obj);
return get(obj, obj.getClass());
}
private static FFIType get(Object obj, Class<?> cls) {
TypeMapper mapper = Native.getTypeMapper(cls);
if (mapper != null) {
ToNativeConverter nc = mapper.getToNativeConverter(cls);
if (nc != null) {
cls = nc.nativeType();
}
}
synchronized(typeInfoMap) {
FFIType o = getTypeInfo(cls, cls.isArray() ? Array.getLength(obj) : 0);
if (o != null) {
return o;
}
if ((Platform.HAS_BUFFERS && Buffer.class.isAssignableFrom(cls))
|| Callback.class.isAssignableFrom(cls)) {
typeInfoMap.put(cls, typeInfoMap.get(Pointer.class));
return typeInfoMap.get(Pointer.class).get(0);
}
if (Structure.class.isAssignableFrom(cls)) {
if (obj == null) obj = newInstance((Class<? extends Structure>) cls, PLACEHOLDER_MEMORY);
if (ByReference.class.isAssignableFrom(cls)) {
typeInfoMap.put(cls, typeInfoMap.get(Pointer.class));
return typeInfoMap.get(Pointer.class).get(0);
}
FFIType type = new FFIType((Structure)obj);
storeTypeInfo(cls, type);
return type;
}
if (NativeMapped.class.isAssignableFrom(cls)) {
NativeMappedConverter c = NativeMappedConverter.getInstance(cls);
return get(c.toNative(obj, new ToNativeContext()), c.nativeType());
}
if (cls.isArray()) {
FFIType type = new FFIType(obj, cls);
// Store it in the map to prevent premature GC of type info
storeTypeInfo(cls, Array.getLength(obj), type);
return type;
}
throw new IllegalArgumentException("Unsupported type " + cls);
}
}
private static FFIType getTypeInfo(Class clazz, int elementCount) {
Map<Integer,FFIType> typeMap = typeInfoMap.get(clazz);
if(typeMap != null) {
return typeMap.get(elementCount);
} else {
return null;
}
}
private static void storeTypeInfo(Class clazz, FFIType type) {
storeTypeInfo(clazz, 0, type);
}
private static void storeTypeInfo(Class clazz, int elementCount, FFIType type) {
synchronized (typeInfoMap) {
Map<Integer,FFIType> typeMap = typeInfoMap.get(clazz);
if(typeMap == null) {
typeMap = new HashMap<>();
typeInfoMap.put(clazz, typeMap);
}
typeMap.put(elementCount, type);
}
}
}
private static class AutoAllocated extends Memory {
public AutoAllocated(int size) {
super(size);
// Always clear new structure memory
super.clear();
}
@Override
public String toString() {
return "auto-" + super.toString();
}
}
private static void structureArrayCheck(Structure[] ss) {
if (Structure.ByReference[].class.isAssignableFrom(ss.getClass())) {
return;
}
Pointer base = ss[0].getPointer();
int size = ss[0].size();
for (int si=1;si < ss.length;si++) {
if (ss[si].getPointer().peer != base.peer + size*si) {
String msg = "Structure array elements must use"
+ " contiguous memory (bad backing address at Structure array index " + si + ")";
throw new IllegalArgumentException(msg);
}
}
}
public static void autoRead(Structure[] ss) {
structureArrayCheck(ss);
if (ss[0].array == ss) {
ss[0].autoRead();
}
else {
for (int si=0;si < ss.length;si++) {
if (ss[si] != null) {
ss[si].autoRead();
}
}
}
}
public void autoRead() {
if (getAutoRead()) {
read();
if (array != null) {
for (int i=1;i < array.length;i++) {
array[i].autoRead();
}
}
}
}
public static void autoWrite(Structure[] ss) {
structureArrayCheck(ss);
if (ss[0].array == ss) {
ss[0].autoWrite();
}
else {
for (int si=0;si < ss.length;si++) {
if (ss[si] != null) {
ss[si].autoWrite();
}
}
}
}
public void autoWrite() {
if (getAutoWrite()) {
write();
if (array != null) {
for (int i=1;i < array.length;i++) {
array[i].autoWrite();
}
}
}
}
/** Return the native size of the given Java type, from the perspective of
* this Structure.
* @param nativeType field type to examine
* @return native size (in bytes) of the requested field type
*/
protected int getNativeSize(Class<?> nativeType) {
return getNativeSize(nativeType, null);
}
/** Return the native size of the given Java type, from the perspective of
* this Structure.
* @param nativeType field type to examine
* @param value instance of the field type
* @return native size (in bytes) of the requested field type
*/
protected int getNativeSize(Class<?> nativeType, Object value) {
return Native.getNativeSize(nativeType, value);
}
/** Placeholder pointer to help avoid auto-allocation of memory where a
* Structure needs a valid pointer but want to avoid actually reading from it.
*/
private static final Pointer PLACEHOLDER_MEMORY = new Pointer(0) {
@Override
public Pointer share(long offset, long sz) { return this; }
};
/** Indicate whether the given Structure class can be created by JNA.
* @param cls Structure subclass to check
*/
static void validate(Class<? extends Structure> cls) {
try {
cls.getConstructor();
return;
}catch(NoSuchMethodException | SecurityException e) {
}
throw new IllegalArgumentException("No suitable constructor found for class: " + cls.getName());
}
}
| java-native-access/jna | src/com/sun/jna/Structure.java |
2,784 | package com.winterbe.java8.samples.stream;
import java.util.Optional;
import java.util.function.Supplier;
/**
* Examples how to avoid null checks with Optional:
*
* http://winterbe.com/posts/2015/03/15/avoid-null-checks-in-java/
*
* @author Benjamin Winterberg
*/
public class Optional2 {
static class Outer {
Nested nested = new Nested();
public Nested getNested() {
return nested;
}
}
static class Nested {
Inner inner = new Inner();
public Inner getInner() {
return inner;
}
}
static class Inner {
String foo = "boo";
public String getFoo() {
return foo;
}
}
public static void main(String[] args) {
test1();
test2();
test3();
}
public static <T> Optional<T> resolve(Supplier<T> resolver) {
try {
T result = resolver.get();
return Optional.ofNullable(result);
}
catch (NullPointerException e) {
return Optional.empty();
}
}
private static void test3() {
Outer outer = new Outer();
resolve(() -> outer.getNested().getInner().getFoo())
.ifPresent(System.out::println);
}
private static void test2() {
Optional.of(new Outer())
.map(Outer::getNested)
.map(Nested::getInner)
.map(Inner::getFoo)
.ifPresent(System.out::println);
}
private static void test1() {
Optional.of(new Outer())
.flatMap(o -> Optional.ofNullable(o.nested))
.flatMap(n -> Optional.ofNullable(n.inner))
.flatMap(i -> Optional.ofNullable(i.foo))
.ifPresent(System.out::println);
}
}
| winterbe/java8-tutorial | src/com/winterbe/java8/samples/stream/Optional2.java |
2,785 | package com.winterbe.java8.samples.misc;
/**
* @author Benjamin Winterberg
*/
public class Math1 {
public static void main(String[] args) {
testMathExact();
testUnsignedInt();
}
private static void testUnsignedInt() {
try {
Integer.parseUnsignedInt("-123", 10);
}
catch (NumberFormatException e) {
System.out.println(e.getMessage());
}
long maxUnsignedInt = (1l << 32) - 1;
System.out.println(maxUnsignedInt);
String string = String.valueOf(maxUnsignedInt);
int unsignedInt = Integer.parseUnsignedInt(string, 10);
System.out.println(unsignedInt);
String string2 = Integer.toUnsignedString(unsignedInt, 10);
System.out.println(string2);
try {
Integer.parseInt(string, 10);
}
catch (NumberFormatException e) {
System.err.println("could not parse signed int of " + maxUnsignedInt);
}
}
private static void testMathExact() {
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MAX_VALUE + 1);
try {
Math.addExact(Integer.MAX_VALUE, 1);
}
catch (ArithmeticException e) {
System.err.println(e.getMessage());
}
try {
Math.toIntExact(Long.MAX_VALUE);
}
catch (ArithmeticException e) {
System.err.println(e.getMessage());
}
}
}
| winterbe/java8-tutorial | src/com/winterbe/java8/samples/misc/Math1.java |