loadHeaderBytes优化

This commit is contained in:
redkale
2024-09-29 22:47:28 +08:00
parent 0b10009d5e
commit fbe2a01519
2 changed files with 28 additions and 63 deletions

View File

@@ -568,72 +568,27 @@ public class HttpRequest extends Request<HttpContext> {
private int loadHeaderBytes(final ByteBuffer buf) { private int loadHeaderBytes(final ByteBuffer buf) {
final ByteBuffer buffer = buf; final ByteBuffer buffer = buf;
ByteArray hbytes = this.headerBytes; final ByteArray hbytes = this.headerBytes;
int remain = buffer.remaining(); int remain = buffer.remaining();
byte b1, b2, b3, b4; final byte[] content = hbytes.expand(remain);
for (; ; ) { int pos = hbytes.length();
if (remain-- < 4) { // bytes不存放\r\n\r\n这4个字节 int rs = 1;
hbytes.put(buffer); while (remain-- > 0) {
buffer.clear(); byte b = buffer.get();
if (hbytes.length() > 0) { content[pos++] = b;
byte rn1 = 0, rn2 = 0, rn3 = 0; if (b == '\n'
byte b = hbytes.getLastByte(); && pos > 3
if (b == '\r' || b == '\n') { && content[pos - 2] == '\r'
rn3 = b; && content[pos - 3] == '\n'
hbytes.backCount(); && content[pos - 4] == '\r') {
if (hbytes.length() > 0) { rs = 0;
b = hbytes.getLastByte(); break;
if (b == '\r' || b == '\n') {
rn2 = b;
hbytes.backCount();
if (hbytes.length() > 0) {
b = hbytes.getLastByte();
if (b == '\r' || b == '\n') {
rn1 = b;
hbytes.backCount();
}
}
}
}
}
if (rn1 != 0) {
buffer.put(rn1);
}
if (rn2 != 0) {
buffer.put(rn2);
}
if (rn3 != 0) {
buffer.put(rn3);
}
}
this.headerHalfLen = hbytes.length();
return 1;
}
b1 = buffer.get();
hbytes.put(b1);
if (b1 == '\r') {
remain--;
b2 = buffer.get();
if (b2 == '\n') {
remain--;
b3 = buffer.get();
if (b3 == '\r') {
remain--;
b4 = buffer.get();
hbytes.put(b2, b3, b4);
if (b4 == '\n') {
this.headerLength = hbytes.length();
this.headerHalfLen = this.headerLength;
return 0;
}
} else {
hbytes.put(b2, b3);
}
} else {
hbytes.put(b2);
}
} }
} }
hbytes.position(pos);
this.headerLength = hbytes.length();
this.headerHalfLen = this.headerLength;
return rs;
} }
// 解析 GET /xxx HTTP/1.1 // 解析 GET /xxx HTTP/1.1

View File

@@ -76,6 +76,16 @@ public final class ByteArray implements ByteTuple {
return true; return true;
} }
public byte[] expand(int len) {
int newcount = count + len;
if (newcount > content.length) {
byte[] newdata = new byte[newcount];
System.arraycopy(content, 0, newdata, 0, count);
this.content = newdata;
}
return content;
}
public ByteBuffer wrapByteBuffer() { public ByteBuffer wrapByteBuffer() {
return ByteBuffer.wrap(content, 0, count); return ByteBuffer.wrap(content, 0, count);
} }