2024-02-27 14:10:27 +01:00
|
|
|
package data
|
|
|
|
|
2024-03-01 11:30:31 +01:00
|
|
|
import (
|
2024-03-02 00:28:42 +01:00
|
|
|
"sync"
|
2024-03-01 11:30:31 +01:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/google/uuid"
|
|
|
|
)
|
2024-02-27 14:10:27 +01:00
|
|
|
|
|
|
|
type Article struct {
|
|
|
|
Title string
|
|
|
|
Created time.Time
|
|
|
|
Desc string
|
|
|
|
Content string
|
2024-03-01 21:01:38 +01:00
|
|
|
Tags []string
|
2024-03-01 11:30:31 +01:00
|
|
|
UUID uuid.UUID
|
2024-02-27 14:10:27 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
type ArticleList struct {
|
2024-03-02 00:28:42 +01:00
|
|
|
addCh chan *Article
|
|
|
|
delCh chan uuid.UUID
|
|
|
|
retCh chan *Article
|
|
|
|
getCh chan []Article
|
|
|
|
list []*Article
|
|
|
|
wg sync.WaitGroup
|
|
|
|
}
|
|
|
|
|
|
|
|
func minArticleList() *ArticleList {
|
|
|
|
return &ArticleList{
|
|
|
|
addCh: make(chan *Article),
|
|
|
|
delCh: make(chan uuid.UUID),
|
|
|
|
retCh: make(chan *Article),
|
|
|
|
getCh: make(chan []Article),
|
|
|
|
}
|
2024-02-27 14:10:27 +01:00
|
|
|
}
|
|
|
|
|
2024-03-01 21:01:38 +01:00
|
|
|
func (l *ArticleList) start() {
|
2024-03-02 00:28:42 +01:00
|
|
|
l.wg.Done()
|
2024-03-01 21:01:38 +01:00
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case article := <-l.addCh:
|
|
|
|
l.list = append(l.list, article)
|
|
|
|
case uuid := <-l.delCh:
|
|
|
|
for i, article := range l.list {
|
|
|
|
if article.UUID == uuid {
|
|
|
|
l.list = append(l.list[:i], l.list[i+1:]...)
|
|
|
|
l.retCh <- article
|
|
|
|
}
|
|
|
|
}
|
2024-03-02 00:28:42 +01:00
|
|
|
case l.getCh <- func() []Article {
|
2024-03-01 21:01:38 +01:00
|
|
|
var list []Article
|
|
|
|
for _, article := range l.list {
|
|
|
|
list = append(list, *article)
|
|
|
|
}
|
|
|
|
return list
|
|
|
|
}():
|
|
|
|
}
|
|
|
|
}
|
2024-02-27 14:10:27 +01:00
|
|
|
}
|
|
|
|
|
2024-03-01 21:01:38 +01:00
|
|
|
func NewArticleList() *ArticleList {
|
2024-03-02 00:28:42 +01:00
|
|
|
list := minArticleList()
|
|
|
|
list.list = []*Article{}
|
|
|
|
|
|
|
|
list.wg.Add(1)
|
2024-03-01 21:01:38 +01:00
|
|
|
go list.start()
|
2024-03-02 00:28:42 +01:00
|
|
|
list.wg.Wait()
|
|
|
|
|
2024-03-01 21:01:38 +01:00
|
|
|
return list
|
|
|
|
}
|
|
|
|
|
|
|
|
func (l *ArticleList) Add(a *Article) {
|
|
|
|
l.addCh <- a
|
|
|
|
}
|
|
|
|
|
|
|
|
func (l *ArticleList) Release(uuid uuid.UUID) (*Article, bool) {
|
|
|
|
l.delCh <- uuid
|
|
|
|
article := <-l.retCh
|
|
|
|
if article == nil {
|
|
|
|
return nil, false
|
2024-02-27 14:10:27 +01:00
|
|
|
}
|
2024-03-01 21:01:38 +01:00
|
|
|
return article, true
|
|
|
|
}
|
|
|
|
|
2024-03-02 00:28:42 +01:00
|
|
|
func (l *ArticleList) Get() []Article {
|
|
|
|
return <-l.getCh
|
2024-02-27 14:10:27 +01:00
|
|
|
}
|