summaryrefslogtreecommitdiff
path: root/src/bitmap.zig
blob: 9a9f7ac5d7bf44db6a2eb3f41c431eac87006863 (plain)
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
const std = @import("std");
const Allocator = std.mem.Allocator;

pub fn Bitmap(PixelType: type) type {
    return struct {
        const Self = @This();

        pixels: []PixelType,
        width: usize,
        height: usize,

        /// Creates a new Bitmap instance and allocates the `pixels` buffer.
        pub fn init_undefined(gpa: Allocator, width: usize, height: usize) !Self {
            const self: Self = .{
                .width = width,
                .height = height,
                .pixels = try gpa.alloc(PixelType, width * height),
            };

            return self;
        }

        pub fn from_buffer(buffer: []PixelType, width: usize, height: usize) Self {
            return .{
                .width = width,
                .height = height,
                .pixels = buffer,
            };
        }

        pub inline fn pixel(self: *Self, x: usize, y: usize) ?*PixelType {
            return if (x < self.width and y < self.height)
                self.pixels[x + self.width * y]
            else
                null;
        }

        pub fn deinit(self: Self, gpa: Allocator) void {
            gpa.free(self.pixels);
        }
    };
}