github.com/lirm/aeron-go@v0.0.0-20230415210743-920325491dc4/aeron/broadcast/copyreceiver.go (about) 1 /* 2 Copyright 2016 Stanislav Liberman 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package broadcast 18 19 import ( 20 "fmt" 21 22 "github.com/lirm/aeron-go/aeron/atomic" 23 ) 24 25 type Handler func(int32, *atomic.Buffer, int32, int32) 26 27 type CopyReceiver struct { 28 receiver *Receiver 29 scratchBuffer *atomic.Buffer 30 } 31 32 func NewCopyReceiver(receiver *Receiver) *CopyReceiver { 33 bcast := new(CopyReceiver) 34 bcast.receiver = receiver 35 bcast.scratchBuffer = atomic.MakeBuffer(make([]byte, 4096)) 36 37 // Scroll to the latest unprocessed 38 for bcast.receiver.receiveNext() { 39 } 40 return bcast 41 } 42 43 func (bcast *CopyReceiver) Receive(handler Handler) int { 44 messagesReceived := 0 45 lastSeenLappedCount := bcast.receiver.GetLappedCount() 46 47 if bcast.receiver.receiveNext() { 48 if lastSeenLappedCount != bcast.receiver.GetLappedCount() { 49 panic("Unable to keep up with broadcast buffer") 50 } 51 52 length := bcast.receiver.length() 53 if length > bcast.scratchBuffer.Capacity() { 54 panic(fmt.Sprintf("Buffer required size %d but only has %d", length, bcast.scratchBuffer.Capacity())) 55 } 56 57 msgTypeID := bcast.receiver.typeID() 58 bcast.scratchBuffer.PutBytes(0, bcast.receiver.buffer, bcast.receiver.offset(), length) 59 60 if !bcast.receiver.Validate() { 61 panic("Unable to keep up with broadcast buffer") 62 } 63 64 handler(msgTypeID, bcast.scratchBuffer, 0, length) 65 66 messagesReceived = 1 67 } 68 69 return messagesReceived 70 }