kble/src/parameter.zig

37 lines
1.2 KiB
Zig

// SPDX-License-Identifier: MIT
// Copyright (c) 2021 KikooDX
// This file is part of [KBLE](https://sr.ht/~kikoodx/kble), which is
// MIT licensed. The MIT license requires this copyright notice to be
// included in all copies and substantial portions of the software.
const std = @import("std");
const Self = @This();
pub const buffer_type = u16;
pub const buffer_limit = std.math.maxInt(buffer_type) / 10;
buffer: buffer_type = 0, // hold current number
used: bool = false, // keep track of buffer usage
/// Only accept key between '0' and '9' inclusive. Add a number to the buffer.
pub fn process_key(self: *Self, key: u8) void {
if (key < '0' or key > '9') unreachable;
self.used = true;
const number: buffer_type = key - '0';
if (self.buffer < buffer_limit) {
self.buffer *= 10;
self.buffer += number;
std.log.info("Parameter buffer: {}", .{self});
} else {
std.log.warn("Buffer limit reached.", .{});
}
}
/// Return the buffer value if used and reset it. Otherwise return `default`.
pub fn pop(self: *Self, default: buffer_type) buffer_type {
defer self.buffer = 0;
defer self.used = false;
return if (self.used) self.buffer else default;
}