github.com/df-mc/dragonfly@v0.9.13/server/player/chat/chat.go (about) 1 package chat 2 3 import ( 4 "sync" 5 ) 6 7 // Global represents a global chat. Players will write in this chat by default when they send any message in 8 // the chat. 9 var Global = New() 10 11 // Chat represents the in-game chat. Messages may be written to it to send a message to all subscribers. The 12 // zero value of Chat is a chat ready to use. 13 // Methods on Chat may be called from multiple goroutines concurrently. 14 // Chat implements the io.Writer and io.StringWriter interfaces. fmt.Fprintf and fmt.Fprint may be used to write 15 // formatted messages to the chat. 16 type Chat struct { 17 m sync.Mutex 18 subscribers map[Subscriber]struct{} 19 } 20 21 // New returns a new chat. 22 func New() *Chat { 23 return &Chat{subscribers: map[Subscriber]struct{}{}} 24 } 25 26 // Write writes the byte slice p as a string to the chat. It is equivalent to calling 27 // Chat.WriteString(string(p)). 28 func (chat *Chat) Write(p []byte) (n int, err error) { 29 return chat.WriteString(string(p)) 30 } 31 32 // WriteString writes a string s to the chat. 33 func (chat *Chat) WriteString(s string) (n int, err error) { 34 chat.m.Lock() 35 defer chat.m.Unlock() 36 for subscriber := range chat.subscribers { 37 subscriber.Message(s) 38 } 39 return len(s), nil 40 } 41 42 // Subscribe adds a subscriber to the chat, sending it every message written to the chat. In order to remove 43 // it again, use Chat.Unsubscribe(). 44 func (chat *Chat) Subscribe(s Subscriber) { 45 chat.m.Lock() 46 defer chat.m.Unlock() 47 chat.subscribers[s] = struct{}{} 48 } 49 50 // Subscribed checks if a subscriber is currently subscribed to the chat. 51 func (chat *Chat) Subscribed(s Subscriber) bool { 52 chat.m.Lock() 53 defer chat.m.Unlock() 54 _, ok := chat.subscribers[s] 55 return ok 56 } 57 58 // Unsubscribe removes a subscriber from the chat, so that messages written to the chat will no longer be 59 // sent to it. 60 func (chat *Chat) Unsubscribe(s Subscriber) { 61 chat.m.Lock() 62 defer chat.m.Unlock() 63 delete(chat.subscribers, s) 64 } 65 66 // Close closes the chat, removing all subscribers from it. 67 func (chat *Chat) Close() error { 68 chat.m.Lock() 69 chat.subscribers = nil 70 chat.m.Unlock() 71 return nil 72 }