Skip to content

Commit

Permalink
✏️ Diana 插件实装教你一篇小作文
Browse files Browse the repository at this point in the history
  • Loading branch information
fumiama committed Sep 8, 2021
1 parent 4bce4b2 commit 0bffc38
Showing 1 changed file with 52 additions and 14 deletions.
66 changes: 52 additions & 14 deletions plugin_diana/data/text.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@
package data

import (
"crypto/md5"
"io"
"net/http"
"os"
"sync"
"time"
"unsafe"

log "github.com/sirupsen/logrus"
)
Expand All @@ -20,6 +23,10 @@ var (
compo Composition
// Array 小作文数组指针
Array = &compo.Array
// m 小作文保存锁
m sync.Mutex
// md5s 验证重复
md5s [][16]byte
)

func init() {
Expand All @@ -31,7 +38,12 @@ func init() {
}
err1 := LoadText()
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 {
log.Printf("[Diana]读取小作文错误:%v", err1)
}
Expand Down Expand Up @@ -79,21 +91,47 @@ func LoadText() error {

// AddText 添加小作文
func AddText(txt string) error {
if txt != "" {
sum := md5.Sum(str2bytes(txt))
if txt != "" && !isin(sum) {
compo.Array = append(compo.Array, txt)
data, err := compo.Marshal()
if err == nil {
if _, err := os.Stat(datapath); err == nil || os.IsExist(err) {
f, err1 := os.OpenFile(pbfile, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
if err1 == nil {
defer f.Close()
_, err2 := f.Write(data)
return err2
}
return err1
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()
if err == nil {
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)
if err1 == nil {
_, err2 := f.Write(data)
f.Close()

return err2
}
return err1
}
return err
}
return nil
return err
}

// 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))
}

0 comments on commit 0bffc38

Please sign in to comment.