下面列出了com.google.protobuf.ByteString#substring ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Internal
// exposed for use in `TransactionRecord`
public ContractFunctionResult(ContractFunctionResultOrBuilder inner) {
contractId = new ContractId(inner.getContractIDOrBuilder());
String errMsg = inner.getErrorMessage();
errorMessage = !errMsg.isEmpty() ? errMsg : null;
ByteString callResult = inner.getContractCallResult();
// if an exception was thrown, the call result is encoded like the params
// for a function `Error(string)`
// https://solidity.readthedocs.io/en/v0.6.2/control-structures.html#revert
if (errorMessage != null && callResult.startsWith(errorPrefix)) {
// trim off the function selector bytes
rawResult = callResult.substring(4);
} else {
rawResult = callResult;
}
bloom = inner.getBloom().toByteArray();
gasUsed = inner.getGasUsed();
logs = inner.getLogInfoList().stream().map(ContractLogInfo::new).collect(Collectors.toList());
}
public static ByteString findLongestCommonStart(Set<ByteString> rests)
{
ByteString longest = null;
for(ByteString bs : rests)
{
if (longest == null) longest = bs;
else
{
int sz = Math.min(longest.size(), bs.size());
int match = 0;
for(int i=0; i<sz; i++)
{
if (longest.byteAt(i) == bs.byteAt(i))
{
match = i;
}
else break;
}
longest = bs.substring(0, match +1);
}
}
return longest;
}
@Override
public synchronized Collection<TransactionOutPoint> getUnspentForScriptHash(ByteString prefix)
{
Collection<ByteString> txinfo = db_map.getSet(prefix, 10000);
LinkedList<TransactionOutPoint> outs = new LinkedList<TransactionOutPoint>();
for(ByteString key : txinfo)
{
ByteString tx_data = key.substring(0,32);
ByteBuffer bb = ByteBuffer.wrap(key.substring(32).toByteArray());
bb.order(java.nio.ByteOrder.LITTLE_ENDIAN);
int idx=bb.getInt();
Sha256Hash tx_id = Sha256Hash.wrap(tx_data.toByteArray());
TransactionOutPoint o = new TransactionOutPoint(jelly.getNetworkParameters(), idx, tx_id);
outs.add(o);
}
return outs;
}
public static List<TagValue> from(ByteString tagLengthValues) throws BadDataException {
List<TagValue> tagValues = new ArrayList<>();
int i = 0;
while (i + 8 <= tagLengthValues.size()) {
String tag = tagLengthValues.substring(i, i + 4).toStringUtf8();
// Signed 32 bit length. Limited to 2 GB.
int length = tagLengthValues.substring(i + 4, i + 8).asReadOnlyByteBuffer().getInt();
int end = i + 8 + length;
if (length < 0 || end > tagLengthValues.size()) {
throw new BadDataException("Bad TagLengthValue length: " + length);
}
TagValue tagValue = new TagValue(tag, tagLengthValues.substring(i + 8, end));
tagValues.add(tagValue);
i += 8 + length;
}
return tagValues;
}
private static ByteString getPrefix(ByteString byteString) {
if (byteString.size() <= PREFIX_LEN) {
return byteString;
}
return byteString.substring(0, PREFIX_LEN);
}
public static ByteString plusOne(ByteString key) {
int max = key.size() - 1;
if (max < 0) {
return singleByte(1);
}
int lastPlusOne = key.byteAt(max) + 1;
ByteString excludeLast = key.substring(0, max);
return lastPlusOne == 0 ? plusOne(excludeLast)
: excludeLast.concat(singleByte(lastPlusOne));
}
public static ByteString getCompressedPublicKeyEncoding(PublicKey key)
{
ByteString full = ByteString.copyFrom(key.getEncoded());
Assert.assertTrue(full.startsWith(EC_SECP256K1_PREFIX));
Assert.assertEquals( full.size(), EC_SECP256K1_PREFIX.size() + 33);
return full.substring(EC_SECP256K1_PREFIX.size());
}
@Override
public List<ByteString> getSet(ByteString key, int max_reply)
{
ByteString dbKey = getDBKey(key);
LinkedList<ByteString> set = new LinkedList<>();
int count = 0;
try(RocksIterator it = db.newIterator())
{
it.seek(dbKey.toByteArray());
while(it.isValid())
{
ByteString curr_key = ByteString.copyFrom(it.key());
if (!curr_key.startsWith(dbKey)) break;
ByteString v = curr_key.substring(dbKey.size());
set.add(v);
count++;
if (count > max_reply) throw new DBTooManyResultsException();
it.next();
}
}
return set;
}
/**
* Takes a string from encode above and turns it back into
* bytes. The string can be with or without the "label:" on it.
* Either way, expected_label is used to validate the checksum.
*/
public static ByteString decode(String expected_label, String encoding)
throws ValidationException
{
int colon = encoding.indexOf(':');
String data_str;
if (colon > 0)
{
String found_label = encoding.substring(0, colon);
// Use found label if we have null
if (expected_label == null) expected_label = found_label;
data_str = encoding.substring(colon+1);
if (!expected_label.equals(found_label))
{
throw new ValidationException(String.format("Expected label %s, found %s", expected_label, found_label));
}
}
else
{
data_str = encoding;
}
ByteString fulldata = convertBase32ToBytes(data_str);
ByteString data = fulldata.substring(0, Globals.ADDRESS_SPEC_HASH_LEN);
ByteString checksum = fulldata.substring(Globals.ADDRESS_SPEC_HASH_LEN);
validateChecksum(expected_label, data, checksum);
return data;
}
/** Writes part of a ByteString into a ByteBuffer with as little copying as possible */
private static final void put(ByteString source, int offset, int size, ByteBuffer dest) {
ByteString croppedSource = source.substring(offset, offset + size);
for (ByteBuffer sourcePiece : croppedSource.asReadOnlyByteBufferList()) {
dest.put(sourcePiece);
}
}
public Set<ByteString> getSet(ByteString key, int max_reply)
{
ByteString dbKey = getDBKey(key);
HashSet<ByteString> set = new HashSet<>();
int count = 0;
RocksIterator it = db.newIterator();
try
{
it.seek(dbKey.toByteArray());
while(it.isValid())
{
ByteString curr_key = ByteString.copyFrom(it.key());
if (!curr_key.startsWith(dbKey)) break;
ByteString v = curr_key.substring(dbKey.size());
set.add(v);
count++;
if (count > max_reply) throw new DBTooManyResultsException();
it.next();
}
}
finally
{
it.dispose();
}
return set;
}
/**
* Decodes the current element updating the buffer to only contain the unconsumed bytes.
*
* <p>This invalidates the currently stored {@code startOfDelimiterInBuffer} and {@code
* endOfDelimiterInBuffer}.
*/
private void decodeCurrentElement() throws IOException {
ByteString dataToDecode = buffer.substring(0, startOfDelimiterInBuffer);
// If present, the UTF8 Byte Order Mark (BOM) will be removed.
if (startOfRecord == 0 && dataToDecode.startsWith(UTF8_BOM)) {
dataToDecode = dataToDecode.substring(UTF8_BOM.size());
}
currentValue = dataToDecode.toStringUtf8();
elementIsPresent = true;
buffer = buffer.substring(endOfDelimiterInBuffer);
}
private static ByteString shiftByStatus(ByteString v, Status s) {
switch (s) {
case EQUAL:
return v;
case LESS:
return v.substring(0, v.size() - 1);
case GREATER:
return v.concat(ByteString.copyFrom(new byte[] {1, 0}));
default:
throw new IllegalArgumentException("Only EQUAL,LESS,GREATER allowed");
}
}
ServerCallStreamObserver<ByteString> newChunkObserver(
ServerCallStreamObserver<ReadResponse> responseObserver) {
return new DelegateServerCallStreamObserver<ByteString, ReadResponse>(responseObserver) {
@Override
public void onNext(ByteString data) {
while (!data.isEmpty()) {
ByteString slice;
if (data.size() > CHUNK_SIZE) {
slice = data.substring(0, CHUNK_SIZE);
data = data.substring(CHUNK_SIZE);
} else {
slice = data;
data = ByteString.EMPTY;
}
responseObserver.onNext(ReadResponse.newBuilder().setData(slice).build());
}
}
@Override
public void onError(Throwable t) {
responseObserver.onError(t);
}
@Override
public void onCompleted() {
responseObserver.onCompleted();
}
};
}
private void expectSubstringIndexOutOfBounds(ByteString bs, int startIndex, int endIndex) {
try {
bs.substring(startIndex, endIndex);
fail("Expected IndexOutOfBoundsException to be thrown");
} catch (IndexOutOfBoundsException e) {
// Expected
}
}
public void testByteStringSubstring() throws Exception {
ByteString bs1 = ByteString.copyFrom("abcdefghijklmnop".getBytes("UTF-8"));
ByteString bs2 = bs1.substring(1, 15);
assertEquals("bcdefghijklmno", new String(bs2.toByteArray(), "UTF-8"));
ByteString bs3 = bs1.substring(12);
assertEquals("mnop", new String(bs3.toByteArray(), "UTF-8"));
ByteString bs4 = bs1.substring(11, 11);
assertTrue(bs4.isEmpty());
expectSubstringIndexOutOfBounds(bs1, -1, 1);
expectSubstringIndexOutOfBounds(bs1, 0, 17);
expectSubstringIndexOutOfBounds(bs1, 7, 6);
}
@Override
public Map<ByteString, ByteString> getByPrefix(ByteString key, int max_reply, boolean allow_partial)
{
ByteString key_str = prefix.concat(key);
LinkedList<ByteString> set = new LinkedList<>();
Map<ByteString, ByteString> map = new HashMap<>(16,0.5f);
int count = 0;
RocksIterator it = db.newIterator();
try
{
it.seek(key_str.toByteArray());
while(it.isValid())
{
ByteString curr_key = ByteString.copyFrom(it.key());
if (!curr_key.startsWith(key_str)) break;
ByteString k = curr_key.substring(prefix.size());
map.put(k, ByteString.copyFrom(it.value()));
count++;
if (count > max_reply)
{
if (allow_partial) return map;
else throw new DBTooManyResultsException();
}
it.next();
}
}
finally
{
it.dispose();
}
return map;
}
public static List<Coprocessor.KeyRange> split(Coprocessor.KeyRange range, int splitFactor) {
if (splitFactor > 32 || splitFactor <= 0 || (splitFactor & (splitFactor - 1)) != 0) {
throw new TiClientInternalException(
"splitFactor must be positive integer power of 2 and no greater than 16");
}
ByteString startKey = range.getStart();
ByteString endKey = range.getEnd();
// we don't cut infinite
if (startKey.isEmpty() || endKey.isEmpty()) {
return ImmutableList.of(range);
}
ImmutableList.Builder<Coprocessor.KeyRange> resultList = ImmutableList.builder();
int maxSize = Math.max(startKey.size(), endKey.size());
int i;
for (i = 0; i < maxSize; i++) {
byte sb = i < startKey.size() ? startKey.byteAt(i) : 0;
byte eb = i < endKey.size() ? endKey.byteAt(i) : 0;
if (sb != eb) {
break;
}
}
ByteString sRemaining = i < startKey.size() ? startKey.substring(i) : ByteString.EMPTY;
ByteString eRemaining = i < endKey.size() ? endKey.substring(i) : ByteString.EMPTY;
CodecDataInput cdi = new CodecDataInput(sRemaining);
int uss = cdi.readPartialUnsignedShort();
cdi = new CodecDataInput(eRemaining);
int ues = cdi.readPartialUnsignedShort();
int delta = (ues - uss) / splitFactor;
if (delta <= 0) {
return ImmutableList.of(range);
}
ByteString prefix = startKey.size() > endKey.size() ?
startKey.substring(0, i) : endKey.substring(0, i);
ByteString newStartKey = startKey;
ByteString newEndKey;
for (int j = 0; j < splitFactor; j++) {
uss += delta;
if (j == splitFactor - 1) {
newEndKey = endKey;
} else {
CodecDataOutput cdo = new CodecDataOutput();
cdo.writeShort(uss);
newEndKey = prefix.concat(cdo.toByteString());
}
resultList.add(makeCoprocRange(newStartKey, newEndKey));
newStartKey = newEndKey;
}
return resultList.build();
}
@Test
public void writeCanBeResumed() throws IOException, InterruptedException {
ByteString helloWorld = ByteString.copyFromUtf8("Hello, World!");
Digest digest = DIGEST_UTIL.compute(helloWorld);
String uuid = UUID.randomUUID().toString();
String resourceName = createBlobUploadResourceName(uuid, digest);
Channel channel = InProcessChannelBuilder.forName(fakeServerName).directExecutor().build();
ClientCall<WriteRequest, WriteResponse> initialCall =
channel.newCall(ByteStreamGrpc.getWriteMethod(), CallOptions.DEFAULT);
ByteString initialData = helloWorld.substring(0, 6);
ClientCall.Listener<WriteResponse> initialCallListener =
new ClientCall.Listener<WriteResponse>() {
boolean complete = false;
boolean callHalfClosed = false;
@Override
public void onReady() {
while (initialCall.isReady()) {
if (complete) {
if (!callHalfClosed) {
initialCall.halfClose();
callHalfClosed = true;
}
return;
}
initialCall.sendMessage(
WriteRequest.newBuilder()
.setResourceName(resourceName)
.setData(initialData)
.build());
complete = true;
}
}
};
initialCall.start(initialCallListener, new Metadata());
initialCall.request(1);
ByteStreamBlockingStub service = ByteStreamGrpc.newBlockingStub(channel);
QueryWriteStatusResponse response =
service.queryWriteStatus(
QueryWriteStatusRequest.newBuilder().setResourceName(resourceName).build());
assertThat(response.getCommittedSize()).isEqualTo(initialData.size());
assertThat(response.getComplete()).isFalse();
ClientCall<WriteRequest, WriteResponse> finishCall =
channel.newCall(ByteStreamGrpc.getWriteMethod(), CallOptions.DEFAULT);
ClientCall.Listener<WriteResponse> finishCallListener =
new ClientCall.Listener<WriteResponse>() {
boolean complete = false;
boolean callHalfClosed = false;
@Override
public void onReady() {
while (finishCall.isReady()) {
if (complete) {
if (!callHalfClosed) {
finishCall.halfClose();
callHalfClosed = true;
}
return;
}
finishCall.sendMessage(
WriteRequest.newBuilder()
.setResourceName(resourceName)
.setWriteOffset(initialData.size())
.setData(helloWorld.substring(initialData.size()))
.setFinishWrite(true)
.build());
complete = true;
}
}
};
finishCall.start(finishCallListener, new Metadata());
finishCall.request(1);
ArgumentCaptor<InputStream> inputStreamCaptor = ArgumentCaptor.forClass(InputStream.class);
verify(simpleBlobStore, times(1))
.put(eq(digest.getHash()), eq(digest.getSizeBytes()), inputStreamCaptor.capture());
InputStream inputStream = inputStreamCaptor.getValue();
assertThat(inputStream.available()).isEqualTo(helloWorld.size());
byte[] data = new byte[helloWorld.size()];
assertThat(inputStream.read(data)).isEqualTo(helloWorld.size());
assertThat(data).isEqualTo(helloWorld.toByteArray());
}