Compare commits

..

46 Commits

Author SHA1 Message Date
scbj 90fc9cac0d (clang) array initialisation test, -Wno-maybe-uninitialized! 2026-06-16 14:30:20 +02:00
scbj 4c79d20fb2 (make) rule expansion, or double colon rules 2026-06-10 09:11:29 +02:00
scbj 4cf6c18b81 (bash) dirname/basename with variable expansion 2026-06-01 09:30:21 +02:00
zegonix 607543767b (bash) handling arrays of paths 2026-05-29 09:37:06 +02:00
zegonix 5cc74596cc added GPLv2 license 2026-04-20 10:03:54 +02:00
root d1749b61da (bash) adding suffix to each element of an array 2026-04-13 09:22:21 +02:00
scbj fc655cd6ad (graphviz) initial testing 2026-04-10 09:40:36 +02:00
root 118fcef730 (bash) arrays are weird 2026-02-19 23:47:58 +01:00
scbj 7477a1dc37 (bash) test tput to format text output 2026-02-03 15:43:18 +01:00
scbj 0f7acf58e7 (clang) tested array initialisation in 2026-02-03 10:02:31 +01:00
scbj ac3fa61211 (clang) added targets rebuild and run 2026-02-03 10:02:24 +01:00
root 8bc0c27ab2 (bash) robust way to get path to script 2026-01-29 15:06:39 +01:00
scbj faecef25ce (clang) renamed C project to clang 2026-01-09 14:01:23 +01:00
scbj a08e7d979c (clang) const void* const pointer confusion 2026-01-09 14:00:32 +01:00
scbj 56a7cb865a (clang) added project for C 2026-01-09 14:00:28 +01:00
scbj cb463b0207 (rust) temperature type and conversions 2025-11-26 14:55:39 +01:00
scbj 5900789ce4 (zig) extended vector.rs 2025-10-06 21:33:33 +02:00
scbj 42f5119f42 (zig) fixed output of vector.drain() 2025-10-06 15:25:34 +02:00
root f7d6c7c902 (zig) started implementing vector type 2025-10-05 23:28:58 +02:00
scbj 52365e7b08 (rust) get tcpstream peer address 2025-09-23 10:40:28 +02:00
scbj 28a1d3dada (rust) **very** basic restapi with axum 2025-09-18 10:39:50 +02:00
scbj 1e7c7d7cba (rust) removed obsolete code 2025-09-18 08:56:48 +02:00
scbj 8749cbdad7 (rust) macaddress type tests 2025-09-08 16:13:23 +02:00
root e34990fc31 (zig) read and write files 2025-09-08 16:11:46 +02:00
scbj 34ec866782 (rust) tcpstream io with vectors 2025-09-08 15:55:52 +02:00
scbj cd7b47d3e7 (rust) tested communcication over tcp with cobs and cbor 2025-07-31 16:15:49 +02:00
scbj 462d45ffd0 (rust) started another cobs test 2025-07-31 16:15:43 +02:00
scbj f5a20d500e (zig) filesystem tests 2025-07-18 16:54:09 +02:00
scbj 753163d28e (zig) added symbolic link to executable 2025-07-18 10:07:15 +02:00
scbj e5a338ae64 (rust) tested cobs crate 2025-07-18 10:06:09 +02:00
scbj 860fed5810 (zig) added test project for zig 2025-07-10 09:59:17 +02:00
root 1d3c3b1930 (rust) ciborium! 2025-07-07 14:50:20 +02:00
scbj b02682ab70 (rust) quick serde/json tryout 2025-07-04 14:52:37 +02:00
scbj b86e403814 (rust) reading interface addresses 2025-06-26 08:51:31 +02:00
root 1acb77331b (rust) PathBuf push() behaviour 2025-06-24 19:26:51 +02:00
scbj 2b52a3d949 (bash) test on behaviour of sourcing 2025-06-23 10:55:58 +02:00
scbj 9b426e85e0 (bash) renamed bash test file to bash-test.sh .. 2025-06-23 10:53:25 +02:00
scbj a545b29f03 (rust) prost: test of protobuf en/decoding and transmission via tcp 2025-06-03 15:50:25 +02:00
scbj a7d09cb062 (rust) prost: added simple protobuf sample for testing 2025-06-02 16:05:05 +02:00
root 4933c7dd14 added small-lorem.md with one paragraph for quick debugging of shell
commands
2025-05-29 16:37:18 +02:00
root 954c450b7e (rust) file transfer via tcp
added lorem.md for tests
2025-05-20 13:46:46 +02:00
root 705aea3ba9 (rust) sending files via tcp 2025-05-20 13:46:42 +02:00
scbj 5ce940c8b9 (rust) sqlx: inserted a rust type and sql column for the log type 2025-05-20 12:23:13 +02:00
scbj 3dc3d46a21 (rust) sqlx tests for armasuisse 2025-05-15 15:35:13 +02:00
root d1297d6e83 (rust) very basic command handler 2025-04-29 10:46:08 +02:00
root 115cc27152 initial commit 2025-04-29 08:51:10 +02:00
23 changed files with 2054 additions and 3 deletions
-3
View File
@@ -1,3 +0,0 @@
# test-projects
projects to test specific features of programming languages
Executable
+6
View File
@@ -0,0 +1,6 @@
#!/usr/bin/env bash
path="$(realpath "${BASH_SOURCE}")"
echo "path: ${path%/*}"
echo "file: ${path##*/}"
+13
View File
@@ -0,0 +1,13 @@
bin/
*.o
*.pdf
*.a
*.so
*.tar
*.zip
*.xz
*.gz
+66
View File
@@ -0,0 +1,66 @@
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 $@
+17
View File
@@ -0,0 +1,17 @@
#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] );
}
}
+1380
View File
File diff suppressed because it is too large Load Diff
+3
View File
@@ -0,0 +1,3 @@
clean::
echo "AAAA"
+3
View File
@@ -0,0 +1,3 @@
clean::
echo "BBBB"
+9
View File
@@ -0,0 +1,9 @@
SHELL := /usr/bin/env bash
.PHONY: all clean test
clean::
echo "blargh"
include ./a.mk
include ./b.mk
+4
View File
@@ -0,0 +1,4 @@
target
Cargo.lock
test*
log.db*
+18
View File
@@ -0,0 +1,18 @@
[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
View File
@@ -0,0 +1 @@
target/debug/rust
+1
View File
@@ -0,0 +1 @@
stable
+115
View File
@@ -0,0 +1,115 @@
#![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(())
}
}
+16
View File
@@ -0,0 +1,16 @@
# 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.
+10
View File
@@ -0,0 +1,10 @@
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
}
+2
View File
@@ -0,0 +1,2 @@
zig-out
.zig-cache
Symlink
+1
View File
@@ -0,0 +1 @@
zig-out/bin/zig
+116
View File
@@ -0,0 +1,116 @@
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);
}
+86
View File
@@ -0,0 +1,86 @@
.{
// 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",
},
}
+24
View File
@@ -0,0 +1,24 @@
//! 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]});
}
+13
View File
@@ -0,0 +1,13 @@
//! 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);
}
+150
View File
@@ -0,0 +1,150 @@
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;
}
};
}