mirror of
https://github.com/zgwit/beeq.git
synced 2025-09-28 04:22:06 +08:00
翻出历史项目,先上传,未测试(MQTT3.1.1已经支持)
This commit is contained in:
70
topic.go
Normal file
70
topic.go
Normal file
@@ -0,0 +1,70 @@
|
||||
package beeq
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func ValidTopic(topic []byte) error {
|
||||
//no + #
|
||||
if bytes.ContainsAny(topic, "+#") {
|
||||
return fmt.Errorf("+ # is not valid (%s)", string(topic))
|
||||
}
|
||||
//no //
|
||||
if bytes.Contains(topic, []byte("//")) {
|
||||
return fmt.Errorf("// is not valid (%s)", string(topic))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidSubscribe(topic []byte) error {
|
||||
if len(topic) == 0 {
|
||||
return errors.New("Blank topic")
|
||||
}
|
||||
topics := bytes.Split(topic, []byte("/"))
|
||||
if len(topics[0]) == 0 {
|
||||
topics[0] = []byte("/")
|
||||
}
|
||||
for i, tt := range topics {
|
||||
l := len(tt)
|
||||
if l == 0 {
|
||||
return errors.New("inner blank")
|
||||
}
|
||||
if l == 1 && tt[0] == '#' && i < len(topics)-1 {
|
||||
return errors.New("# must be the last one")
|
||||
}
|
||||
if l > 1 && bytes.ContainsAny(tt, "+#") {
|
||||
return errors.New("+ # is alone")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func MatchSubscribe(topic []byte, sub []byte) bool {
|
||||
i, j := 0, 0
|
||||
for i < len(topic) && j < len(sub) {
|
||||
t, s := topic[i], sub[j]
|
||||
if s == '#' {
|
||||
return true
|
||||
} else if s == '+' {
|
||||
for t != '/' {
|
||||
i++
|
||||
t = topic[i]
|
||||
}
|
||||
j++ // skip /
|
||||
} else if s != t {
|
||||
break
|
||||
}
|
||||
// else s==t
|
||||
i++
|
||||
j++
|
||||
}
|
||||
|
||||
//Just match
|
||||
if i == len(topic) && j == len(sub) {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
Reference in New Issue
Block a user