cached.go 824 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package net
  2. import (
  3. "net"
  4. "github.com/metacubex/mihomo/common/buf"
  5. )
  6. var _ ExtendedConn = (*CachedConn)(nil)
  7. type CachedConn struct {
  8. ExtendedConn
  9. data []byte
  10. }
  11. func NewCachedConn(c net.Conn, data []byte) *CachedConn {
  12. return &CachedConn{NewExtendedConn(c), data}
  13. }
  14. func (c *CachedConn) Read(b []byte) (n int, err error) {
  15. if len(c.data) > 0 {
  16. n = copy(b, c.data)
  17. c.data = c.data[n:]
  18. return
  19. }
  20. return c.ExtendedConn.Read(b)
  21. }
  22. func (c *CachedConn) ReadCached() *buf.Buffer { // call in sing/common/bufio.Copy
  23. if len(c.data) > 0 {
  24. return buf.As(c.data)
  25. }
  26. return nil
  27. }
  28. func (c *CachedConn) Upstream() any {
  29. return c.ExtendedConn
  30. }
  31. func (c *CachedConn) ReaderReplaceable() bool {
  32. if len(c.data) > 0 {
  33. return false
  34. }
  35. return true
  36. }
  37. func (c *CachedConn) WriterReplaceable() bool {
  38. return true
  39. }