com.google.protobuf.ByteString#substring ( )源码实例Demo

下面列出了com.google.protobuf.ByteString#substring ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: hedera-sdk-java   文件: ContractFunctionResult.java
@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());
}
 
源代码2 项目: snowblossom   文件: HashedTrie.java
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;

}
 
源代码3 项目: jelectrum   文件: SimpleUtxoMgr.java
@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;
}
 
源代码4 项目: LiquidDonkey   文件: TagValue.java
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;
}
 
源代码5 项目: hedera-sdk-java   文件: Transaction.java
private static ByteString getPrefix(ByteString byteString) {
    if (byteString.size() <= PREFIX_LEN) {
        return byteString;
    }

    return byteString.substring(0, PREFIX_LEN);
}
 
源代码6 项目: etcd-java   文件: KeyUtils.java
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));
}
 
源代码7 项目: snowblossom   文件: KeyUtil.java
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());
}
 
源代码8 项目: snowblossom   文件: RocksDBMapMutationSet.java
@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;

}
 
源代码9 项目: snowblossom   文件: Duck32.java
/**
 * 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);
  }
}
 
源代码11 项目: jelectrum   文件: RocksDBMapMutationSet.java
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;

}
 
源代码12 项目: DataflowTemplates   文件: TextSource.java
/**
 * 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);
}
 
源代码13 项目: tikv-client-lib-java   文件: RangeSplitterTest.java
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");
  }
}
 
源代码14 项目: bazel-buildfarm   文件: ByteStreamService.java
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();
    }
  };
}
 
源代码15 项目: j2objc   文件: CompatibilityTest.java
private void expectSubstringIndexOutOfBounds(ByteString bs, int startIndex, int endIndex) {
  try {
    bs.substring(startIndex, endIndex);
    fail("Expected IndexOutOfBoundsException to be thrown");
  } catch (IndexOutOfBoundsException e) {
    // Expected
  }
}
 
源代码16 项目: j2objc   文件: CompatibilityTest.java
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);
}
 
源代码17 项目: snowblossom   文件: RocksDBMap.java
@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;

}
 
源代码18 项目: tikv-client-lib-java   文件: KeyRangeUtils.java
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();
}
 
源代码19 项目: bazel-buildfarm   文件: ByteStreamServiceTest.java
@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());
}
 
源代码20 项目: jetcd   文件: Util.java
public static ByteString unprefixNamespace(ByteString key, ByteSequence namespace) {
    return namespace.isEmpty() ? key : key.substring(namespace.size());
}