✏️ Diana 插件实装教你一篇小作文

This commit is contained in:
fumiama 2021-09-08 13:45:23 +08:00
parent 4bce4b2dd1
commit 0bffc38be4

View File

@ -2,10 +2,13 @@
package data package data
import ( import (
"crypto/md5"
"io" "io"
"net/http" "net/http"
"os" "os"
"sync"
"time" "time"
"unsafe"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
@ -20,6 +23,10 @@ var (
compo Composition compo Composition
// Array 小作文数组指针 // Array 小作文数组指针
Array = &compo.Array Array = &compo.Array
// m 小作文保存锁
m sync.Mutex
// md5s 验证重复
md5s [][16]byte
) )
func init() { func init() {
@ -31,7 +38,12 @@ func init() {
} }
err1 := LoadText() err1 := LoadText()
if err1 == nil { if err1 == nil {
log.Printf("[Diana]读取%d条小作文", len(*Array)) arrl := len(*Array)
log.Printf("[Diana]读取%d条小作文", arrl)
md5s = make([][16]byte, arrl)
for i, t := range *Array {
md5s[i] = md5.Sum(str2bytes(t))
}
} else { } else {
log.Printf("[Diana]读取小作文错误:%v", err1) log.Printf("[Diana]读取小作文错误:%v", err1)
} }
@ -79,21 +91,47 @@ func LoadText() error {
// AddText 添加小作文 // AddText 添加小作文
func AddText(txt string) error { func AddText(txt string) error {
if txt != "" { sum := md5.Sum(str2bytes(txt))
if txt != "" && !isin(sum) {
compo.Array = append(compo.Array, txt) compo.Array = append(compo.Array, txt)
md5s = append(md5s, sum)
savecompo()
}
return nil
}
func isin(sum [16]byte) bool {
for _, t := range md5s {
if t == sum {
return true
}
}
return false
}
// savecompo 同步保存作文
func savecompo() error {
data, err := compo.Marshal() data, err := compo.Marshal()
if err == nil { if err == nil {
if _, err := os.Stat(datapath); err == nil || os.IsExist(err) { if _, err := os.Stat(datapath); err == nil || os.IsExist(err) {
m.Lock()
defer m.Unlock()
f, err1 := os.OpenFile(pbfile, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644) f, err1 := os.OpenFile(pbfile, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
if err1 == nil { if err1 == nil {
defer f.Close()
_, err2 := f.Write(data) _, err2 := f.Write(data)
f.Close()
return err2 return err2
} }
return err1 return err1
} }
} }
return err return err
} }
return nil
// str2bytes Fast convert
func str2bytes(s string) []byte {
x := (*[2]uintptr)(unsafe.Pointer(&s))
h := [3]uintptr{x[0], x[1], x[1]}
return *(*[]byte)(unsafe.Pointer(&h))
} }