1package vt
2
3import (
4 "fmt"
5 "math"
6)
7
8// DecodeStats describes resources declared by one canonical VT blob.
9type DecodeStats struct {
10 Chunks uint64
11 Rows uint64
12 Cells uint64
13 Styles uint64
14 Bytes uint64
15}
16
17// Add adds another preflight result with overflow checking.
18func (s *DecodeStats) Add(other DecodeStats) bool {
19 for _, totals := range [][2]*uint64{{&s.Chunks, &other.Chunks}, {&s.Rows, &other.Rows}, {&s.Cells, &other.Cells}, {&s.Styles, &other.Styles}, {&s.Bytes, &other.Bytes}} {
20 if math.MaxUint64-*totals[0] < *totals[1] {
21 return false
22 }
23 *totals[0] += *totals[1]
24 }
25 return true
26}
27
28// PreflightHistoryBlob validates one self-contained history blob without
29// allocating decoded rows.
30func PreflightHistoryBlob(data []byte) (DecodeStats, error) {
31 stats, ok := preflightHistory(data)
32 if !ok {
33 return DecodeStats{}, fmt.Errorf("preflight history: %w", errInvalidHistory)
34 }
35 return DecodeStats{Chunks: stats.chunks, Rows: stats.rows, Cells: stats.cells, Styles: stats.styles, Bytes: stats.bytes}, nil
36}
37
38// MarshalHistoryChunk encodes one immutable chunk as a self-contained blob.
39func MarshalHistoryChunk(chunk *HistoryChunk) ([]byte, error) {
40 if chunk == nil {
41 return nil, fmt.Errorf("marshal history chunk: %w", errInvalidHistory)
42 }
43 return MarshalHistory(HistoryView{chunks: []*HistoryChunk{chunk}, rows: len(chunk.rows)})
44}
45
46// MarshalEmptyHistoryTail returns the mandatory canonical empty tail blob.
47func MarshalEmptyHistoryTail() ([]byte, error) { return MarshalHistory(HistoryView{}) }
48
49// MarshalHistoryTail encodes the copied mutable tail of a snapshot view as one
50// canonical history blob. It does not seal or otherwise mutate live history.
51func MarshalHistoryTail(view HistorySnapshotView) ([]byte, error) {
52 return MarshalHistory(view.Tail())
53}
54
55// MarshalSealedHistory serializes a SealAndView result as oldest-first,
56// self-contained sealed blobs plus a mandatory empty tail blob. The empty tail
57// carries NextRowID and is not the canonical default empty encoding.
58func MarshalSealedHistory(view HistoryView) ([][]byte, []byte, error) {
59 if view.rows != historyViewRowCount(view) {
60 return nil, nil, fmt.Errorf("marshal sealed history: %w", errInvalidHistory)
61 }
62 sealed := make([][]byte, len(view.chunks))
63 for i, chunk := range view.chunks {
64 blob, err := MarshalHistoryChunk(chunk)
65 if err != nil {
66 return nil, nil, err
67 }
68 sealed[i] = blob
69 }
70 tail, err := MarshalHistory(HistoryView{nextRowID: view.NextRowID()})
71 if err != nil {
72 return nil, nil, err
73 }
74 return sealed, tail, nil
75}
76
77// HistoryFromBlobs restores history directly from sealed, oldest-first blobs
78// and the mandatory tail blob. It never feeds decoded rows through Append.
79func HistoryFromBlobs(config HistoryConfig, sealed [][]byte, tail []byte) (*History, error) {
80 sealedViews, tailView, err := decodeRestoredHistoryBlobs(sealed, tail)
81 if err != nil {
82 return nil, err
83 }
84 return restoreHistoryViews(config, sealedViews, tailView), nil
85}
86
87func decodeRestoredHistoryBlobs(sealed [][]byte, tail []byte, extra ...HistoryView) ([]HistoryView, HistoryView, error) {
88 seen := make(map[RowID]struct{})
89 sealedViews := make([]HistoryView, len(sealed))
90 for i, blob := range sealed {
91 view, err := UnmarshalHistory(blob)
92 if err != nil || len(view.chunks) != 1 || len(view.chunks[0].rows) == 0 || !validateRestoredHistoryView(view, seen) {
93 return nil, HistoryView{}, fmt.Errorf("restore sealed history: %w", errInvalidHistory)
94 }
95 sealedViews[i] = view
96 }
97
98 tailView, err := UnmarshalHistory(tail)
99 if err != nil || len(tailView.chunks) > 1 || !validateRestoredHistoryView(tailView, seen) {
100 return nil, HistoryView{}, fmt.Errorf("restore history tail: %w", errInvalidHistory)
101 }
102 for _, view := range extra {
103 if !validateRestoredHistoryView(view, seen) {
104 return nil, HistoryView{}, fmt.Errorf("restore recovery transcript: %w", errInvalidHistory)
105 }
106 }
107 return sealedViews, tailView, nil
108}
109
110func restoreHistoryViews(config HistoryConfig, sealed []HistoryView, tail HistoryView) *History {
111 h := NewHistory(config)
112 for _, view := range sealed {
113 h.nextRowID = max(h.nextRowID, view.nextRowID)
114 if h.maxRows == 0 {
115 continue
116 }
117 chunk := view.chunks[0]
118 h.chunks = append(h.chunks, chunk)
119 h.rows += len(chunk.rows)
120 h.cells += view.Cells()
121 h.evict()
122 }
123 h.nextRowID = max(h.nextRowID, tail.nextRowID)
124 if h.maxRows == 0 || len(tail.chunks) == 0 {
125 return h
126 }
127 chunk := tail.chunks[0]
128 h.tail = chunk.rows
129 h.tailBounds = append([]LineBound(nil), chunk.bounds...)
130 h.tailIDs = append([]RowID(nil), chunk.rowIDs...)
131 h.rows += len(h.tail)
132 h.cells += tail.Cells()
133 h.evict()
134 h.normalizeTail()
135 return h
136}
137
138func validateRestoredHistoryView(view HistoryView, seen map[RowID]struct{}) bool {
139 if view.nextRowID == 0 || view.nextRowID == ^RowID(0) {
140 return false
141 }
142 var maxID RowID
143 for _, chunk := range view.chunks {
144 if chunk == nil || len(chunk.rows) != len(chunk.rowIDs) || len(chunk.rows) != len(chunk.bounds) {
145 return false
146 }
147 for _, id := range chunk.rowIDs {
148 if id == 0 || id >= ^RowID(0)-1 {
149 return false
150 }
151 if _, duplicate := seen[id]; duplicate {
152 return false
153 }
154 seen[id] = struct{}{}
155 maxID = max(maxID, id)
156 }
157 }
158 return view.nextRowID > maxID
159}
160
161// NewScreenWithRecoveryTranscript constructs a fresh blank screen whose
162// history contains the restored bounded history followed by the recovery
163// transcript. The transcript is decoded in full before history is restored.
164func NewScreenWithRecoveryTranscript(width, height int, config HistoryConfig, sealed [][]byte, tail, transcript []byte) (*Screen, error) {
165 transcriptView, err := UnmarshalHistory(transcript)
166 if err != nil {
167 return nil, fmt.Errorf("restore recovery transcript: %w", err)
168 }
169
170 sealedViews, tailView, err := decodeRestoredHistoryBlobs(sealed, tail, transcriptView)
171 if err != nil {
172 return nil, err
173 }
174 history := restoreHistoryViews(config, sealedViews, tailView)
175 remainingRows := transcriptView.rows
176 for _, chunk := range transcriptView.chunks {
177 for i, row := range chunk.rows {
178 remainingRows--
179 bound := chunk.bounds[i]
180 if remainingRows == 0 {
181 bound.Soft = false
182 }
183 if err := history.AppendWithID(row, bound, chunk.rowIDs[i]); err != nil {
184 return nil, fmt.Errorf("restore recovery transcript: %w", err)
185 }
186 }
187 }
188
189 screen := NewScreenWithHistory(width, height, config)
190 screen.history = history
191 counter := max(history.nextRowID, transcriptView.nextRowID, RowID(1))
192 if counter == 0 || counter >= ^RowID(0) || uint64(height) > uint64(^RowID(0)-1-counter) {
193 return nil, fmt.Errorf("restore recovery transcript: %w", errInvalidHistory)
194 }
195 screen.nextRowID = counter - 1
196 for i := range screen.buffer.rowIDs {
197 screen.buffer.rowIDs[i] = screen.nextRowIDValue()
198 }
199 screen.Frame = screen.buffer.frame
200 return screen, nil
201}