libnmdc: use extra variable instead of reflect package

This commit is contained in:
mappu 2016-04-03 13:22:09 +12:00
parent da92afa51e
commit 27c21572b3

View File

@ -7,7 +7,6 @@ import (
"fmt" "fmt"
"net" "net"
"net/url" "net/url"
"reflect"
"regexp" "regexp"
"strings" "strings"
"time" "time"
@ -97,20 +96,10 @@ type HubConnection struct {
// Private state // Private state
conn net.Conn // this is an interface conn net.Conn // this is an interface
connValid bool
sentOurHello bool sentOurHello bool
} }
func isNil(a interface{}) bool {
// Workaround to catch the potential for storing nil in an interface.
// @ref http://stackoverflow.com/q/13476349
defer func() { recover() }()
return a == nil || reflect.ValueOf(a).IsNil()
}
func (this *HubConnection) isConnValid() bool {
return isNil(this.conn)
}
type HubEvent struct { type HubEvent struct {
EventType HubEventType EventType HubEventType
Nick string Nick string
@ -174,7 +163,7 @@ func (this *HubConnection) userJoined_Full(uinf *UserInfo) {
// Note that protocol messages are transmitted on the caller thread, not from // Note that protocol messages are transmitted on the caller thread, not from
// any internal libnmdc thread. // any internal libnmdc thread.
func (this *HubConnection) SayRaw(protocolCommand string) error { func (this *HubConnection) SayRaw(protocolCommand string) error {
if this.isConnValid() { if this.connValid {
_, err := this.conn.Write([]byte(protocolCommand)) _, err := this.conn.Write([]byte(protocolCommand))
return err return err
} else { } else {
@ -354,12 +343,14 @@ func (this *HubConnection) worker() {
if err == nil { if err == nil {
this.OnEvent <- HubEvent{EventType: EVENT_CONNECTION_STATE_CHANGED, StateChange: CONNECTIONSTATE_CONNECTING} this.OnEvent <- HubEvent{EventType: EVENT_CONNECTION_STATE_CHANGED, StateChange: CONNECTIONSTATE_CONNECTING}
this.conn = nil // WARNING: storing nil in an interface(!) this.connValid = false
} else {
this.connValid = true
} }
} }
// Read from socket into our local buffer (blocking) // Read from socket into our local buffer (blocking)
if this.isConnValid() { if this.connValid {
readBuff := make([]byte, 4096) readBuff := make([]byte, 4096)
nbytes, err = this.conn.Read(readBuff) nbytes, err = this.conn.Read(readBuff)
if nbytes > 0 { if nbytes > 0 {