mirror of
https://github.com/MetaCubeX/mihomo.git
synced 2026-12-02 15:16:47 +00:00
chore: optimize sudoku packed hot paths (#2833)
This commit is contained in:
1 parent
5639e93f72
commit
5b28a0ee46
10 files changed
+250
-91
No files matched your search
@@ -122,39 +122,40 @@ func runPackedTCPSession(id int, cfg *ProtocolConfig, errCh chan<- error) {
|
||||
target := fmt.Sprintf("1.1.1.%d:80", (id%200)+1)
|
||||
payload := []byte{0x42, byte(id)}
|
||||
|
||||
// Server side
|
||||
serverErr := make(chan error, 1)
|
||||
go func() {
|
||||
c, meta, err := ServerHandshake(serverConn, cfg)
|
||||
if err != nil {
|
||||
errCh <- fmt.Errorf("server handshake tcp: %w", err)
|
||||
serverErr <- fmt.Errorf("server handshake tcp: %w", err)
|
||||
return
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
session, err := ReadServerSession(c, meta)
|
||||
if err != nil {
|
||||
errCh <- fmt.Errorf("server read session tcp: %w", err)
|
||||
serverErr <- fmt.Errorf("server read session tcp: %w", err)
|
||||
return
|
||||
}
|
||||
if session.Type != SessionTypeTCP {
|
||||
errCh <- fmt.Errorf("unexpected session type: %v", session.Type)
|
||||
serverErr <- fmt.Errorf("unexpected session type: %v", session.Type)
|
||||
return
|
||||
}
|
||||
if session.Target != target {
|
||||
errCh <- fmt.Errorf("target mismatch want %s got %s", target, session.Target)
|
||||
serverErr <- fmt.Errorf("target mismatch want %s got %s", target, session.Target)
|
||||
return
|
||||
}
|
||||
if _, err := session.Conn.Write(payload); err != nil {
|
||||
errCh <- fmt.Errorf("server write: %w", err)
|
||||
serverErr <- fmt.Errorf("server write: %w", err)
|
||||
return
|
||||
}
|
||||
serverErr <- nil
|
||||
}()
|
||||
|
||||
// Client side
|
||||
clientCfg := *cfg
|
||||
cConn, err := ClientHandshake(clientConn, &clientCfg)
|
||||
if err != nil {
|
||||
errCh <- fmt.Errorf("client handshake tcp: %w", err)
|
||||
_ = clientConn.Close()
|
||||
return
|
||||
}
|
||||
defer cConn.Close()
|
||||
@@ -178,6 +179,7 @@ func runPackedTCPSession(id int, cfg *ProtocolConfig, errCh chan<- error) {
|
||||
errCh <- fmt.Errorf("payload mismatch want %x got %x", payload, buf)
|
||||
return
|
||||
}
|
||||
reportPackedServerErr(serverErr, errCh)
|
||||
}
|
||||
|
||||
func runPackedUoTSession(id int, cfg *ProtocolConfig, errCh chan<- error) {
|
||||
@@ -185,35 +187,36 @@ func runPackedUoTSession(id int, cfg *ProtocolConfig, errCh chan<- error) {
|
||||
target := "8.8.8.8:53"
|
||||
payload := []byte{0xaa, byte(id)}
|
||||
|
||||
// Server side
|
||||
serverErr := make(chan error, 1)
|
||||
go func() {
|
||||
c, meta, err := ServerHandshake(serverConn, cfg)
|
||||
if err != nil {
|
||||
errCh <- fmt.Errorf("server handshake uot: %w", err)
|
||||
serverErr <- fmt.Errorf("server handshake uot: %w", err)
|
||||
return
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
session, err := ReadServerSession(c, meta)
|
||||
if err != nil {
|
||||
errCh <- fmt.Errorf("server read session uot: %w", err)
|
||||
serverErr <- fmt.Errorf("server read session uot: %w", err)
|
||||
return
|
||||
}
|
||||
if session.Type != SessionTypeUoT {
|
||||
errCh <- fmt.Errorf("unexpected session type: %v", session.Type)
|
||||
serverErr <- fmt.Errorf("unexpected session type: %v", session.Type)
|
||||
return
|
||||
}
|
||||
if err := WriteDatagram(session.Conn, target, payload); err != nil {
|
||||
errCh <- fmt.Errorf("server write datagram: %w", err)
|
||||
serverErr <- fmt.Errorf("server write datagram: %w", err)
|
||||
return
|
||||
}
|
||||
serverErr <- nil
|
||||
}()
|
||||
|
||||
// Client side
|
||||
clientCfg := *cfg
|
||||
cConn, err := ClientHandshake(clientConn, &clientCfg)
|
||||
if err != nil {
|
||||
errCh <- fmt.Errorf("client handshake uot: %w", err)
|
||||
_ = clientConn.Close()
|
||||
return
|
||||
}
|
||||
defer cConn.Close()
|
||||
@@ -236,6 +239,17 @@ func runPackedUoTSession(id int, cfg *ProtocolConfig, errCh chan<- error) {
|
||||
errCh <- fmt.Errorf("uot payload mismatch want %x got %x", payload, data)
|
||||
return
|
||||
}
|
||||
reportPackedServerErr(serverErr, errCh)
|
||||
}
|
||||
|
||||
func reportPackedServerErr(serverErr <-chan error, errCh chan<- error) {
|
||||
select {
|
||||
case err := <-serverErr:
|
||||
if err != nil {
|
||||
errCh <- err
|
||||
}
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func TestCustomTableHandshake(t *testing.T) {
|
||||
|
||||
@@ -244,7 +244,7 @@ type httpClientTarget struct {
|
||||
|
||||
func buildHTTPTransport(serverAddress string, tlsEnabled bool, hostOverride string, dialContext func(ctx context.Context, network, addr string) (net.Conn, error), maxIdleConns int) (*http.Transport, httpClientTarget, error) {
|
||||
if dialContext == nil {
|
||||
panic("httpmask: DialContext is nil")
|
||||
return nil, httpClientTarget{}, errors.New("httpmask: DialContext is nil")
|
||||
}
|
||||
|
||||
scheme, urlHost, dialAddr, serverName, err := normalizeHTTPDialTarget(serverAddress, tlsEnabled, hostOverride)
|
||||
|
||||
@@ -3,6 +3,7 @@ package httpmask
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
mrand "math/rand"
|
||||
@@ -96,7 +97,7 @@ func applyWSHeaders(h stdhttp.Header, host string) {
|
||||
|
||||
func dialWS(ctx context.Context, serverAddress string, opts TunnelDialOptions) (net.Conn, error) {
|
||||
if opts.DialContext == nil {
|
||||
panic("httpmask: DialContext is nil")
|
||||
return nil, errors.New("httpmask: DialContext is nil")
|
||||
}
|
||||
|
||||
scheme, urlHost, dialAddr, serverName, err := normalizeWSDialTarget(serverAddress, opts.TLSEnabled, opts.HostOverride)
|
||||
|
||||
@@ -3,6 +3,7 @@ package sudoku
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
@@ -10,6 +11,8 @@ import (
|
||||
|
||||
const IOBufferSize = 32 * 1024
|
||||
|
||||
const minDecodeReadSize = 64
|
||||
|
||||
var perm4 = [24][4]byte{
|
||||
{0, 1, 2, 3},
|
||||
{0, 1, 3, 2},
|
||||
@@ -52,7 +55,7 @@ type Conn struct {
|
||||
writeMu sync.Mutex
|
||||
writeBuf []byte
|
||||
|
||||
rng randomSource
|
||||
rng *sudokuRand
|
||||
paddingThreshold uint64
|
||||
}
|
||||
|
||||
@@ -97,6 +100,9 @@ func NewConn(c net.Conn, table *Table, pMin, pMax int, record bool) *Conn {
|
||||
}
|
||||
|
||||
func (sc *Conn) StopRecording() {
|
||||
if sc == nil {
|
||||
return
|
||||
}
|
||||
sc.recordLock.Lock()
|
||||
sc.recording.Store(false)
|
||||
sc.recorder = nil
|
||||
@@ -115,6 +121,9 @@ func (sc *Conn) GetBufferedAndRecorded() []byte {
|
||||
if sc.recorder != nil {
|
||||
recorded = sc.recorder.Bytes()
|
||||
}
|
||||
if sc.reader == nil {
|
||||
return recorded
|
||||
}
|
||||
|
||||
buffered := sc.reader.Buffered()
|
||||
if buffered > 0 {
|
||||
@@ -131,6 +140,9 @@ func (sc *Conn) Write(p []byte) (n int, err error) {
|
||||
if len(p) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
if sc == nil || sc.Conn == nil || sc.table == nil || sc.table.layout == nil || sc.rng == nil {
|
||||
return 0, io.ErrClosedPipe
|
||||
}
|
||||
|
||||
sc.writeMu.Lock()
|
||||
defer sc.writeMu.Unlock()
|
||||
@@ -140,16 +152,19 @@ func (sc *Conn) Write(p []byte) (n int, err error) {
|
||||
}
|
||||
|
||||
func (sc *Conn) Read(p []byte) (n int, err error) {
|
||||
if len(p) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
if sc == nil || sc.Conn == nil || sc.reader == nil || len(sc.rawBuf) == 0 || sc.table == nil || sc.table.layout == nil {
|
||||
return 0, io.ErrClosedPipe
|
||||
}
|
||||
if n, ok := drainPending(p, &sc.pendingData); ok {
|
||||
return n, nil
|
||||
}
|
||||
|
||||
outN := 0
|
||||
for {
|
||||
if sc.pendingData.available() > 0 {
|
||||
break
|
||||
}
|
||||
|
||||
nr, rErr := sc.reader.Read(sc.rawBuf)
|
||||
nr, rErr := readRawLimited(sc.Conn, sc.reader, sc.rawBuf[:sudokuReadSize(len(p)-outN, len(sc.rawBuf))])
|
||||
if nr > 0 {
|
||||
chunk := sc.rawBuf[:nr]
|
||||
if sc.recording.Load() {
|
||||
@@ -174,20 +189,47 @@ func (sc *Conn) Read(p []byte) (n int, err error) {
|
||||
if !ok {
|
||||
return 0, ErrInvalidSudokuMapMiss
|
||||
}
|
||||
sc.pendingData.appendByte(val)
|
||||
outN = appendDecodedByte(p, outN, &sc.pendingData, val)
|
||||
sc.hintCount = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if rErr != nil {
|
||||
if outN > 0 {
|
||||
return outN, nil
|
||||
}
|
||||
if n, ok := drainPending(p, &sc.pendingData); ok {
|
||||
return n, nil
|
||||
}
|
||||
return 0, rErr
|
||||
}
|
||||
if sc.pendingData.available() > 0 {
|
||||
break
|
||||
if outN > 0 {
|
||||
return outN, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
n, _ = drainPending(p, &sc.pendingData)
|
||||
return n, nil
|
||||
func sudokuReadSize(decodedRemaining, maxRaw int) int {
|
||||
if maxRaw <= minDecodeReadSize || decodedRemaining <= 0 {
|
||||
return maxRaw
|
||||
}
|
||||
if decodedRemaining > (maxRaw-minDecodeReadSize)/5 {
|
||||
return maxRaw
|
||||
}
|
||||
|
||||
return decodedRemaining*5 + minDecodeReadSize
|
||||
}
|
||||
|
||||
func readRawLimited(conn net.Conn, reader *bufio.Reader, dst []byte) (int, error) {
|
||||
if len(dst) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
if reader != nil && reader.Buffered() > 0 {
|
||||
return reader.Read(dst)
|
||||
}
|
||||
if conn == nil {
|
||||
return 0, io.ErrClosedPipe
|
||||
}
|
||||
return conn.Read(dst)
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
package sudoku
|
||||
|
||||
func encodeSudokuPayload(dst []byte, table *Table, rng randomSource, paddingThreshold uint64, p []byte) []byte {
|
||||
func encodeSudokuPayload(dst []byte, table *Table, rng *sudokuRand, paddingThreshold uint64, p []byte) []byte {
|
||||
if len(p) == 0 {
|
||||
return dst[:0]
|
||||
}
|
||||
if paddingThreshold == 0 {
|
||||
return encodeSudokuPayloadNoPadding(dst, table, rng, p)
|
||||
}
|
||||
|
||||
outCapacity := len(p)*6 + 1
|
||||
if cap(dst) < outCapacity {
|
||||
@@ -34,3 +37,19 @@ func encodeSudokuPayload(dst []byte, table *Table, rng randomSource, paddingThre
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func encodeSudokuPayloadNoPadding(dst []byte, table *Table, rng *sudokuRand, p []byte) []byte {
|
||||
outCapacity := len(p) * 4
|
||||
if cap(dst) < outCapacity {
|
||||
dst = make([]byte, 0, outCapacity)
|
||||
}
|
||||
out := dst[:0]
|
||||
|
||||
for _, b := range p {
|
||||
puzzles := table.EncodeTable[b]
|
||||
puzzle := puzzles[rng.Intn(len(puzzles))]
|
||||
perm := perm4[rng.Intn(len(perm4))]
|
||||
out = append(out, puzzle[perm[0]], puzzle[perm[1]], puzzle[perm[2]], puzzle[perm[3]])
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -8,9 +8,9 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
RngBatchSize = 128
|
||||
|
||||
packedProtectedPrefixBytes = 14
|
||||
packedIOBufferSize = 64 * 1024
|
||||
packedDecodeBufferSize = 96 * 1024
|
||||
)
|
||||
|
||||
// PackedConn encodes traffic with the packed Sudoku layout while preserving
|
||||
@@ -35,7 +35,7 @@ type PackedConn struct {
|
||||
readBits int
|
||||
|
||||
// Padding selection matches Conn's threshold-based model.
|
||||
rng randomSource
|
||||
rng *sudokuRand
|
||||
paddingThreshold uint64
|
||||
padMarker byte
|
||||
padPool []byte
|
||||
@@ -67,18 +67,20 @@ func NewPackedConn(c net.Conn, table *Table, pMin, pMax int) *PackedConn {
|
||||
pc := &PackedConn{
|
||||
Conn: c,
|
||||
table: table,
|
||||
reader: bufio.NewReaderSize(c, IOBufferSize),
|
||||
rawBuf: make([]byte, IOBufferSize),
|
||||
reader: bufio.NewReaderSize(c, packedIOBufferSize),
|
||||
rawBuf: make([]byte, packedDecodeBufferSize),
|
||||
pendingData: newPendingBuffer(4096),
|
||||
writeBuf: make([]byte, 0, 4096),
|
||||
rng: localRng,
|
||||
paddingThreshold: pickPaddingThreshold(localRng, pMin, pMax),
|
||||
}
|
||||
|
||||
pc.padMarker = table.layout.padMarker
|
||||
for _, b := range table.PaddingPool {
|
||||
if b != pc.padMarker {
|
||||
pc.padPool = append(pc.padPool, b)
|
||||
if table != nil && table.layout != nil {
|
||||
pc.padMarker = table.layout.padMarker
|
||||
for _, b := range table.PaddingPool {
|
||||
if b != pc.padMarker {
|
||||
pc.padPool = append(pc.padPool, b)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(pc.padPool) == 0 {
|
||||
@@ -87,18 +89,6 @@ func NewPackedConn(c net.Conn, table *Table, pMin, pMax int) *PackedConn {
|
||||
return pc
|
||||
}
|
||||
|
||||
func (pc *PackedConn) maybeAddPadding(out []byte) []byte {
|
||||
if shouldPad(pc.rng, pc.paddingThreshold) {
|
||||
out = append(out, pc.getPaddingByte())
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (pc *PackedConn) appendGroup(out []byte, group byte) []byte {
|
||||
out = pc.maybeAddPadding(out)
|
||||
return append(out, pc.table.layout.groupByte(group))
|
||||
}
|
||||
|
||||
func (pc *PackedConn) appendForcedPadding(out []byte) []byte {
|
||||
return append(out, pc.getPaddingByte())
|
||||
}
|
||||
@@ -134,7 +124,7 @@ func (pc *PackedConn) writeProtectedPrefix(out []byte, p []byte) ([]byte, int) {
|
||||
} else {
|
||||
pc.bitBuf &= (1 << pc.bitCount) - 1
|
||||
}
|
||||
out = pc.appendGroup(out, group&0x3F)
|
||||
out = appendPackedGroup(out, pc.table.layout, pc.rng, pc.paddingThreshold, pc.padPool, group)
|
||||
}
|
||||
|
||||
effective++
|
||||
@@ -148,19 +138,49 @@ func (pc *PackedConn) writeProtectedPrefix(out []byte, p []byte) ([]byte, int) {
|
||||
return out, limit
|
||||
}
|
||||
|
||||
func appendPackedGroup(out []byte, layout *byteLayout, rng *sudokuRand, paddingThreshold uint64, padPool []byte, group byte) []byte {
|
||||
if paddingThreshold != 0 {
|
||||
u := rng.Uint32()
|
||||
if uint64(u) < paddingThreshold {
|
||||
out = append(out, padPool[fastIntnFromUint32(rng.Uint32(), len(padPool))])
|
||||
}
|
||||
}
|
||||
return append(out, layout.encodeGroup[group&0x3F])
|
||||
}
|
||||
|
||||
func maybeAppendPackedPadding(out []byte, rng *sudokuRand, paddingThreshold uint64, padPool []byte) []byte {
|
||||
if paddingThreshold != 0 {
|
||||
u := rng.Uint32()
|
||||
if uint64(u) < paddingThreshold {
|
||||
out = append(out, padPool[fastIntnFromUint32(rng.Uint32(), len(padPool))])
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (pc *PackedConn) Write(p []byte) (int, error) {
|
||||
if len(p) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
if pc == nil || pc.Conn == nil || pc.table == nil || pc.table.layout == nil || pc.rng == nil || len(pc.padPool) == 0 {
|
||||
return 0, io.ErrClosedPipe
|
||||
}
|
||||
|
||||
pc.writeMu.Lock()
|
||||
defer pc.writeMu.Unlock()
|
||||
|
||||
needed := len(p)*3/2 + 32
|
||||
if pc.paddingThreshold == 0 {
|
||||
needed = ((len(p)+2)/3)*4 + 32
|
||||
}
|
||||
if cap(pc.writeBuf) < needed {
|
||||
pc.writeBuf = make([]byte, 0, needed)
|
||||
}
|
||||
out := pc.writeBuf[:0]
|
||||
layout := pc.table.layout
|
||||
rng := pc.rng
|
||||
paddingThreshold := pc.paddingThreshold
|
||||
padPool := pc.padPool
|
||||
|
||||
var prefixN int
|
||||
out, prefixN = pc.writeProtectedPrefix(out, p)
|
||||
@@ -181,7 +201,7 @@ func (pc *PackedConn) Write(p []byte) (int, error) {
|
||||
} else {
|
||||
pc.bitBuf &= (1 << pc.bitCount) - 1
|
||||
}
|
||||
out = pc.appendGroup(out, group&0x3F)
|
||||
out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, group)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,10 +215,10 @@ func (pc *PackedConn) Write(p []byte) (int, error) {
|
||||
g3 := ((b2 & 0x0F) << 2) | ((b3 >> 6) & 0x03)
|
||||
g4 := b3 & 0x3F
|
||||
|
||||
out = pc.appendGroup(out, g1)
|
||||
out = pc.appendGroup(out, g2)
|
||||
out = pc.appendGroup(out, g3)
|
||||
out = pc.appendGroup(out, g4)
|
||||
out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, g1)
|
||||
out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, g2)
|
||||
out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, g3)
|
||||
out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, g4)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -211,10 +231,10 @@ func (pc *PackedConn) Write(p []byte) (int, error) {
|
||||
g3 := ((b2 & 0x0F) << 2) | ((b3 >> 6) & 0x03)
|
||||
g4 := b3 & 0x3F
|
||||
|
||||
out = pc.appendGroup(out, g1)
|
||||
out = pc.appendGroup(out, g2)
|
||||
out = pc.appendGroup(out, g3)
|
||||
out = pc.appendGroup(out, g4)
|
||||
out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, g1)
|
||||
out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, g2)
|
||||
out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, g3)
|
||||
out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, g4)
|
||||
}
|
||||
|
||||
for ; i < n; i++ {
|
||||
@@ -229,7 +249,7 @@ func (pc *PackedConn) Write(p []byte) (int, error) {
|
||||
} else {
|
||||
pc.bitBuf &= (1 << pc.bitCount) - 1
|
||||
}
|
||||
out = pc.appendGroup(out, group&0x3F)
|
||||
out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, group)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -237,11 +257,11 @@ func (pc *PackedConn) Write(p []byte) (int, error) {
|
||||
group := byte(pc.bitBuf << (6 - pc.bitCount))
|
||||
pc.bitBuf = 0
|
||||
pc.bitCount = 0
|
||||
out = pc.appendGroup(out, group&0x3F)
|
||||
out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, group)
|
||||
out = append(out, pc.padMarker)
|
||||
}
|
||||
|
||||
out = pc.maybeAddPadding(out)
|
||||
out = maybeAppendPackedPadding(out, rng, paddingThreshold, padPool)
|
||||
|
||||
if len(out) > 0 {
|
||||
pc.writeBuf = out[:0]
|
||||
@@ -252,6 +272,10 @@ func (pc *PackedConn) Write(p []byte) (int, error) {
|
||||
}
|
||||
|
||||
func (pc *PackedConn) Flush() error {
|
||||
if pc == nil || pc.Conn == nil || pc.table == nil || pc.table.layout == nil || pc.rng == nil || len(pc.padPool) == 0 {
|
||||
return io.ErrClosedPipe
|
||||
}
|
||||
|
||||
pc.writeMu.Lock()
|
||||
defer pc.writeMu.Unlock()
|
||||
|
||||
@@ -265,7 +289,7 @@ func (pc *PackedConn) Flush() error {
|
||||
out = append(out, pc.padMarker)
|
||||
}
|
||||
|
||||
out = pc.maybeAddPadding(out)
|
||||
out = maybeAppendPackedPadding(out, pc.rng, pc.paddingThreshold, pc.padPool)
|
||||
|
||||
if len(out) > 0 {
|
||||
pc.writeBuf = out[:0]
|
||||
@@ -289,19 +313,44 @@ func writeFull(w io.Writer, b []byte) error {
|
||||
}
|
||||
|
||||
func (pc *PackedConn) Read(p []byte) (int, error) {
|
||||
if len(p) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
if pc == nil || pc.Conn == nil || pc.reader == nil || len(pc.rawBuf) == 0 || pc.table == nil || pc.table.layout == nil {
|
||||
return 0, io.ErrClosedPipe
|
||||
}
|
||||
if n, ok := drainPending(p, &pc.pendingData); ok {
|
||||
return n, nil
|
||||
}
|
||||
|
||||
outN := 0
|
||||
for {
|
||||
nr, rErr := pc.reader.Read(pc.rawBuf)
|
||||
nr, rErr := readRawLimited(pc.Conn, pc.reader, pc.rawBuf[:packedReadSize(len(p)-outN, len(pc.rawBuf))])
|
||||
if nr > 0 {
|
||||
rBuf := pc.readBitBuf
|
||||
rBits := pc.readBits
|
||||
padMarker := pc.padMarker
|
||||
layout := pc.table.layout
|
||||
|
||||
for _, b := range pc.rawBuf[:nr] {
|
||||
chunk := pc.rawBuf[:nr]
|
||||
for i := 0; i < len(chunk); {
|
||||
if rBits == 0 && outN+3 <= len(p) && i+3 < len(chunk) &&
|
||||
layout.hintTable[chunk[i]] && layout.hintTable[chunk[i+1]] &&
|
||||
layout.hintTable[chunk[i+2]] && layout.hintTable[chunk[i+3]] {
|
||||
g1 := layout.decodeGroup[chunk[i]]
|
||||
g2 := layout.decodeGroup[chunk[i+1]]
|
||||
g3 := layout.decodeGroup[chunk[i+2]]
|
||||
g4 := layout.decodeGroup[chunk[i+3]]
|
||||
p[outN] = (g1 << 2) | (g2 >> 4)
|
||||
p[outN+1] = (g2 << 4) | (g3 >> 2)
|
||||
p[outN+2] = (g3 << 6) | g4
|
||||
outN += 3
|
||||
i += 4
|
||||
continue
|
||||
}
|
||||
|
||||
b := chunk[i]
|
||||
i++
|
||||
if !layout.hintTable[b] {
|
||||
if b == padMarker {
|
||||
rBuf = 0
|
||||
@@ -321,7 +370,7 @@ func (pc *PackedConn) Read(p []byte) (int, error) {
|
||||
if rBits >= 8 {
|
||||
rBits -= 8
|
||||
val := byte(rBuf >> rBits)
|
||||
pc.pendingData.appendByte(val)
|
||||
outN = appendDecodedByte(p, outN, &pc.pendingData, val)
|
||||
if rBits == 0 {
|
||||
rBuf = 0
|
||||
} else {
|
||||
@@ -339,21 +388,32 @@ func (pc *PackedConn) Read(p []byte) (int, error) {
|
||||
pc.readBitBuf = 0
|
||||
pc.readBits = 0
|
||||
}
|
||||
if pc.pendingData.available() > 0 {
|
||||
break
|
||||
if outN > 0 {
|
||||
return outN, nil
|
||||
}
|
||||
if n, ok := drainPending(p, &pc.pendingData); ok {
|
||||
return n, nil
|
||||
}
|
||||
return 0, rErr
|
||||
}
|
||||
|
||||
if pc.pendingData.available() > 0 {
|
||||
break
|
||||
if outN > 0 {
|
||||
return outN, nil
|
||||
}
|
||||
}
|
||||
|
||||
n, _ := drainPending(p, &pc.pendingData)
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (pc *PackedConn) getPaddingByte() byte {
|
||||
return pc.padPool[pc.rng.Intn(len(pc.padPool))]
|
||||
}
|
||||
|
||||
func packedReadSize(decodedRemaining, maxRaw int) int {
|
||||
if maxRaw <= minDecodeReadSize || decodedRemaining <= 0 {
|
||||
return maxRaw
|
||||
}
|
||||
if decodedRemaining > (maxRaw-minDecodeReadSize)/2 {
|
||||
return maxRaw
|
||||
}
|
||||
|
||||
return decodedRemaining*2 + minDecodeReadSize
|
||||
}
|
||||
@@ -3,7 +3,6 @@ package sudoku
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"math/rand"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -39,7 +38,7 @@ func TestPackedConn_ProtectedPrefixPadding(t *testing.T) {
|
||||
table := NewTable("packed-prefix-seed", "prefer_ascii")
|
||||
mock := &mockConn{}
|
||||
writer := NewPackedConn(mock, table, 0, 0)
|
||||
writer.rng = rand.New(rand.NewSource(1))
|
||||
writer.rng = newSudokuRand(1)
|
||||
|
||||
payload := bytes.Repeat([]byte{0}, 32)
|
||||
if _, err := writer.Write(payload); err != nil {
|
||||
|
||||
@@ -2,7 +2,7 @@ package sudoku
|
||||
|
||||
const probOne = uint64(1) << 32
|
||||
|
||||
func pickPaddingThreshold(r randomSource, pMin, pMax int) uint64 {
|
||||
func pickPaddingThreshold(r *sudokuRand, pMin, pMax int) uint64 {
|
||||
if r == nil {
|
||||
return 0
|
||||
}
|
||||
@@ -28,7 +28,7 @@ func pickPaddingThreshold(r randomSource, pMin, pMax int) uint64 {
|
||||
return min + (u * (max - min) >> 32)
|
||||
}
|
||||
|
||||
func shouldPad(r randomSource, threshold uint64) bool {
|
||||
func shouldPad(r *sudokuRand, threshold uint64) bool {
|
||||
if threshold == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -25,7 +25,10 @@ func (p *pendingBuffer) reset() {
|
||||
}
|
||||
|
||||
func (p *pendingBuffer) ensureAppendCapacity(extra int) {
|
||||
if p == nil || extra <= 0 || p.off == 0 {
|
||||
if p == nil || extra <= 0 {
|
||||
return
|
||||
}
|
||||
if p.off == 0 {
|
||||
return
|
||||
}
|
||||
if cap(p.data)-len(p.data) >= extra {
|
||||
@@ -43,6 +46,15 @@ func (p *pendingBuffer) appendByte(b byte) {
|
||||
p.data = append(p.data, b)
|
||||
}
|
||||
|
||||
func appendDecodedByte(dst []byte, n int, pending *pendingBuffer, b byte) int {
|
||||
if n < len(dst) {
|
||||
dst[n] = b
|
||||
return n + 1
|
||||
}
|
||||
pending.appendByte(b)
|
||||
return n
|
||||
}
|
||||
|
||||
func drainPending(dst []byte, pending *pendingBuffer) (int, bool) {
|
||||
if pending == nil || pending.available() == 0 {
|
||||
return 0, false
|
||||
|
||||
@@ -6,14 +6,10 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type randomSource interface {
|
||||
Uint32() uint32
|
||||
Uint64() uint64
|
||||
Intn(n int) int
|
||||
}
|
||||
|
||||
type sudokuRand struct {
|
||||
state uint64
|
||||
state uint64
|
||||
cached uint32
|
||||
haveCached bool
|
||||
}
|
||||
|
||||
func newSeededRand() *sudokuRand {
|
||||
@@ -37,20 +33,36 @@ func (r *sudokuRand) Uint64() uint64 {
|
||||
if r == nil {
|
||||
return 0
|
||||
}
|
||||
r.state += 0x9e3779b97f4a7c15
|
||||
z := r.state
|
||||
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9
|
||||
z = (z ^ (z >> 27)) * 0x94d049bb133111eb
|
||||
return z ^ (z >> 31)
|
||||
r.haveCached = false
|
||||
x := r.state
|
||||
x ^= x >> 12
|
||||
x ^= x << 25
|
||||
x ^= x >> 27
|
||||
r.state = x
|
||||
return x * 0x2545f4914f6cdd1d
|
||||
}
|
||||
|
||||
func (r *sudokuRand) Uint32() uint32 {
|
||||
return uint32(r.Uint64() >> 32)
|
||||
if r == nil {
|
||||
return 0
|
||||
}
|
||||
if r.haveCached {
|
||||
r.haveCached = false
|
||||
return r.cached
|
||||
}
|
||||
v := r.Uint64()
|
||||
r.cached = uint32(v)
|
||||
r.haveCached = true
|
||||
return uint32(v >> 32)
|
||||
}
|
||||
|
||||
func (r *sudokuRand) Intn(n int) int {
|
||||
if n <= 1 {
|
||||
return 0
|
||||
}
|
||||
return int((uint64(r.Uint32()) * uint64(n)) >> 32)
|
||||
return fastIntnFromUint32(r.Uint32(), n)
|
||||
}
|
||||
|
||||
func fastIntnFromUint32(u uint32, n int) int {
|
||||
return int((uint64(u) * uint64(n)) >> 32)
|
||||
}
|
||||
Reference in new issue
Block a user