Compare commits
1 Commits
main
..
6451142c47
| Author | SHA1 | Date | |
|---|---|---|---|
| 6451142c47 |
@@ -0,0 +1,3 @@
|
||||
# test-projects
|
||||
|
||||
projects to test specific features of programming languages
|
||||
@@ -1,6 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
path="$(realpath "${BASH_SOURCE}")"
|
||||
|
||||
echo "path: ${path%/*}"
|
||||
echo "file: ${path##*/}"
|
||||
@@ -1,13 +0,0 @@
|
||||
bin/
|
||||
|
||||
*.o
|
||||
|
||||
*.pdf
|
||||
|
||||
*.a
|
||||
*.so
|
||||
*.tar
|
||||
|
||||
*.zip
|
||||
*.xz
|
||||
*.gz
|
||||
@@ -1,66 +0,0 @@
|
||||
SHELL := /usr/bin/env bash
|
||||
|
||||
PREFIX :=
|
||||
CC := $(PREFIX)gcc
|
||||
LD := $(PREFIX)ld
|
||||
SIZE := $(PREFIX)size
|
||||
GDB := $(PREFIX)gdb
|
||||
|
||||
NAME := c-test-project
|
||||
|
||||
SRC_DIR := ./src
|
||||
INC_DIR := ./inc
|
||||
BIN_DIR := ./bin
|
||||
OBJ_DIR := $(BIN_DIR)/obj
|
||||
|
||||
OPT_LEVEL := -g3 \
|
||||
-O0
|
||||
|
||||
C_SRC := main.c
|
||||
|
||||
C_DEF :=
|
||||
C_DEF := $(addprefix -D, $(C_DEF))
|
||||
|
||||
C_INC := $(INC_DIR)
|
||||
C_INC := $(addprefix -I, $(C_INC))
|
||||
|
||||
C_FLAGS := $(C_DEF) \
|
||||
$(C_INC) \
|
||||
$(OPT_LEVEL) \
|
||||
-Wall \
|
||||
-Wextra \
|
||||
-Wpedantic \
|
||||
-Wconversion \
|
||||
-Wsign-conversion \
|
||||
-Wsign-compare \
|
||||
-Wcast-align=strict \
|
||||
-Wfloat-equal \
|
||||
-Wlogical-op \
|
||||
-Wno-maybe-uninitialized \
|
||||
-Werror
|
||||
|
||||
BINARY := $(BIN_DIR)/$(NAME)
|
||||
|
||||
MKDIR := $(BIN_DIR) $(OBJ_DIR)
|
||||
|
||||
VPATH := $(SRC_DIR)
|
||||
|
||||
|
||||
.PHONY: all clean rebuild run test
|
||||
|
||||
all: $(MKDIR) $(BINARY)
|
||||
|
||||
clean:
|
||||
@rm -rf $(MKDIR)
|
||||
|
||||
rebuild: clean all
|
||||
|
||||
run: all
|
||||
./$(BINARY)
|
||||
|
||||
$(MKDIR):
|
||||
@mkdir -p $@
|
||||
|
||||
$(BINARY): $(C_SRC)
|
||||
gcc $(C_FLAGS) $^ -o $@
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#define ARRAY_SIZE ( ( int ) 16 )
|
||||
|
||||
int main(void)
|
||||
{
|
||||
int array[ARRAY_SIZE] = { 0 };
|
||||
int n;
|
||||
|
||||
for ( n = 0; n < ARRAY_SIZE; n++ )
|
||||
{
|
||||
printf( "array[%d] = %d;\n", n, array[n] );
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
|
||||
clean::
|
||||
echo "AAAA"
|
||||
@@ -1,3 +0,0 @@
|
||||
|
||||
clean::
|
||||
echo "BBBB"
|
||||
@@ -1,9 +0,0 @@
|
||||
SHELL := /usr/bin/env bash
|
||||
|
||||
.PHONY: all clean test
|
||||
|
||||
clean::
|
||||
echo "blargh"
|
||||
|
||||
include ./a.mk
|
||||
include ./b.mk
|
||||
@@ -1,4 +0,0 @@
|
||||
target
|
||||
Cargo.lock
|
||||
test*
|
||||
log.db*
|
||||
@@ -1,18 +0,0 @@
|
||||
[package]
|
||||
name = "rust"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0"
|
||||
axum = "0.8.4"
|
||||
chrono = { version = "0.4.41", features = ["serde"] }
|
||||
ciborium = "0.2.2"
|
||||
clap = { version = "4.5.0", features = ["derive"] }
|
||||
cobs = { version = "0.4.0" }
|
||||
dirs = "5.0.1"
|
||||
serde = { version = "1.0.219", features = ["derive"] }
|
||||
serde_json = "1.0.141"
|
||||
thiserror = "2.0.12"
|
||||
tokio = { version = "1.46.1", features = ["full"] }
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
target/debug/rust
|
||||
@@ -1 +0,0 @@
|
||||
stable
|
||||
@@ -1,115 +0,0 @@
|
||||
#![allow(dead_code, unused)]
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
for n in 0..16 {
|
||||
let measurement: u16 = 65_535 / 16 * n;
|
||||
let millikelvin = (((measurement as u32) * 21_875u32) >> 13) + 228_150u32;
|
||||
let temperature = Temperature::from_millikelvin(millikelvin);
|
||||
|
||||
println!("raw = {measurement}, converted = {millikelvin}, temperature = {temperature}");
|
||||
}
|
||||
let measurement: u16 = 65_535;
|
||||
let millikelvin = (((measurement as u32) * 21_875u32) >> 13) + 228_150u32;
|
||||
let temperature = Temperature::from_millikelvin(millikelvin);
|
||||
|
||||
println!("raw = {measurement}, converted = {millikelvin}, temperature = {temperature}");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, thiserror::Error)]
|
||||
pub enum TemperatureError {
|
||||
#[error("provided input is invalid: {0}")]
|
||||
InvalidInput(f32),
|
||||
#[error("conversion between units changed the value noticeably")]
|
||||
ConversionError,
|
||||
}
|
||||
|
||||
/// type for temperature
|
||||
/// represents the temperature in Millikelvin
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
|
||||
pub struct Temperature{
|
||||
value: u32,
|
||||
}
|
||||
|
||||
impl Temperature {
|
||||
#[allow(non_upper_case_globals)]
|
||||
const CELSIUS_OFFSET_C: f32 = 273.15f32;
|
||||
|
||||
/// create a new instance of `Temperature` from a value in Millikelvin
|
||||
/// this function is an alias for `from_millikelvin()`
|
||||
pub fn new(millikelvin: u32) -> Self {
|
||||
Self::from_millikelvin(millikelvin)
|
||||
}
|
||||
|
||||
/// create a new instance of `Temperature` from a value in Millikelvin
|
||||
pub fn from_millikelvin(millikelvin: u32) -> Self {
|
||||
Self { value: millikelvin }
|
||||
}
|
||||
|
||||
/// create a new instance of `Temperature` from a value in degrees Celsius
|
||||
pub fn from_celsius(celsius: f32) -> Result<Self, TemperatureError> {
|
||||
if celsius < -Self::CELSIUS_OFFSET_C { return Err(TemperatureError::InvalidInput(celsius)) }
|
||||
Ok(Self { value: Self::celsius_to_millikelvin(celsius)? })
|
||||
}
|
||||
|
||||
/// returns the temperature value in Millikelvin
|
||||
pub fn get_millikelvin(&self) -> u32 {
|
||||
self.value
|
||||
}
|
||||
|
||||
/// returns the temperature value in degrees celsius
|
||||
pub fn get_celsius(&self) -> Result<f32, TemperatureError> {
|
||||
Self::millikelvin_to_celsius(self.value)
|
||||
}
|
||||
|
||||
fn celsius_to_millikelvin(celsius: f32) -> Result<u32, TemperatureError> {
|
||||
const ACCEPTABLE_INACCURACY: f32 = 1.0 / 16.0;
|
||||
|
||||
let millikelvin: u32 = Self::celsius_to_millikelvin_unchecked(celsius);
|
||||
let celsius_converted: f32 = Self::millikelvin_to_celsius_unchecked(millikelvin);
|
||||
|
||||
if f32::abs(celsius - celsius_converted) > ACCEPTABLE_INACCURACY {
|
||||
return Err(TemperatureError::ConversionError);
|
||||
}
|
||||
|
||||
Ok(millikelvin)
|
||||
}
|
||||
|
||||
fn millikelvin_to_celsius(millikelvin: u32) -> Result<f32, TemperatureError> {
|
||||
const ACCEPTABLE_INACCURACY: u32 = 80;
|
||||
|
||||
let celsius: f32 = Self::millikelvin_to_celsius_unchecked(millikelvin);
|
||||
let millikelvin_converted: u32 = Self::celsius_to_millikelvin_unchecked(celsius);
|
||||
|
||||
if millikelvin.wrapping_sub(millikelvin_converted) > ACCEPTABLE_INACCURACY {
|
||||
return Err(TemperatureError::ConversionError);
|
||||
}
|
||||
|
||||
Ok(celsius)
|
||||
}
|
||||
|
||||
fn celsius_to_millikelvin_unchecked(celsius: f32) -> u32 {
|
||||
((celsius + Self::CELSIUS_OFFSET_C) * 1000.0) as u32
|
||||
}
|
||||
|
||||
fn millikelvin_to_celsius_unchecked(millikelvin: u32) -> f32 {
|
||||
let millicelsius: f32 = (millikelvin as f32) / 1000.0;
|
||||
millicelsius - Self::CELSIUS_OFFSET_C
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Temperature {
|
||||
// display `Temperatures` in degrees Celsius
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
if let Ok(value) = Self::millikelvin_to_celsius(self.value) {
|
||||
write!(f, "{:.2?}°C", value)?;
|
||||
} else {
|
||||
return Err(std::fmt::Error::default());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
# Lorem Ipsum
|
||||
|
||||
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
|
||||
Sed ut elementum leo, in iaculis lectus.
|
||||
Aliquam facilisis finibus ex ac tincidunt.
|
||||
Phasellus porta ornare lorem varius blandit.
|
||||
Phasellus lacinia quam porttitor massa mollis, accumsan mattis ligula iaculis.
|
||||
Maecenas nisl nisl, viverra sed gravida facilisis, varius at lorem.
|
||||
Integer eros nisl, mattis ac dapibus id, cursus eu tellus.
|
||||
Cras at odio ex.
|
||||
Mauris in lacus neque.
|
||||
Donec eleifend rutrum dolor quis aliquet.
|
||||
Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
|
||||
Proin malesuada posuere purus.
|
||||
Morbi id consectetur magna.
|
||||
Integer nec turpis dapibus, tincidunt felis sodales, mattis augue.
|
||||
@@ -1,10 +0,0 @@
|
||||
digraph {
|
||||
node [shape = "rect", style = "rounded", fontname = "JetBrainsMono"];
|
||||
entry [label = "", shape = "circle", style = "filled", color = "black"];
|
||||
adc_init [label = "initialise ADC"];
|
||||
loop [label = "", shape = "circle", style = "filled", color = "gray"];
|
||||
|
||||
entry -> adc_init
|
||||
adc_init -> loop
|
||||
loop -> entry
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
zig-out
|
||||
.zig-cache
|
||||
-116
@@ -1,116 +0,0 @@
|
||||
const std = @import("std");
|
||||
|
||||
// Although this function looks imperative, note that its job is to
|
||||
// declaratively construct a build graph that will be executed by an external
|
||||
// runner.
|
||||
pub fn build(b: *std.Build) void {
|
||||
// Standard target options allows the person running `zig build` to choose
|
||||
// what target to build for. Here we do not override the defaults, which
|
||||
// means any target is allowed, and the default is native. Other options
|
||||
// for restricting supported target set are available.
|
||||
const target = b.standardTargetOptions(.{});
|
||||
|
||||
// Standard optimization options allow the person running `zig build` to select
|
||||
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do not
|
||||
// set a preferred release mode, allowing the user to decide how to optimize.
|
||||
const optimize = b.standardOptimizeOption(.{});
|
||||
|
||||
// This creates a "module", which represents a collection of source files alongside
|
||||
// some compilation options, such as optimization mode and linked system libraries.
|
||||
// Every executable or library we compile will be based on one or more modules.
|
||||
const lib_mod = b.createModule(.{
|
||||
// `root_source_file` is the Zig "entry point" of the module. If a module
|
||||
// only contains e.g. external object files, you can make this `null`.
|
||||
// In this case the main source file is merely a path, however, in more
|
||||
// complicated build scripts, this could be a generated file.
|
||||
.root_source_file = b.path("src/root.zig"),
|
||||
.target = target,
|
||||
.optimize = optimize,
|
||||
});
|
||||
|
||||
// We will also create a module for our other entry point, 'main.zig'.
|
||||
const exe_mod = b.createModule(.{
|
||||
// `root_source_file` is the Zig "entry point" of the module. If a module
|
||||
// only contains e.g. external object files, you can make this `null`.
|
||||
// In this case the main source file is merely a path, however, in more
|
||||
// complicated build scripts, this could be a generated file.
|
||||
.root_source_file = b.path("src/main.zig"),
|
||||
.target = target,
|
||||
.optimize = optimize,
|
||||
});
|
||||
|
||||
// Modules can depend on one another using the `std.Build.Module.addImport` function.
|
||||
// This is what allows Zig source code to use `@import("foo")` where 'foo' is not a
|
||||
// file path. In this case, we set up `exe_mod` to import `lib_mod`.
|
||||
exe_mod.addImport("zig_lib", lib_mod);
|
||||
|
||||
// Now, we will create a static library based on the module we created above.
|
||||
// This creates a `std.Build.Step.Compile`, which is the build step responsible
|
||||
// for actually invoking the compiler.
|
||||
const lib = b.addLibrary(.{
|
||||
.linkage = .static,
|
||||
.name = "zig",
|
||||
.root_module = lib_mod,
|
||||
});
|
||||
|
||||
// This declares intent for the library to be installed into the standard
|
||||
// location when the user invokes the "install" step (the default step when
|
||||
// running `zig build`).
|
||||
b.installArtifact(lib);
|
||||
|
||||
// This creates another `std.Build.Step.Compile`, but this one builds an executable
|
||||
// rather than a static library.
|
||||
const exe = b.addExecutable(.{
|
||||
.name = "zig",
|
||||
.root_module = exe_mod,
|
||||
});
|
||||
|
||||
// This declares intent for the executable to be installed into the
|
||||
// standard location when the user invokes the "install" step (the default
|
||||
// step when running `zig build`).
|
||||
b.installArtifact(exe);
|
||||
|
||||
// This *creates* a Run step in the build graph, to be executed when another
|
||||
// step is evaluated that depends on it. The next line below will establish
|
||||
// such a dependency.
|
||||
const run_cmd = b.addRunArtifact(exe);
|
||||
|
||||
// By making the run step depend on the install step, it will be run from the
|
||||
// installation directory rather than directly from within the cache directory.
|
||||
// This is not necessary, however, if the application depends on other installed
|
||||
// files, this ensures they will be present and in the expected location.
|
||||
run_cmd.step.dependOn(b.getInstallStep());
|
||||
|
||||
// This allows the user to pass arguments to the application in the build
|
||||
// command itself, like this: `zig build run -- arg1 arg2 etc`
|
||||
if (b.args) |args| {
|
||||
run_cmd.addArgs(args);
|
||||
}
|
||||
|
||||
// This creates a build step. It will be visible in the `zig build --help` menu,
|
||||
// and can be selected like this: `zig build run`
|
||||
// This will evaluate the `run` step rather than the default, which is "install".
|
||||
const run_step = b.step("run", "Run the app");
|
||||
run_step.dependOn(&run_cmd.step);
|
||||
|
||||
// Creates a step for unit testing. This only builds the test executable
|
||||
// but does not run it.
|
||||
const lib_unit_tests = b.addTest(.{
|
||||
.root_module = lib_mod,
|
||||
});
|
||||
|
||||
const run_lib_unit_tests = b.addRunArtifact(lib_unit_tests);
|
||||
|
||||
const exe_unit_tests = b.addTest(.{
|
||||
.root_module = exe_mod,
|
||||
});
|
||||
|
||||
const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests);
|
||||
|
||||
// Similar to creating the run step earlier, this exposes a `test` step to
|
||||
// the `zig build --help` menu, providing a way for the user to request
|
||||
// running the unit tests.
|
||||
const test_step = b.step("test", "Run unit tests");
|
||||
test_step.dependOn(&run_lib_unit_tests.step);
|
||||
test_step.dependOn(&run_exe_unit_tests.step);
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
.{
|
||||
// This is the default name used by packages depending on this one. For
|
||||
// example, when a user runs `zig fetch --save <url>`, this field is used
|
||||
// as the key in the `dependencies` table. Although the user can choose a
|
||||
// different name, most users will stick with this provided value.
|
||||
//
|
||||
// It is redundant to include "zig" in this name because it is already
|
||||
// within the Zig package namespace.
|
||||
.name = .zig,
|
||||
|
||||
// This is a [Semantic Version](https://semver.org/).
|
||||
// In a future version of Zig it will be used for package deduplication.
|
||||
.version = "0.0.0",
|
||||
|
||||
// Together with name, this represents a globally unique package
|
||||
// identifier. This field is generated by the Zig toolchain when the
|
||||
// package is first created, and then *never changes*. This allows
|
||||
// unambiguous detection of one package being an updated version of
|
||||
// another.
|
||||
//
|
||||
// When forking a Zig project, this id should be regenerated (delete the
|
||||
// field and run `zig build`) if the upstream project is still maintained.
|
||||
// Otherwise, the fork is *hostile*, attempting to take control over the
|
||||
// original project's identity. Thus it is recommended to leave the comment
|
||||
// on the following line intact, so that it shows up in code reviews that
|
||||
// modify the field.
|
||||
.fingerprint = 0xc1ce10817981a2b1, // Changing this has security and trust implications.
|
||||
|
||||
// Tracks the earliest Zig version that the package considers to be a
|
||||
// supported use case.
|
||||
.minimum_zig_version = "0.14.1",
|
||||
|
||||
// This field is optional.
|
||||
// Each dependency must either provide a `url` and `hash`, or a `path`.
|
||||
// `zig build --fetch` can be used to fetch all dependencies of a package, recursively.
|
||||
// Once all dependencies are fetched, `zig build` no longer requires
|
||||
// internet connectivity.
|
||||
.dependencies = .{
|
||||
// See `zig fetch --save <url>` for a command-line interface for adding dependencies.
|
||||
//.example = .{
|
||||
// // When updating this field to a new URL, be sure to delete the corresponding
|
||||
// // `hash`, otherwise you are communicating that you expect to find the old hash at
|
||||
// // the new URL. If the contents of a URL change this will result in a hash mismatch
|
||||
// // which will prevent zig from using it.
|
||||
// .url = "https://example.com/foo.tar.gz",
|
||||
//
|
||||
// // This is computed from the file contents of the directory of files that is
|
||||
// // obtained after fetching `url` and applying the inclusion rules given by
|
||||
// // `paths`.
|
||||
// //
|
||||
// // This field is the source of truth; packages do not come from a `url`; they
|
||||
// // come from a `hash`. `url` is just one of many possible mirrors for how to
|
||||
// // obtain a package matching this `hash`.
|
||||
// //
|
||||
// // Uses the [multihash](https://multiformats.io/multihash/) format.
|
||||
// .hash = "...",
|
||||
//
|
||||
// // When this is provided, the package is found in a directory relative to the
|
||||
// // build root. In this case the package's hash is irrelevant and therefore not
|
||||
// // computed. This field and `url` are mutually exclusive.
|
||||
// .path = "foo",
|
||||
//
|
||||
// // When this is set to `true`, a package is declared to be lazily
|
||||
// // fetched. This makes the dependency only get fetched if it is
|
||||
// // actually used.
|
||||
// .lazy = false,
|
||||
//},
|
||||
},
|
||||
|
||||
// Specifies the set of files and directories that are included in this package.
|
||||
// Only files and directories listed here are included in the `hash` that
|
||||
// is computed for this package. Only files listed here will remain on disk
|
||||
// when using the zig package manager. As a rule of thumb, one should list
|
||||
// files required for compilation plus any license(s).
|
||||
// Paths are relative to the build root. Use the empty string (`""`) to refer to
|
||||
// the build root itself.
|
||||
// A directory listed here means that all files within, recursively, are included.
|
||||
.paths = .{
|
||||
"build.zig",
|
||||
"build.zig.zon",
|
||||
"src",
|
||||
// For example...
|
||||
//"LICENSE",
|
||||
//"README.md",
|
||||
},
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
//! zig test project
|
||||
//! this project serves to learn zig and test the behaviour of specific features
|
||||
|
||||
const std = @import("std");
|
||||
const fs = std.fs;
|
||||
const vec = @import("vector.zig");
|
||||
|
||||
pub fn main() !void {
|
||||
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
|
||||
const allocator = gpa.allocator();
|
||||
var test_vector = try vec.vector(u8).new(allocator);
|
||||
|
||||
for (0..12) |n|
|
||||
{
|
||||
try test_vector.push(@truncate(n));
|
||||
}
|
||||
std.debug.print("{X}\n", .{test_vector.array[0..test_vector.length]});
|
||||
|
||||
const blargh: []u8 = try test_vector.drain(.{3, 6});
|
||||
defer allocator.free(blargh);
|
||||
std.debug.print("drained slice: {X}\n", .{blargh});
|
||||
std.debug.print("vector after drain: {X}\n", .{test_vector.array[0..test_vector.length]});
|
||||
}
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
//! By convention, root.zig is the root source file when making a library. If
|
||||
//! you are making an executable, the convention is to delete this file and
|
||||
//! start with main.zig instead.
|
||||
const std = @import("std");
|
||||
const testing = std.testing;
|
||||
|
||||
pub export fn add(a: i32, b: i32) i32 {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
test "basic add functionality" {
|
||||
try testing.expect(add(3, 7) == 10);
|
||||
}
|
||||
@@ -1,150 +0,0 @@
|
||||
const std = @import("std");
|
||||
|
||||
/// return empty instance of `Vector`
|
||||
/// use `new()` or `new_with_capacity()` to
|
||||
/// get an initialised instance of `Vector`
|
||||
pub fn vector(comptime T: type) type
|
||||
{
|
||||
return struct
|
||||
{
|
||||
const Vector: type = @This();
|
||||
const VectorType: type = T;
|
||||
const DEFAULT_SIZE: usize = 16;
|
||||
|
||||
const VectorError: type = error {
|
||||
OutOfBounds,
|
||||
FailedToAllocateMemory,
|
||||
};
|
||||
|
||||
allocator: std.mem.Allocator,
|
||||
array: []VectorType,
|
||||
length: usize,
|
||||
|
||||
/// create new vector with the default capacity
|
||||
///
|
||||
/// returns initialised instance of `Vector`
|
||||
pub fn new(allocator: std.mem.Allocator) !Vector
|
||||
{
|
||||
return Vector
|
||||
{
|
||||
.allocator = allocator,
|
||||
.array = allocator.alloc(VectorType, DEFAULT_SIZE) catch return VectorError.FailedToAllocateMemory,
|
||||
.length = 0,
|
||||
};
|
||||
}
|
||||
|
||||
/// create new vector with the given capacity
|
||||
///
|
||||
/// returns initialised instance of `Vector`
|
||||
pub fn new_with_capacity(allocator: std.mem.Allocator, size: usize) VectorError!Vector
|
||||
{
|
||||
return Vector
|
||||
{
|
||||
.allocator = allocator,
|
||||
.array = allocator.alloc(VectorType, size) catch return VectorError.FailedToAllocateMemory,
|
||||
.length = 0,
|
||||
};
|
||||
}
|
||||
|
||||
/// get the vectors length
|
||||
///
|
||||
/// **note:** length != capacity
|
||||
/// length = number of items in the vector
|
||||
/// capacity = maximum number of items the vector can hold
|
||||
pub fn len(self: *Vector) usize
|
||||
{
|
||||
return self.length;
|
||||
}
|
||||
|
||||
/// get the vectors capacity
|
||||
///
|
||||
/// **note:** length != capacity
|
||||
/// length = number of items in the vector
|
||||
/// capacity = maximum number of items the vector can hold
|
||||
pub fn capacity(self: *Vector) usize
|
||||
{
|
||||
return self.array.len;
|
||||
}
|
||||
|
||||
/// add one item at the end of the vector
|
||||
pub fn push(self: *Vector, item: VectorType) VectorError!void
|
||||
{
|
||||
if (self.length >= self.array.len) try self.double_capacity();
|
||||
|
||||
self.array[self.length] = item;
|
||||
self.length += 1;
|
||||
}
|
||||
|
||||
/// remove and return last item of the vector
|
||||
pub fn pop(self: *Vector) VectorType
|
||||
{
|
||||
self.length -= 1;
|
||||
return self.array[self.length];
|
||||
}
|
||||
|
||||
/// remove and return a range of elements
|
||||
///
|
||||
/// range[0] has to be less than range[1]
|
||||
/// the range bounds are **both** included
|
||||
pub fn drain(self: *Vector, range: [2]usize) VectorError![]VectorType
|
||||
{
|
||||
if (2 != range.len
|
||||
or range[1] <= range[0]
|
||||
or range[0] > self.array.len
|
||||
or range[1] > self.array.len)
|
||||
{
|
||||
return VectorError.OutOfBounds;
|
||||
}
|
||||
|
||||
const slice_length: usize = range[1] - range[0] + 1;
|
||||
const slice: []VectorType = self.allocator.alloc(VectorType, slice_length)
|
||||
catch
|
||||
{
|
||||
return VectorError.FailedToAllocateMemory;
|
||||
};
|
||||
|
||||
// TODO: return array instead of pointer
|
||||
@memcpy(slice.ptr, self.array[range[0]..range[1] + 1]);
|
||||
@memmove(self.array.ptr + range[0], self.array[range[1] + 1..self.length]);
|
||||
self.length -= slice_length;
|
||||
|
||||
return slice;
|
||||
}
|
||||
|
||||
/// add slice of `VectorType` to the end of the vector
|
||||
pub fn extend(self: *Vector, slice: []VectorType) VectorError!void
|
||||
{
|
||||
if (slice.len == 0) return;
|
||||
|
||||
if (slice.len > self.capacity()) {
|
||||
try self.increase_capacity(slice.len + self.capacity());
|
||||
}
|
||||
else if (slice.len > self.capacity() - self.length)
|
||||
{
|
||||
try self.double_capacity();
|
||||
}
|
||||
|
||||
@memcpy(self.array.ptr + self.length, slice);
|
||||
}
|
||||
|
||||
/// double the vectors capacity
|
||||
fn double_capacity(self: *Vector) VectorError!void
|
||||
{
|
||||
try self.increase_capacity(2 * self.capacity());
|
||||
}
|
||||
|
||||
/// increase the vectors capacity to given size
|
||||
fn increase_capacity(self: *Vector, size: usize) VectorError!void
|
||||
{
|
||||
const new_buffer: []VectorType = self.allocator.alloc(VectorType, size)
|
||||
catch
|
||||
{
|
||||
return VectorError.FailedToAllocateMemory;
|
||||
};
|
||||
@memcpy(new_buffer, self.array);
|
||||
self.allocator.free(self.array);
|
||||
self.array = new_buffer;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user