Official cwtch.im peer and server implementations. https://cwtch.im
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.1KB

  1. package bridge
  2. import (
  3. "cwtch.im/cwtch/event"
  4. "sync"
  5. )
  6. type goChanBridge struct {
  7. in chan event.IPCMessage
  8. out chan event.IPCMessage
  9. closedChan chan bool
  10. closed bool
  11. lock sync.Mutex
  12. }
  13. // MakeGoChanBridge returns a simple testing IPCBridge made from inprocess go channels
  14. func MakeGoChanBridge() (b1, b2 event.IPCBridge) {
  15. chan1 := make(chan event.IPCMessage)
  16. chan2 := make(chan event.IPCMessage)
  17. closed := make(chan bool)
  18. a := &goChanBridge{in: chan1, out: chan2, closedChan: closed, closed: false}
  19. b := &goChanBridge{in: chan2, out: chan1, closedChan: closed, closed: false}
  20. go monitor(a, b)
  21. return a, b
  22. }
  23. func monitor(a, b *goChanBridge) {
  24. <-a.closedChan
  25. a.closed = true
  26. b.closed = true
  27. a.closedChan <- true
  28. }
  29. func (pb *goChanBridge) Read() (*event.IPCMessage, bool) {
  30. message, ok := <-pb.in
  31. return &message, ok
  32. }
  33. func (pb *goChanBridge) Write(message *event.IPCMessage) {
  34. pb.lock.Lock()
  35. defer pb.lock.Unlock()
  36. if !pb.closed {
  37. pb.out <- *message
  38. }
  39. }
  40. func (pb *goChanBridge) Shutdown() {
  41. if !pb.closed {
  42. close(pb.in)
  43. close(pb.out)
  44. pb.closedChan <- true
  45. <-pb.closedChan
  46. }
  47. }