1// Package chonk provides a simple way to store arbitrarily large strings
2// in a linked list across transactions for efficient storage and retrieval.
3// A Chonk support three operations: Add, Flush, and Scanner.
4// - Add appends a string to the Chonk.
5// - Flush clears the Chonk.
6// - Scanner is used to iterate over the chunks in the Chonk.
7package chonk
8
9// Chonk is a linked list string storage and
10// retrieval system for fine bois.
11type Chonk struct {
12 first *chunk
13 last *chunk
14}
15
16// chunk is a linked list node for Chonk
17type chunk struct {
18 text string
19 next *chunk
20}
21
22// New creates a reference to a new Chonk
23func New() *Chonk {
24 return &Chonk{}
25}
26
27// Add appends a string to the Chonk. If the Chonk is empty,
28// the string will be the first and last chunk. Otherwise,
29// the string will be appended to the end of the Chonk.
30func (c *Chonk) Add(text string) {
31 next := &chunk{text: text}
32 if c.first == nil {
33 c.first = next
34 c.last = next
35 return
36 }
37 c.last.next = next
38 c.last = next
39}
40
41// Flush clears the Chonk by setting the first and last
42// chunks to nil. This will allow the garbage collector to
43// free the memory used by the Chonk.
44func (c *Chonk) Flush() {
45 c.first = nil
46 c.last = nil
47}
48
49// Scanner returns a new Scanner for the Chonk. The Scanner
50// is used to iterate over the chunks in the Chonk.
51func (c *Chonk) Scanner() *Scanner {
52 return &Scanner{
53 next: c.first,
54 }
55}
56
57// Scanner is a simple string scanner for Chonk. It is used
58// to iterate over the chunks in a Chonk from first to last.
59type Scanner struct {
60 current *chunk
61 next *chunk
62}
63
64// Scan advances the scanner to the next chunk. It returns
65// true if there is a next chunk, and false if there is not.
66func (s *Scanner) Scan() bool {
67 if s.next != nil {
68 s.current = s.next
69 s.next = s.next.next
70 return true
71 }
72 return false
73}
74
75// Text returns the current chunk. It is only valid to call
76// this method after a call to Scan returns true. Expected usage:
77//
78// scanner := chonk.Scanner()
79// for scanner.Scan() {
80// fmt.Println(scanner.Text())
81// }
82func (s *Scanner) Text() string {
83 return s.current.text
84}
chonk.gno
2.07 Kb ยท 84 lines