1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
|
const std = @import("std");
const assert = std.debug.assert;
const color = @import("color.zig");
const sgr = @import("sgr.zig");
const page = @import("page.zig");
const size = @import("size.zig");
const Offset = size.Offset;
const OffsetBuf = size.OffsetBuf;
const RefCountedSet = @import("ref_counted_set.zig").RefCountedSet;
const XxHash3 = std.hash.XxHash3;
const autoHash = std.hash.autoHash;
/// The unique identifier for a style. This is at most the number of cells
/// that can fit into a terminal page.
pub const Id = size.CellCountInt;
/// The Id to use for default styling.
pub const default_id: Id = 0;
/// The style attributes for a cell.
pub const Style = struct {
/// Various colors, all self-explanatory.
fg_color: Color = .none,
bg_color: Color = .none,
underline_color: Color = .none,
/// On/off attributes that don't require much bit width so we use
/// a packed struct to make this take up significantly less space.
flags: Flags = .{},
const Flags = packed struct(u16) {
bold: bool = false,
italic: bool = false,
faint: bool = false,
blink: bool = false,
inverse: bool = false,
invisible: bool = false,
strikethrough: bool = false,
overline: bool = false,
underline: sgr.Attribute.Underline = .none,
_padding: u5 = 0,
};
/// The color for an SGR attribute. A color can come from multiple
/// sources so we use this to track the source plus color value so that
/// we can properly react to things like palette changes.
pub const Color = union(Tag) {
none: void,
palette: u8,
rgb: color.RGB,
const Tag = enum(u8) {
none,
palette,
rgb,
};
/// Formatting to make debug logs easier to read
/// by only including non-default attributes.
pub fn format(
self: Color,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = fmt;
_ = options;
switch (self) {
.none => {
_ = try writer.write("Color.none");
},
.palette => |p| {
_ = try writer.print("Color.palette{{ {} }}", .{p});
},
.rgb => |rgb| {
_ = try writer.print("Color.rgb{{ {}, {}, {} }}", .{ rgb.r, rgb.g, rgb.b });
},
}
}
};
/// True if the style is the default style.
pub fn default(self: Style) bool {
return self.eql(.{});
}
/// True if the style is equal to another style.
pub fn eql(self: Style, other: Style) bool {
const packed_self = PackedStyle.fromStyle(self);
const packed_other = PackedStyle.fromStyle(other);
// TODO: in Zig 0.14, equating packed structs is allowed. Remove this work around.
return @as(u128, @bitCast(packed_self)) == @as(u128, @bitCast(packed_other));
}
/// Returns the bg color for a cell with this style given the cell
/// that has this style and the palette to use.
///
/// Note that generally if a cell is a color-only cell, it SHOULD
/// only have the default style, but this is meant to work with the
/// default style as well.
pub fn bg(
self: Style,
cell: *const page.Cell,
palette: *const color.Palette,
) ?color.RGB {
return switch (cell.content_tag) {
.bg_color_palette => palette[cell.content.color_palette],
.bg_color_rgb => rgb: {
const rgb = cell.content.color_rgb;
break :rgb .{ .r = rgb.r, .g = rgb.g, .b = rgb.b };
},
else => switch (self.bg_color) {
.none => null,
.palette => |idx| palette[idx],
.rgb => |rgb| rgb,
},
};
}
/// Returns the fg color for a cell with this style given the palette.
pub fn fg(
self: Style,
palette: *const color.Palette,
bold_is_bright: bool,
) ?color.RGB {
return switch (self.fg_color) {
.none => null,
.palette => |idx| palette: {
if (bold_is_bright and self.flags.bold) {
const bright_offset = @intFromEnum(color.Name.bright_black);
if (idx < bright_offset)
break :palette palette[idx + bright_offset];
}
break :palette palette[idx];
},
.rgb => |rgb| rgb,
};
}
/// Returns the underline color for this style.
pub fn underlineColor(
self: Style,
palette: *const color.Palette,
) ?color.RGB {
return switch (self.underline_color) {
.none => null,
.palette => |idx| palette[idx],
.rgb => |rgb| rgb,
};
}
/// Returns a bg-color only cell from this style, if it exists.
pub fn bgCell(self: Style) ?page.Cell {
return switch (self.bg_color) {
.none => null,
.palette => |idx| .{
.content_tag = .bg_color_palette,
.content = .{ .color_palette = idx },
},
.rgb => |rgb| .{
.content_tag = .bg_color_rgb,
.content = .{ .color_rgb = .{
.r = rgb.r,
.g = rgb.g,
.b = rgb.b,
} },
},
};
}
/// Formatting to make debug logs easier to read
/// by only including non-default attributes.
pub fn format(
self: Style,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = fmt;
_ = options;
const dflt: Style = .{};
_ = try writer.write("Style{ ");
var started = false;
inline for (std.meta.fields(Style)) |f| {
if (std.mem.eql(u8, f.name, "flags")) {
if (started) {
_ = try writer.write(", ");
}
_ = try writer.write("flags={ ");
started = false;
inline for (std.meta.fields(@TypeOf(self.flags))) |ff| {
const v = @as(ff.type, @field(self.flags, ff.name));
const d = @as(ff.type, @field(dflt.flags, ff.name));
if (ff.type == bool) {
if (v) {
if (started) {
_ = try writer.write(", ");
}
_ = try writer.print("{s}", .{ff.name});
started = true;
}
} else if (!std.meta.eql(v, d)) {
if (started) {
_ = try writer.write(", ");
}
_ = try writer.print(
"{s}={any}",
.{ ff.name, v },
);
started = true;
}
}
_ = try writer.write(" }");
started = true;
comptime continue;
}
const value = @as(f.type, @field(self, f.name));
const d_val = @as(f.type, @field(dflt, f.name));
if (!std.meta.eql(value, d_val)) {
if (started) {
_ = try writer.write(", ");
}
_ = try writer.print(
"{s}={any}",
.{ f.name, value },
);
started = true;
}
}
_ = try writer.write(" }");
}
/// `PackedStyle` represents the same data as `Style` but without padding,
/// which is necessary for hashing via re-interpretation of the underlying
/// bytes.
///
/// `Style` is still preferred for everything else as it has type-safety
/// when using the `Color` tagged union.
///
/// Empirical testing shows that storing all of the tags first and then the
/// data provides a better layout for serializing into and is faster on
/// benchmarks.
const PackedStyle = packed struct(u128) {
tags: packed struct {
fg: Color.Tag,
bg: Color.Tag,
underline: Color.Tag,
},
data: packed struct {
fg: Data,
bg: Data,
underline: Data,
},
flags: Flags,
_padding: u16 = 0,
/// After https://github.com/ziglang/zig/issues/19754 is implemented,
/// it will be an compiler-error to have packed union fields of
/// differing size.
///
/// For now we just need to be careful not to accidentally introduce
/// padding.
const Data = packed union {
none: u24,
palette: packed struct(u24) {
idx: u8,
_padding: u16 = 0,
},
rgb: color.RGB,
fn fromColor(c: Color) Data {
return switch (c) {
inline else => |v, t| @unionInit(
Data,
@tagName(t),
switch (t) {
.none => 0,
.palette => .{ .idx = v },
.rgb => v,
},
),
};
}
};
fn fromStyle(style: Style) PackedStyle {
return .{
.tags = .{
.fg = std.meta.activeTag(style.fg_color),
.bg = std.meta.activeTag(style.bg_color),
.underline = std.meta.activeTag(style.underline_color),
},
.data = .{
.fg = Data.fromColor(style.fg_color),
.bg = Data.fromColor(style.bg_color),
.underline = Data.fromColor(style.underline_color),
},
.flags = style.flags,
};
}
};
pub fn hash(self: *const Style) u64 {
const packed_style = PackedStyle.fromStyle(self.*);
return XxHash3.hash(0, std.mem.asBytes(&packed_style));
}
comptime {
assert(@sizeOf(PackedStyle) == 16);
assert(std.meta.hasUniqueRepresentation(PackedStyle));
}
};
pub const Set = RefCountedSet(
Style,
Id,
size.CellCountInt,
struct {
pub fn hash(self: *const @This(), style: Style) u64 {
_ = self;
return style.hash();
}
pub fn eql(self: *const @This(), a: Style, b: Style) bool {
_ = self;
return a.eql(b);
}
},
);
test "Set basic usage" {
const testing = std.testing;
const alloc = testing.allocator;
const layout: Set.Layout = .init(16);
const buf = try alloc.alignedAlloc(u8, Set.base_align, layout.total_size);
defer alloc.free(buf);
const style: Style = .{ .flags = .{ .bold = true } };
const style2: Style = .{ .flags = .{ .italic = true } };
var set = Set.init(OffsetBuf.init(buf), layout, .{});
// Add style
const id = try set.add(buf, style);
try testing.expect(id > 0);
// Second add should return the same metadata.
{
const id2 = try set.add(buf, style);
try testing.expectEqual(id, id2);
}
// Look it up
{
const v = set.get(buf, id);
try testing.expect(v.flags.bold);
const v2 = set.get(buf, id);
try testing.expectEqual(v, v2);
}
// Add a second style
const id2 = try set.add(buf, style2);
// Look it up
{
const v = set.get(buf, id2);
try testing.expect(v.flags.italic);
}
// Ref count
try testing.expect(set.refCount(buf, id) == 2);
try testing.expect(set.refCount(buf, id2) == 1);
// Release
set.release(buf, id);
try testing.expect(set.refCount(buf, id) == 1);
set.release(buf, id2);
try testing.expect(set.refCount(buf, id2) == 0);
// We added the first one twice, so
set.release(buf, id);
try testing.expect(set.refCount(buf, id) == 0);
}
test "Set capacities" {
// We want to support at least this many styles without overflowing.
_ = Set.Layout.init(16384);
}
|