package pnyx import ( "slices" ) type ChannelID uint32 const ( RootChannelID ChannelID = 0 MODE_RAW ModeID = iota MODE_COMMAND_DATA byte = 0x00 MODE_COMMAND_JOIN = 0x01 MODE_COMMAND_LEAVE = 0x02 ) type ModeID uint8 type CommandID uint8 type Channel struct { modes map[ModeID]Mode } type SendPacket struct { Packet *Packet Session SessionID } type Mode interface { // Process takes incoming packets from a session and returns a list of packets to send Process(*Session, *Packet) []SendPacket } func multiplex(session *Session, packet *Packet, sessions []SessionID) []SendPacket { send_packets := make([]SendPacket, len(sessions)) for i, session_id := range(sessions) { if session_id == session.ID { continue } send_packets[i] = SendPacket{ Packet: packet, Session: session_id, } } return send_packets } type RawMode struct { Sessions []SessionID } func(mode *RawMode) Process(session *Session, packet *Packet) []SendPacket { switch packet.Command { case MODE_COMMAND_JOIN: if slices.Contains(mode.Sessions, session.ID) == false { mode.Sessions = append(mode.Sessions, session.ID) } case MODE_COMMAND_LEAVE: idx := slices.Index(mode.Sessions, session.ID) if idx != -1 { mode.Sessions = slices.Delete(mode.Sessions, idx, idx+1) } case MODE_COMMAND_DATA: if slices.Contains(mode.Sessions, session.ID) { new_packet := &Packet{ Channel: packet.Channel, Mode: packet.Mode, Command: MODE_COMMAND_DATA, Data: append(session.Peer[:], packet.Data...), } return multiplex(session, new_packet, mode.Sessions) } } return nil }