本文整理了Java中okio.Buffer
类的一些代码示例,展示了Buffer
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Buffer
类的具体详情如下:
包路径:okio.Buffer
类名称:Buffer
[英]A collection of bytes in memory.
Moving data from one buffer to another is fast. Instead of copying bytes from one place in memory to another, this class just changes ownership of the underlying byte arrays.
This buffer grows with your data. Just like ArrayList, each buffer starts small. It consumes only the memory it needs to.
This buffer pools its byte arrays. When you allocate a byte array in Java, the runtime must zero-fill the requested array before returning it to you. Even if you're going to write over that space anyway. This class avoids zero-fill and GC churn by pooling byte arrays.
[中]内存中字节的集合。
将数据从一个缓冲区移动到另一个缓冲区很快。此类并没有将字节从内存中的一个位置复制到另一个位置,而是更改底层字节数组的所有权。
此缓冲区随数据的增长而增长。就像ArrayList一样,每个缓冲区的开始都很小。它只消耗所需的内存。
此缓冲区汇集其字节数组。在Java中分配字节数组时,运行时必须在将请求的数组返回给您之前对其进行零填充。即使你无论如何都要在上面写。此类通过共享字节数组避免了零填充和GC搅动。
代码示例来源:origin: square/okhttp
/**
* Reads a double-quoted string, unescaping quoted pairs like {@code \"} to the 2nd character in
* each sequence. Returns the unescaped string, or null if the buffer isn't prefixed with a
* double-quoted string.
*/
private static String readQuotedString(Buffer buffer) {
if (buffer.readByte() != '\"') throw new IllegalArgumentException();
Buffer result = new Buffer();
while (true) {
long i = buffer.indexOfElement(QUOTED_STRING_DELIMITERS);
if (i == -1L) return null; // Unterminated quoted string.
if (buffer.getByte(i) == '"') {
result.write(buffer, i);
buffer.readByte(); // Consume '"'.
return result.readUtf8();
}
if (buffer.size() == i + 1L) return null; // Dangling escape.
result.write(buffer, i);
buffer.readByte(); // Consume '\'.
result.write(buffer, 1L); // The escaped character.
}
}
代码示例来源:origin: square/okhttp
public MockResponse setBody(Buffer body) {
setHeader("Content-Length", body.size());
this.body = body.clone(); // Defensive copy.
return this;
}
代码示例来源:origin: jgilfelt/chuck
private String readFromBuffer(Buffer buffer, Charset charset) {
long bufferSize = buffer.size();
long maxBytes = Math.min(bufferSize, maxContentLength);
String body = "";
try {
body = buffer.readString(maxBytes, charset);
} catch (EOFException e) {
body += context.getString(R.string.chuck_body_unexpected_eof);
}
if (bufferSize > maxContentLength) {
body += context.getString(R.string.chuck_body_content_truncated);
}
return body;
}
代码示例来源:origin: square/okhttp
@Override public void writeTo(BufferedSink sink) throws IOException {
buffer.copyTo(sink.buffer(), 0, buffer.size());
}
}
代码示例来源:origin: square/okhttp
/**
* Consumes and returns a non-empty token, terminating at special characters in {@link
* #TOKEN_DELIMITERS}. Returns null if the buffer is empty or prefixed with a delimiter.
*/
private static String readToken(Buffer buffer) {
try {
long tokenSize = buffer.indexOfElement(TOKEN_DELIMITERS);
if (tokenSize == -1L) tokenSize = buffer.size();
return tokenSize != 0L
? buffer.readUtf8(tokenSize)
: null;
} catch (EOFException e) {
throw new AssertionError();
}
}
代码示例来源:origin: huxq17/tractor
@Override public String readUtf8LineStrict() throws EOFException {
long newline = indexOf((byte) '\n');
if (newline == -1) {
Buffer data = new Buffer();
copyTo(data, 0, Math.min(32, size));
throw new EOFException("\\n not found: size=" + size()
+ " content=" + data.readByteString().hex() + "...");
}
return readUtf8Line(newline);
}
代码示例来源:origin: square/moshi
if (!source.request(1)) {
throw syntaxError("Unterminated escape sequence");
byte escaped = buffer.readByte();
switch (escaped) {
case 'u':
if (!source.request(4)) {
throw new EOFException("Unterminated escape sequence at path " + getPath());
byte c = buffer.getByte(i);
result <<= 4;
if (c >= '0' && c <= '9') {
result += (c - 'A' + 10);
} else {
throw syntaxError("\\u" + buffer.readUtf8(4));
buffer.skip(4);
return result;
代码示例来源:origin: square/okhttp
synchronized (Http2Stream.this) {
finished = this.finished;
flowControlError = byteCount + readBuffer.size() > maxByteCount;
in.skip(byteCount);
closeLater(ErrorCode.FLOW_CONTROL_ERROR);
return;
in.skip(byteCount);
return;
long read = in.read(receiveBuffer, byteCount);
if (read == -1) throw new EOFException();
byteCount -= read;
boolean wasEmpty = readBuffer.size() == 0;
readBuffer.writeAll(receiveBuffer);
if (wasEmpty) {
Http2Stream.this.notifyAll();
代码示例来源:origin: huxq17/tractor
@Override public void skip(long byteCount) throws IOException {
if (closed) throw new IllegalStateException("closed");
while (byteCount > 0) {
if (buffer.size == 0 && source.read(buffer, Segment.SIZE) == -1) {
throw new EOFException();
}
long toSkip = Math.min(byteCount, buffer.size());
buffer.skip(toSkip);
byteCount -= toSkip;
}
}
代码示例来源:origin: square/okio
@Test public void originalDoesNotObserveWritesToClone() {
Buffer original = new Buffer();
Buffer clone = original.clone();
clone.writeUtf8("abc");
assertEquals(0, original.size());
}
代码示例来源:origin: square/okio
@Test public void testReadChannel() throws Exception {
ReadableByteChannel channel = new Buffer().writeUtf8(quote);
Buffer buffer = new Buffer();
Source source = new ByteChannelSource(channel, Timeout.NONE);
source.read(buffer, 75);
assertThat(buffer.readUtf8())
.isEqualTo("John, the kind of control you're attempting simply is... it's not possible.");
}
代码示例来源:origin: smuyyh/BookReader
logger.log("--> END " + request.method() + " (encoded body omitted)");
} else {
Buffer buffer = new Buffer();
requestBody.writeTo(buffer);
logger.log(buffer.readString(charset));
} else {
BufferedSource source = responseBody.source();
source.request(Long.MAX_VALUE); // Buffer the entire body.
Buffer buffer = source.buffer();
logger.log(buffer.clone().readString(charset));
logger.log("<-- END HTTP (" + buffer.size() + "-byte body)");
代码示例来源:origin: square/okhttp
logger.log("--> END " + request.method() + " (encoded body omitted)");
} else {
Buffer buffer = new Buffer();
requestBody.writeTo(buffer);
logger.log(buffer.readString(charset));
logger.log("--> END " + request.method()
+ " (" + requestBody.contentLength() + "-byte body)");
} else {
BufferedSource source = responseBody.source();
source.request(Long.MAX_VALUE); // Buffer the entire body.
Buffer buffer = source.getBuffer();
gzippedLength = buffer.size();
try (GzipSource gzippedResponseBody = new GzipSource(buffer.clone())) {
buffer = new Buffer();
buffer.writeAll(gzippedResponseBody);
logger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
return response;
logger.log(buffer.clone().readString(charset));
logger.log("<-- END HTTP (" + buffer.size() + "-byte, "
+ gzippedLength + "-gzipped-byte body)");
} else {
logger.log("<-- END HTTP (" + buffer.size() + "-byte body)");
代码示例来源:origin: square/okio
@Test public void writeAll() throws Exception {
Buffer source = new Buffer().writeUtf8("abcdef");
assertEquals(6, sink.writeAll(source));
assertEquals(0, source.size());
sink.flush();
assertEquals("abcdef", data.readUtf8());
}
代码示例来源:origin: square/okhttp
public static ByteString encodeQuery(String host, int type) {
Buffer buf = new Buffer();
buf.writeShort(0); // query id
buf.writeShort(256); // flags with recursion
buf.writeShort(1); // question count
buf.writeShort(0); // answerCount
buf.writeShort(0); // authorityResourceCount
buf.writeShort(0); // additional
Buffer nameBuf = new Buffer();
final String[] labels = host.split("\\.");
for (String label : labels) {
long utf8ByteCount = Utf8.size(label);
if (utf8ByteCount != label.length()) {
throw new IllegalArgumentException("non-ascii hostname: " + host);
}
nameBuf.writeByte((byte) utf8ByteCount);
nameBuf.writeUtf8(label);
}
nameBuf.writeByte(0); // end
nameBuf.copyTo(buf, 0, nameBuf.size());
buf.writeShort(type);
buf.writeShort(1); // CLASS_IN
return buf.readByteString();
}
代码示例来源:origin: square/okio
@Test public void readFullyTooShortThrows() throws IOException {
sink.writeUtf8("Hi");
sink.emit();
Buffer sink = new Buffer();
try {
source.readFully(sink, 5);
fail();
} catch (EOFException ignored) {
}
// Verify we read all that we could from the source.
assertEquals("Hi", sink.readUtf8());
}
代码示例来源:origin: square/okio
@Test public void readFullyByteArray() throws IOException {
Buffer data = new Buffer();
data.writeUtf8("Hello").writeUtf8(repeat('e', SEGMENT_SIZE));
byte[] expected = data.clone().readByteArray();
sink.write(data, data.size());
sink.emit();
byte[] sink = new byte[SEGMENT_SIZE + 5];
source.readFully(sink);
assertByteArraysEquals(expected, sink);
}
代码示例来源:origin: square/okio
@Test public void writeAll() throws IOException {
MockSink mockSink = new MockSink();
BufferedSink bufferedSink = Okio.buffer(mockSink);
bufferedSink.getBuffer().writeUtf8("abc");
assertEquals(3, bufferedSink.writeAll(new Buffer().writeUtf8("def")));
assertEquals(6, bufferedSink.getBuffer().size());
assertEquals("abcdef", bufferedSink.getBuffer().readUtf8(6));
mockSink.assertLog(); // No writes.
}
代码示例来源:origin: square/okhttp
/**
* Sets the response body to {@code body}, chunked every {@code maxChunkSize} bytes.
*/
public MockResponse setChunkedBody(Buffer body, int maxChunkSize) {
removeHeader("Content-Length");
headers.add(CHUNKED_BODY_HEADER);
Buffer bytesOut = new Buffer();
while (!body.exhausted()) {
long chunkSize = Math.min(body.size(), maxChunkSize);
bytesOut.writeHexadecimalUnsignedLong(chunkSize);
bytesOut.writeUtf8("\r\n");
bytesOut.write(body, chunkSize);
bytesOut.writeUtf8("\r\n");
}
bytesOut.writeUtf8("0\r\n"); // Last chunk. Trailers follow!
this.body = bytesOut;
return this;
}
代码示例来源:origin: square/okhttp
static String percentDecode(String encoded, int pos, int limit, boolean plusIsSpace) {
for (int i = pos; i < limit; i++) {
char c = encoded.charAt(i);
if (c == '%' || (c == '+' && plusIsSpace)) {
// Slow path: the character at i requires decoding!
Buffer out = new Buffer();
out.writeUtf8(encoded, pos, i);
percentDecode(out, encoded, i, limit, plusIsSpace);
return out.readUtf8();
}
}
// Fast path: no characters in [pos..limit) required decoding.
return encoded.substring(pos, limit);
}
内容来源于网络,如有侵权,请联系作者删除!