boards.gno
1.49 Kb ยท 97 lines
1package storage
2
3import (
4 "strconv"
5
6 "gno.land/p/nt/avl"
7)
8
9var boards avl.Tree
10
11type Board interface {
12 AddPost(title, content string)
13 GetPost(id int) (Post, bool)
14 Size() int
15}
16
17// posts are persisted in an avl tree
18type TreeBoard struct {
19 id int
20 posts *avl.Tree
21}
22
23func (b *TreeBoard) AddPost(title, content string) {
24 n := b.posts.Size()
25 p := Post{n, title, content}
26 b.posts.Set(strconv.Itoa(n), p)
27}
28
29func (b *TreeBoard) GetPost(id int) (Post, bool) {
30 p, ok := b.posts.Get(strconv.Itoa(id))
31 if ok {
32 return p.(Post), ok
33 } else {
34 return Post{}, ok
35 }
36}
37
38func (b *TreeBoard) Size() int {
39 return b.posts.Size()
40}
41
42// posts are persisted in a map
43type MapBoard struct {
44 id int
45 posts map[int]Post
46}
47
48func (b *MapBoard) AddPost(title, content string) {
49 n := len(b.posts)
50 p := Post{n, title, content}
51 b.posts[n] = p
52}
53
54func (b *MapBoard) GetPost(id int) (Post, bool) {
55 p, ok := b.posts[id]
56 if ok {
57 return p, ok
58 } else {
59 return Post{}, ok
60 }
61}
62
63func (b *MapBoard) Size() int {
64 return len(b.posts)
65}
66
67// posts are persisted in a slice
68type SliceBoard struct {
69 id int
70 posts []Post
71}
72
73func (b *SliceBoard) AddPost(title, content string) {
74 n := len(b.posts)
75 p := Post{n, title, content}
76 b.posts = append(b.posts, p)
77}
78
79func (b *SliceBoard) GetPost(id int) (Post, bool) {
80 if id < len(b.posts) {
81 p := b.posts[id]
82
83 return p, true
84 } else {
85 return Post{}, false
86 }
87}
88
89func (b *SliceBoard) Size() int {
90 return len(b.posts)
91}
92
93type Post struct {
94 id int
95 title string
96 content string
97}