-
-
Notifications
You must be signed in to change notification settings - Fork 1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
bebop: fix concurrent map writes (#1063)
- Loading branch information
1 parent
cb1f952
commit 244f699
Showing
2 changed files
with
100 additions
and
81 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
package client | ||
|
||
import ( | ||
"bytes" | ||
"encoding/binary" | ||
"sync" | ||
) | ||
|
||
type nwFrameGenerator struct { | ||
seq map[byte]byte | ||
hlen int | ||
mutex *sync.Mutex | ||
} | ||
|
||
func newNetworkFrameGenerator() *nwFrameGenerator { | ||
nwg := nwFrameGenerator{ | ||
seq: make(map[byte]byte), // each frame id has it's own sequence number | ||
hlen: 7, // size of ARNETWORKAL_Frame_t header | ||
mutex: &sync.Mutex{}, | ||
} | ||
return &nwg | ||
} | ||
|
||
// generate the "NetworkFrame" as bytes buffer | ||
func (nwg *nwFrameGenerator) generate(cmd *bytes.Buffer, frameType byte, id byte) *bytes.Buffer { | ||
nwg.mutex.Lock() | ||
defer nwg.mutex.Unlock() | ||
|
||
// func networkFrameGenerator() func(*bytes.Buffer, byte, byte) NetworkFrame { | ||
// | ||
// ARNETWORKAL_Frame_t | ||
// | ||
// uint8 type - frame type ARNETWORK_FRAME_TYPE | ||
// uint8 id - identifier of the buffer sending the frame | ||
// uint8 seq - sequence number of the frame | ||
// uint32 size - size of the frame | ||
// | ||
|
||
if _, ok := nwg.seq[id]; !ok { | ||
nwg.seq[id] = 0 | ||
} | ||
|
||
nwg.seq[id]++ | ||
|
||
if nwg.seq[id] > 255 { | ||
nwg.seq[id] = 0 | ||
} | ||
|
||
ret := &bytes.Buffer{} | ||
ret.WriteByte(frameType) | ||
ret.WriteByte(id) | ||
ret.WriteByte(nwg.seq[id]) | ||
|
||
size := &bytes.Buffer{} | ||
if err := binary.Write(size, binary.LittleEndian, uint32(cmd.Len()+nwg.hlen)); err != nil { | ||
panic(err) | ||
} | ||
|
||
ret.Write(size.Bytes()) | ||
ret.Write(cmd.Bytes()) | ||
|
||
return ret | ||
} |