WriteTo writes a single packet to the buffer. The supplied address will remain associated with the packet.
(pkt []byte, addr net.Addr)
| 69 | // WriteTo writes a single packet to the buffer. The supplied address will |
| 70 | // remain associated with the packet. |
| 71 | func (b *PacketBuffer) WriteTo(pkt []byte, addr net.Addr) (int, error) { |
| 72 | b.mutex.Lock() |
| 73 | |
| 74 | if b.closed { |
| 75 | b.mutex.Unlock() |
| 76 | |
| 77 | return 0, io.ErrClosedPipe |
| 78 | } |
| 79 | |
| 80 | var notify chan struct{} |
| 81 | if b.notify != nil { |
| 82 | notify = b.notify |
| 83 | b.notify = nil |
| 84 | } |
| 85 | |
| 86 | // Check to see if we are full. |
| 87 | if b.full { |
| 88 | // If so, grow AddrPacket buffer. |
| 89 | var newSize int |
| 90 | if len(b.packets) < 128 { |
| 91 | // Double the number of packets. |
| 92 | newSize = len(b.packets) * 2 |
| 93 | } else { |
| 94 | // Increase the number of packets by 25%. |
| 95 | newSize = 5 * len(b.packets) / 4 |
| 96 | } |
| 97 | newBuf := make([]AddrPacket, newSize) |
| 98 | var n int |
| 99 | if b.read < b.write { |
| 100 | n = copy(newBuf, b.packets[b.read:b.write]) |
| 101 | } else { |
| 102 | n = copy(newBuf, b.packets[b.read:]) |
| 103 | n += copy(newBuf[n:], b.packets[:b.write]) |
| 104 | } |
| 105 | |
| 106 | b.packets = newBuf |
| 107 | |
| 108 | // Update read/write pointers and mark buffer as not full. |
| 109 | b.read = 0 |
| 110 | b.write = n |
| 111 | b.full = false |
| 112 | } |
| 113 | |
| 114 | // Store the packet at the write pointer. |
| 115 | packet := &b.packets[b.write] |
| 116 | packet.data.Reset() |
| 117 | n, err := packet.data.Write(pkt) |
| 118 | if err != nil { |
| 119 | b.mutex.Unlock() |
| 120 | |
| 121 | return n, err |
| 122 | } |
| 123 | packet.addr = addr |
| 124 | |
| 125 | // Increment write pointer. |
| 126 | b.write++ |
| 127 | |
| 128 | // If the write pointer is equal to the length of the buffer, wrap around. |