kble/src/vec2.zig

64 lines
1.5 KiB
Zig
Raw Normal View History

2021-01-25 09:47:15 +01:00
//! This module provides functions for creating and manipulating 2D
//! vectors with integer precision.
const expect = @import("std").testing.expect;
2021-01-26 14:10:29 +01:00
const Self = @This();
pub const int_type = u16;
x: int_type,
y: int_type,
2021-01-26 14:10:29 +01:00
/// Create a vector with `x` and `y` values.
pub fn init(x: int_type, y: int_type) Self {
2021-01-26 14:10:29 +01:00
return Self {
.x = x,
.y = y,
};
}
/// Return the sum of `self` and `other`.
2021-01-26 14:10:29 +01:00
pub fn add(self: Self, other: Self) Self {
return Self {
.x = self.x + other.x,
.y = self.y + other.y,
};
}
/// Return the difference between `self` and `other`.
2021-01-26 14:10:29 +01:00
pub fn sub(self: Self, other: Self) Self {
return Self {
.x = self.x - other.x,
.y = self.y - other.y,
};
}
test "create Self w/ positive values" {
const vector = Self.init(15984, 95715);
2021-01-25 09:47:15 +01:00
expect(vector.x == 15984);
expect(vector.y == 95715);
}
2021-01-26 14:10:29 +01:00
test "create Self w/ negative values" {
const vector = Self.init(-51428, -56123);
2021-01-25 09:47:15 +01:00
expect(vector.x == -51428);
expect(vector.y == -56123);
}
2021-01-26 14:10:29 +01:00
test "add two Self using dot syntax" {
const vector_1 = Self.init(6712, 981);
const vector_2 = Self.init(-1823, 12);
2021-01-25 09:47:15 +01:00
const vector_sum = vector_1.add(vector_2);
expect(vector_sum.x == 4889);
expect(vector_sum.y == 993);
}
2021-01-26 14:10:29 +01:00
test "calculate difference between two Self using dot syntax" {
const vector_1 = Self.init(6712, 981);
const vector_2 = Self.init(-1823, 12);
2021-01-25 09:47:15 +01:00
const vector_diff = vector_1.sub(vector_2);
expect(vector_diff.x == 8535);
expect(vector_diff.y == 969);
}