Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos
repos/asdf-zig/README.md
# asdf-zig [Zig](https://ziglang.org) plugin for asdf version manager ## Installation First install [asdf](https://asdf-vm.com/guide/getting-started.html) ```bash git clone https://github.com/asdf-vm/asdf.git ~/.asdf --branch v0.14.0 cat <<'EOF' >> $HOME/.bashrc source "$HOME/.asdf/asdf.sh" source "$HOME/.asdf/completions/asdf.bash" EOF ``` Then install asdf-zig ```bash asdf plugin-add zig https://github.com/zigcc/asdf-zig.git ``` Then install latest Zig ```bash asdf install zig latest asdf global zig latest zig version ``` ## Usage Check [asdf](https://github.com/asdf-vm/asdf) readme for instructions on how to install & manage versions. ## License Licensed under the [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0).
0
repos/asdf-zig
repos/asdf-zig/lib/json.bash
#!/usr/bin/env bash # JSON parsing stolen from https://github.com/dominictarr/JSON.sh set +u throw() { echo "$*" >&2 exit 1 } awk_egrep() { local pattern_string=$1 gawk '{ while ($0) { start=match($0, pattern); token=substr($0, start, RLENGTH); print token; $0=substr($0, start+RLENGTH); } }' pattern="$pattern_string" } json_tokenize() { local GREP local ESCAPE local CHAR if echo "test string" | egrep -ao --color=never "test" >/dev/null 2>&1; then GREP='egrep -ao --color=never' else GREP='egrep -ao' fi if echo "test string" | egrep -o "test" >/dev/null 2>&1; then ESCAPE='(\\[^u[:cntrl:]]|\\u[0-9a-fA-F]{4})' CHAR='[^[:cntrl:]"\\]' else GREP=awk_egrep ESCAPE='(\\\\[^u[:cntrl:]]|\\u[0-9a-fA-F]{4})' CHAR='[^[:cntrl:]"\\\\]' fi local STRING="\"$CHAR*($ESCAPE$CHAR*)*\"" local NUMBER='-?(0|[1-9][0-9]*)([.][0-9]*)?([eE][+-]?[0-9]*)?' local KEYWORD='null|false|true' local SPACE='[[:space:]]+' # Force zsh to expand $A into multiple words local is_wordsplit_disabled=$(unsetopt 2>/dev/null | grep -c '^shwordsplit$') if [ $is_wordsplit_disabled != 0 ]; then setopt shwordsplit; fi $GREP "$STRING|$NUMBER|$KEYWORD|$SPACE|." | egrep -v "^$SPACE$" if [ $is_wordsplit_disabled != 0 ]; then unsetopt shwordsplit; fi } json_parse_array() { local index=0 local ary='' read -r token case "$token" in ']') ;; *) while :; do json_parse_value "$1" "$index" index=$((index + 1)) ary="$ary""$value" read -r token case "$token" in ']') break ;; ',') ary="$ary," ;; *) fail "EXPECTED , or ] GOT ${token:-EOF}" ;; esac read -r token done ;; esac value=$(printf '[%s]' "$ary") } json_parse_object() { local key local obj='' read -r token case "$token" in '}') ;; *) while :; do case "$token" in '"'*'"') key=$token ;; *) fail "EXPECTED string GOT ${token:-EOF}" ;; esac read -r token case "$token" in ':') ;; *) fail "EXPECTED : GOT ${token:-EOF}" ;; esac read -r token json_parse_value "$1" "$key" obj="$obj$key:$value" read -r token case "$token" in '}') break ;; ',') obj="$obj," ;; *) fail "EXPECTED , or } GOT ${token:-EOF}" ;; esac read -r token done ;; esac value=$(printf '{%s}' "$obj") : } json_parse_value() { local jpath="${1:+$1,}$2" case "$token" in '{') json_parse_object "$jpath" ;; '[') json_parse_array "$jpath" ;; # At this point, the only valid single-character tokens are digits. '' | [!0-9]) fail "EXPECTED value GOT ${token:-EOF}" ;; # value with solidus ("\/") replaced in json strings with normalized value: "/" *) value=$(echo "$token" | sed 's#\\/##g') ;; esac [ "$value" = '' ] && return printf "[%s]\t%s\n" "$jpath" "$value" : } json_parse() { json="$1" [ -z "$json" ] && return echo "$json" | json_tokenize | ( read -r token json_parse_value read -r token ) case "$token" in '') ;; *) fail "EXPECTED EOF GOT $token" ;; esac }
0
repos
repos/nix-zig-stdenv/default.nix
{ pkgs ? import <nixpkgs> {}, lib ? pkgs.lib, config ? {}, overlays ? [], crossOverlays ? [], zig ? pkgs.zig, utils ? import ./src/utils.nix { inherit lib; }, target ? builtins.currentSystem, static ? utils.supportsStatic target, without-libc ? false, ... } @args: with lib; let localSystem = pkgs.buildPlatform; crossSystem = if isAttrs target then utils.elaborate target else utils.targetToNixSystem target static; config = (args.config or {}) // { allowUnsupportedSystem = localSystem.config != crossSystem.config; }; wrapper = import ./src/wrapper.nix { inherit lib; inherit (pkgs) writeShellScript symlinkJoin; }; rust-wrapper = import ./src/rust-support.nix { inherit lib wrapper static; inherit (pkgs) writeShellScript; }; prebuilt = import ./src/prebuilt.nix { inherit pkgs crossSystem; }; mk-zig-toolchain = import ./src/toolchain.nix { inherit (pkgs) writeShellScript emptyFile gnugrep coreutils; inherit (pkgs.llvmPackages) llvm; inherit localSystem utils lib zig; }; # First native zig toolchain native-toolchain = mk-zig-toolchain { inherit (pkgs) wrapCCWith wrapBintoolsWith; inherit (pkgs.stdenvNoCC) mkDerivation; inherit (pkgs.stdenv.cc) libc; targetSystem = localSystem; targetPkgs = pkgs; }; libc = let # For compiling libc from scratch # Not used if there's prebuilt libc available cross0 = (import pkgs.path { inherit localSystem crossSystem config; stdenvStages = import ./src/stdenv.nix { inherit (pkgs) path; inherit mk-zig-toolchain native-toolchain; }; }).pkgs; lib = { msvcrt = null; libSystem = null; wasilibc = null; musl = prebuilt.dynamic.musl or (cross0.musl.overrideAttrs(o: { outputs = [ "out" ]; CFLAGS = []; # -fstrong-stack-protection is not allowed separateDebugInfo = false; postInstall = "ln -rs $out/lib/libc.so $out/lib/libc.musl-${crossSystem.parsed.cpu.name}.so.1"; })); # XXX: glibc does not compile with anything else than GNU tools while you can compile to # glibc platforms, you won't be able to execute cross-compiled binaries inside a # qemu-static-user environment for example glibc = prebuilt.dynamic.glibc or null; }; in if without-libc || !crossSystem?libc then null else lib."${crossSystem.libc}" or (throw "Could not understand the required libc for target: ${target}"); # Used to compile and install compatibility packages targetPkgs = import pkgs.path { inherit localSystem crossSystem config; stdenvStages = import ./src/stdenv.nix { inherit (pkgs) path; inherit mk-zig-toolchain native-toolchain libc; }; }; cross-env = import pkgs.path { inherit localSystem crossSystem config; stdenvStages = import ./src/stdenv.nix { inherit (pkgs) path; inherit mk-zig-toolchain native-toolchain targetPkgs libc; }; overlays = [(self: super: { rust = rust-wrapper super.rust native-toolchain localSystem.config super.stdenv.cc crossSystem.config; })] ++ overlays; # TODO: check the fixes here # TODO: test for every issue crossOverlays = [(self: super: { # XXX: broken on aarch64 at least gmp = super.gmp.overrideAttrs (old: { configureFlags = old.configureFlags ++ [ "--disable-assembly" ]; }); # XXX: libsepol issue on darwin, should be fixed upstream instead libsepol = super.libsepol.overrideAttrs (old: { nativeBuildInputs = with pkgs; old.nativeBuildInputs ++ optionals (stdenv.isDarwin) [ (writeShellScriptBin "gln" ''${coreutils}/bin/ln "$@"'') ]; }); })] ++ crossOverlays; }; in { inherit static; inherit (cross-env) stdenv; target = crossSystem.config; pkgs = cross-env; wrapRustToolchain = toolchain: rust-wrapper toolchain native-toolchain localSystem.config cross-env.stdenv.cc crossSystem.config; experimental = { inherit prebuilt; }; }
0
repos
repos/nix-zig-stdenv/overlay.nix
{ zig ? null, static ? true, allowBroken ? false } @args: with builtins; pkgs: super: with pkgs.lib; let utils = import ./src/utils.nix { inherit (pkgs) lib; }; versions = import ./versions.nix { inherit pkgs; }; zig = if args ? zig then args.zig else super.zig; gen-targets = zig: let zig-targets = with pkgs; (fromJSON (readFile (runCommandLocal "targets" {} ''${zig}/bin/zig targets > $out''))).libc; broken = [ # Not supported by nixpkgs/systems/parse.nix "csky-unknown-linux-gnueabi" "csky-unknown-linux-gnueabihf" "x86_64-unknown-linux-gnux32" "armeb-unknown-linux-gnueabi" "armeb-unknown-linux-musleabi" "armeb-unknown-linux-gnueabihf" "armeb-unknown-linux-musleabihf" "armeb-w64-mingw32" ]; in filter (x: !(any (y: x == y) broken)) (map utils.zigTargetToNixTarget zig-targets); gen-cross = zig: let broken-targets = let version = if zig.isMasterBuild then "master" else zig.version; in with pkgs; (fromJSON (readFile ./meta/broken-targets.json))."${version}" or []; broken = [] ++ optionals (!allowBroken) (broken-targets); targets = gen-targets zig; static-targets = map (t: "${t}-static") (filter utils.supportsStatic targets); import-target = target: let set = (import ./default.nix { inherit pkgs zig; inherit (pkgs) config overlays; static = hasSuffix "-static" target; target = removeSuffix "-static" target; }); in { inherit (set) pkgs; }; in genAttrs (filter (x: !(any (y: x == y) broken)) (targets ++ static-targets)) import-target; in { zigCross = gen-cross zig; zigVersions = mapAttrs (k: v: { zig = v; targets = gen-cross v; }) (versions // { default = super.zig; }); }
0
repos
repos/nix-zig-stdenv/README.md
# Zig based cross-compiling toolchain ## Major known issues: - Zig seems to randomly fail with parallel builds with 'error: unable to build ... CRT file: BuildingLibCObjectFailed' This seems like race condition with the cache? https://github.com/ziglang/zig/issues/13160 https://github.com/ziglang/zig/issues/9711 - Rust and zig fight for the ownership of libcompiler_rt https://github.com/ziglang/zig/issues/5320 ## Why zig for cross-compiling? Zig can cross-compile out of the box to many target without having to bootstrap the whole cross-compiler and various libcs This means builds are very fast # TODO - Generate meta.json with github actions - Rank zig versions and targets depending how well they do in tests - Provide `zigPkgs` set with packages maintained in this repo - Packages that need major restructuring to compile - Minimal versions of existing packages (we are mostly interested in libs only) - Packages that do not exist yet in nixpkgs - Namespaced for different platforms (c, rust, etc...) - Generally zigPkgs is expected to compile and work while pkgs from nixpkg can be hit and miss For other stuff, run `things-to-do`
0
repos
repos/nix-zig-stdenv/versions.nix
{ pkgs ? import <nixpkgs> {}, lib ? pkgs.lib, stdenv ? pkgs.stdenvNoCC, system ? builtins.currentSystem }: with lib; with builtins; let zig-system = concatStringsSep "-" (map (x: if x == "darwin" then "macos" else x) (splitString "-" system)); in filterAttrs (n: v: v != null) (mapAttrs (k: v: let res = v."${zig-system}" or null; in if res == null then null else stdenv.mkDerivation { pname = "zig"; version = if k == "master" then v.version else k; src = pkgs.fetchurl { url = res.tarball; sha256 = res.shasum; }; dontConfigure = true; dontBuild = true; dontFixup = true; installPhase = '' mkdir -p $out/{doc,bin,lib} [[ -d docs ]] && cp -r docs/* $out/doc [[ -d doc ]] && cp -r doc/* $out/doc cp -r lib/* $out/lib install -Dm755 zig $out/bin/zig ''; passthru = { isMasterBuild = k == "master"; release-date = v.date; release-notes = v.notes; stdDocs = v.stdDocs or null; docs = v.docs; size = res.size; src = v.src; }; meta = with lib; { homepage = "https://ziglang.org/"; description = "General-purpose programming language and toolchain for maintaining robust, optimal, and reusable software"; license = licenses.mit; platforms = platforms.unix; }; }) (fromJSON (readFile ./meta/versions.json)))
0
repos
repos/nix-zig-stdenv/flake.nix
{ description = "nix-zig stdenv"; inputs = { nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable"; flake-utils.url = "github:numtide/flake-utils"; }; outputs = { nixpkgs, flake-utils, ... }: let systems = [ "x86_64-linux" "aarch64-linux" "x86_64-darwin" "aarch64-darwin" ]; outputs = flake-utils.lib.eachSystem systems (system: let pkgs = nixpkgs.legacyPackages.${system}; in rec { env = args: import ./default.nix (args // { inherit pkgs; }); versions = import ./versions.nix { inherit system pkgs; }; apps.zig = flake-utils.lib.mkApp { drv = versions.master; }; apps.default = apps.zig; }); in outputs // { overlays.default = final: prev: { versions = outputs.versions; }; }; }
0
repos
repos/nix-zig-stdenv/flake.lock
{ "nodes": { "flake-utils": { "inputs": { "systems": "systems" }, "locked": { "lastModified": 1701680307, "narHash": "sha256-kAuep2h5ajznlPMD9rnQyffWG8EM/C73lejGofXvdM8=", "owner": "numtide", "repo": "flake-utils", "rev": "4022d587cbbfd70fe950c1e2083a02621806a725", "type": "github" }, "original": { "owner": "numtide", "repo": "flake-utils", "type": "github" } }, "nixpkgs": { "locked": { "lastModified": 1702539185, "narHash": "sha256-KnIRG5NMdLIpEkZTnN5zovNYc0hhXjAgv6pfd5Z4c7U=", "owner": "NixOS", "repo": "nixpkgs", "rev": "aa9d4729cbc99dabacb50e3994dcefb3ea0f7447", "type": "github" }, "original": { "owner": "NixOS", "ref": "nixpkgs-unstable", "repo": "nixpkgs", "type": "github" } }, "root": { "inputs": { "flake-utils": "flake-utils", "nixpkgs": "nixpkgs" } }, "systems": { "locked": { "lastModified": 1681028828, "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", "owner": "nix-systems", "repo": "default", "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", "type": "github" }, "original": { "owner": "nix-systems", "repo": "default", "type": "github" } } }, "root": "root", "version": 7 }
0
repos/nix-zig-stdenv
repos/nix-zig-stdenv/sketchpad/default.nix
{ pkgs ? import <nixpkgs> {}, stdenv ? pkgs.stdenvNoCC, lib ? pkgs.lib, utils ? import ../src/utils.nix { inherit lib; }, target ? builtins.currentSystem, static ? utils.supportsStatic target, without-libc ? false, zig-version ? "0.10.0", ... } @args: with lib; with builtins; let # for rust naersk-for-zig = zig: let cross = import ./.. { inherit pkgs zig target static; }; fenix = import (fetchTarball "https://github.com/nix-community/fenix/archive/5fe1e430e990d5b0715f82dbd8b6c0cb7086c7e1.tar.gz") {}; rust-toolchain = with fenix; combine [ minimal.rustc minimal.cargo targets.${cross.target}.latest.rust-std ]; naersk = import (pkgs.fetchFromGitHub { owner = "nix-community"; repo = "naersk"; rev = "6944160c19cb591eb85bbf9b2f2768a935623ed3"; hash = "sha256-9o2OGQqu4xyLZP9K6kNe1pTHnyPz0Wr3raGYnr9AIgY="; }) { inherit (cross) stdenv; inherit (pkgs) darwin fetchurl jq lib remarshal rsync runCommandLocal writeText zstd; inherit (pkgs.xorg) lndir; cargo = cross.wrapRustToolchain rust-toolchain; rustc = cross.wrapRustToolchain rust-toolchain; }; in naersk; # defaults zig = (import ../versions.nix {})."${zig-version}"; cross = import ./.. { inherit pkgs zig target static without-libc; }; buildRustPackage = (naersk-for-zig zig).buildPackage; in { # minimal glib, the default in nixpkgs is quite large and needs a lot of stuff glib = import ./glib { inherit pkgs cross; }; # NOTE: this only supports aarch64 target for now (only musl is tested!) # NOTE: cross-compiling `rusty-v8` needs `qemu-binfmt` setup so that you can execute the build time binaries # XXX: investigate if the crackjob GN build environment can be made to cross-compile without qemu-binfmt # or if we can compile the build time tools it needs beforehand without it knowing rusty-v8 = import ./rusty-v8 { inherit pkgs cross buildRustPackage glib; }; # if you want to compile with `rusty-v8` derivation above, use `--arg with-rusty-v8 true` # otherwise you need to add the `librusty_v8-aarch64-unknown-linux-musl.a` to your nix store, # by running: `nix store add-file librusty_v8-aarch64-unknown-linux-musl.a` # NOTE: on linux you may have to build with `--argstr zig-version 0.8.1` deno-core-hello-world = let prebuilt = storePath /nix/store/v6a39mcfnijv11d05m77y4qpbkxr8ay3-librusty_v8-aarch64-unknown-linux-musl.a; artifact = "${rusty-v8}/lib/librusty_v8.a"; in import ./rusty-v8/hello.nix { inherit pkgs buildRustPackage; librusty-v8 = if args ? with-rusty-v8 && args.with-rusty-v8 then artifact else prebuilt; }; }
0
repos/nix-zig-stdenv
repos/nix-zig-stdenv/sketchpad/README.md
# What's this? Nix derivations for building packages that are yet experimental, do not build on every platform or needs some external factors to help building like qemu-binfmt ## Can I put my stuff here? Sure
0
repos/nix-zig-stdenv/sketchpad
repos/nix-zig-stdenv/sketchpad/rusty-v8/default.nix
{ pkgs, cross, buildRustPackage, glib, lib ? pkgs.lib, stdenv ? pkgs.stdenvNoCC }: with lib; assert cross.stdenv.targetPlatform.isAarch64; let gn-ninja = rec { version = "20220517"; src = fetchTarball { url = "https://github.com/denoland/ninja_gn_binaries/archive/${version}.tar.gz"; }; gn = stdenv.mkDerivation { inherit version src; name = "gn"; dontPatch = true; dontConfigure = true; dontBuild = true; nativeBuildInputs = with pkgs; [ autoPatchelfHook ]; installPhase = if stdenv.isLinux then "install -Dm 755 linux64/gn $out/bin/gn" else "install -Dm 755 mac/gn $out/bin/gn"; meta = with lib; { description = "A meta-build system that generates build files for Ninja"; homepage = "https://gn.googlesource.com/gn"; license = licenses.bsd3; platforms = [ "x86_64-linux" "x86_64-darwin" "aarch64-darwin" ]; }; }; ninja = stdenv.mkDerivation { inherit version src; name = "ninja"; dontPatch = true; dontConfigure = true; dontBuild = true; nativeBuildInputs = with pkgs.buildPackages; [ autoPatchelfHook ] ++ optionals (stdenv.isLinux) [ gcc.cc.lib ]; # libstdc++.so.6 installPhase = if stdenv.isLinux then "install -Dm 755 linux64/ninja $out/bin/ninja" else "install -Dm 755 mac/ninja $out/bin/ninja"; meta = with lib; { description = "Small build system with a focus on speed"; homepage = "https://ninja-build.org/"; license = licenses.asl20; platforms = [ "x86_64-linux" "x86_64-darwin" "aarch64-darwin" ]; }; }; }; rusty = { name = "rusty_v8"; version = "0.53.1"; clang = pkgs.runCommandLocal "clang" {} '' mkdir -p $out/bin ln -s ${cross.stdenv.cc}/bin/${cross.target}-cc $out/bin/clang ln -s ${cross.stdenv.cc}/bin/${cross.target}-c++ $out/bin/clang++ ln -s ${cross.stdenv.cc}/bin/${cross.target}-ar $out/bin/llvm-ar ''; }; in buildRustPackage { inherit (rusty) name version; src = pkgs.fetchFromGitHub { owner = "denoland"; repo = rusty.name; rev = "v${rusty.version}"; sha256 = "sha256-QKriAHAS6Egq7KdwKQmmhSm1u765W5qPngd2X4DHcQM="; fetchSubmodules = true; }; copyTarget = false; copyBins = false; nativeBuildInputs = with pkgs.buildPackages; [ python3 gn-ninja.gn gn-ninja.ninja pkg-config ]; buildInputs = [ glib ]; V8_FROM_SOURCE = true; # TODO: this needs to be mapped GN_ARGS = ''target_os="linux" target_cpu="arm64" use_custom_libcxx=false is_clang=true v8_snapshot_toolchain="//build/toolchain/linux/unbundle:default"''; # XXX: zig cc doesn't handle some CLI arguments CLANG_BASE_PATH = rusty.clang; NIX_DEBUG = 1; postInstall = '' mkdir -p $out/lib cp target/${cross.target}/release/gn_out/obj/librusty_v8.a $out/lib/librusty_v8.a ''; }
0
repos/nix-zig-stdenv/sketchpad
repos/nix-zig-stdenv/sketchpad/rusty-v8/hello.nix
{ pkgs, librusty-v8, buildRustPackage, lib ? pkgs.lib, stdenv ? pkgs.stdenvNoCC }: with lib; with builtins; let nix-filter = import (pkgs.fetchFromGitHub { owner = "numtide"; repo = "nix-filter"; rev = "3b821578685d661a10b563cba30b1861eec05748"; hash = "sha256-RizGJH/buaw9A2+fiBf9WnXYw4LZABB5kMAZIEE5/T8="; }); in buildRustPackage rec { name = "deno-core-hello-world"; pname = name; stripAllList = [ "bin" ]; src = nix-filter { root = ./deno-core-hello-world; include = [ ./deno-core-hello-world/src ./deno-core-hello-world/Cargo.toml ./deno-core-hello-world/Cargo.lock ]; }; RUSTY_V8_ARCHIVE = librusty-v8; NIX_CFLAGS_COMPILE = [ "-lc++" librusty-v8 ]; }
0
repos/nix-zig-stdenv/sketchpad/rusty-v8
repos/nix-zig-stdenv/sketchpad/rusty-v8/deno-core-hello-world/Cargo.lock
# This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "aho-corasick" version = "0.7.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4f55bd91a0978cbfd91c457a164bab8b4001c833b7f323132c0a4e1922dd44e" dependencies = [ "memchr", ] [[package]] name = "anyhow" version = "1.0.66" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "216261ddc8289130e551ddcd5ce8a064710c0d064a4d2895c67151c92b5443f6" [[package]] name = "autocfg" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "base64" version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" [[package]] name = "bitflags" version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bytes" version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec8a7b6a70fde80372154c65702f00a0f56f3e1c36abbc6c440484be248856db" [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "convert_case" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" [[package]] name = "deno-core-hello-world" version = "0.1.0" dependencies = [ "deno_core", ] [[package]] name = "deno_core" version = "0.156.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9157c30bd82f4e4feca1b19786554dace4ebdaf0f61e8ee25bce8c966c7d97c7" dependencies = [ "anyhow", "bytes", "deno_ops", "futures", "indexmap", "libc", "log", "once_cell", "parking_lot", "pin-project", "serde", "serde_json", "serde_v8", "sourcemap", "url", "v8", ] [[package]] name = "deno_ops" version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b29fb7131fc319533e89b3fd3100409927295c15d05bfd212cbbbbc18182dc0" dependencies = [ "once_cell", "proc-macro-crate", "proc-macro2", "quote", "regex", "syn", ] [[package]] name = "derive_more" version = "0.99.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4fb810d30a7c1953f91334de7244731fc3f3c10d7fe163338a35b9f640960321" dependencies = [ "convert_case", "proc-macro2", "quote", "rustc_version 0.4.0", "syn", ] [[package]] name = "either" version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "90e5c1c8368803113bf0c9584fc495a58b86dc8a29edbf8fe877d21d9507e797" [[package]] name = "form_urlencoded" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a9c384f161156f5260c24a097c56119f9be8c798586aecc13afbcbe7b7e26bf8" dependencies = [ "percent-encoding", ] [[package]] name = "fslock" version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57eafdd0c16f57161105ae1b98a1238f97645f2f588438b2949c99a2af9616bf" dependencies = [ "libc", "winapi", ] [[package]] name = "futures" version = "0.3.25" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "38390104763dc37a5145a53c29c63c1290b5d316d6086ec32c293f6736051bb0" dependencies = [ "futures-channel", "futures-core", "futures-executor", "futures-io", "futures-sink", "futures-task", "futures-util", ] [[package]] name = "futures-channel" version = "0.3.25" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "52ba265a92256105f45b719605a571ffe2d1f0fea3807304b522c1d778f79eed" dependencies = [ "futures-core", "futures-sink", ] [[package]] name = "futures-core" version = "0.3.25" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04909a7a7e4633ae6c4a9ab280aeb86da1236243a77b694a49eacd659a4bd3ac" [[package]] name = "futures-executor" version = "0.3.25" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7acc85df6714c176ab5edf386123fafe217be88c0840ec11f199441134a074e2" dependencies = [ "futures-core", "futures-task", "futures-util", ] [[package]] name = "futures-io" version = "0.3.25" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00f5fb52a06bdcadeb54e8d3671f8888a39697dcb0b81b23b55174030427f4eb" [[package]] name = "futures-macro" version = "0.3.25" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bdfb8ce053d86b91919aad980c220b1fb8401a9394410e1c289ed7e66b61835d" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "futures-sink" version = "0.3.25" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39c15cf1a4aa79df40f1bb462fb39676d0ad9e366c2a33b590d7c66f4f81fcf9" [[package]] name = "futures-task" version = "0.3.25" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2ffb393ac5d9a6eaa9d3fdf37ae2776656b706e200c8e16b1bdb227f5198e6ea" [[package]] name = "futures-util" version = "0.3.25" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "197676987abd2f9cadff84926f410af1c183608d36641465df73ae8211dc65d6" dependencies = [ "futures-channel", "futures-core", "futures-io", "futures-macro", "futures-sink", "futures-task", "memchr", "pin-project-lite", "pin-utils", "slab", ] [[package]] name = "hashbrown" version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" [[package]] name = "idna" version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e14ddfc70884202db2244c223200c204c2bda1bc6e0998d11b5e024d657209e6" dependencies = [ "unicode-bidi", "unicode-normalization", ] [[package]] name = "if_chain" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cb56e1aa765b4b4f3aadfab769793b7087bb03a4ea4920644a6d238e2df5b9ed" [[package]] name = "indexmap" version = "1.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1885e79c1fc4b10f0e172c475f458b7f7b93061064d98c3293e98c5ba0c8b399" dependencies = [ "autocfg", "hashbrown", ] [[package]] name = "itoa" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4217ad341ebadf8d8e724e264f13e593e0648f5b3e94b3896a5df283be015ecc" [[package]] name = "lazy_static" version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" [[package]] name = "libc" version = "0.2.137" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc7fcc620a3bff7cdd7a365be3376c97191aeaccc2a603e600951e452615bf89" [[package]] name = "lock_api" version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "435011366fe56583b16cf956f9df0095b405b82d76425bc8981c0e22e60ec4df" dependencies = [ "autocfg", "scopeguard", ] [[package]] name = "log" version = "0.4.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" dependencies = [ "cfg-if", ] [[package]] name = "memchr" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" [[package]] name = "once_cell" version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "86f0b0d4bf799edbc74508c1e8bf170ff5f41238e5f8225603ca7caaae2b7860" [[package]] name = "parking_lot" version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f" dependencies = [ "lock_api", "parking_lot_core", ] [[package]] name = "parking_lot_core" version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4dc9e0dc2adc1c69d09143aff38d3d30c5c3f0df0dad82e6d25547af174ebec0" dependencies = [ "cfg-if", "libc", "redox_syscall", "smallvec", "windows-sys", ] [[package]] name = "percent-encoding" version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "478c572c3d73181ff3c2539045f6eb99e5491218eae919370993b890cdbdd98e" [[package]] name = "pin-project" version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ad29a609b6bcd67fee905812e544992d216af9d755757c05ed2d0e15a74c6ecc" dependencies = [ "pin-project-internal", ] [[package]] name = "pin-project-internal" version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "069bdb1e05adc7a8990dce9cc75370895fbe4e3d58b9b73bf1aee56359344a55" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "pin-project-lite" version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116" [[package]] name = "pin-utils" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" [[package]] name = "proc-macro-crate" version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eda0fc3b0fb7c975631757e14d9049da17374063edb6ebbcbc54d880d4fe94e9" dependencies = [ "once_cell", "thiserror", "toml", ] [[package]] name = "proc-macro2" version = "1.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" dependencies = [ "proc-macro2", ] [[package]] name = "redox_syscall" version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" dependencies = [ "bitflags", ] [[package]] name = "regex" version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e076559ef8e241f2ae3479e36f97bd5741c0330689e217ad51ce2c76808b868a" dependencies = [ "aho-corasick", "memchr", "regex-syntax", ] [[package]] name = "regex-syntax" version = "0.6.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "456c603be3e8d448b072f410900c09faf164fbce2d480456f50eea6e25f9c848" [[package]] name = "rustc_version" version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" dependencies = [ "semver 0.9.0", ] [[package]] name = "rustc_version" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" dependencies = [ "semver 1.0.14", ] [[package]] name = "ryu" version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4501abdff3ae82a1c1b477a17252eb69cee9e66eb915c1abaa4f44d873df9f09" [[package]] name = "scopeguard" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" [[package]] name = "semver" version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" dependencies = [ "semver-parser", ] [[package]] name = "semver" version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e25dfac463d778e353db5be2449d1cce89bd6fd23c9f1ea21310ce6e5a1b29c4" [[package]] name = "semver-parser" version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" [[package]] name = "serde" version = "1.0.147" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d193d69bae983fc11a79df82342761dfbf28a99fc8d203dca4c3c1b590948965" dependencies = [ "serde_derive", ] [[package]] name = "serde_bytes" version = "0.11.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cfc50e8183eeeb6178dcb167ae34a8051d63535023ae38b5d8d12beae193d37b" dependencies = [ "serde", ] [[package]] name = "serde_derive" version = "1.0.147" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4f1d362ca8fc9c3e3a7484440752472d68a6caa98f1ab81d99b5dfe517cec852" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_json" version = "1.0.88" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e8b3801309262e8184d9687fb697586833e939767aea0dda89f5a8e650e8bd7" dependencies = [ "indexmap", "itoa", "ryu", "serde", ] [[package]] name = "serde_v8" version = "0.67.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "225ac8039b46a4094ce9a30985820af6a602d27bdc7c0ce2728c10ad67aa03dd" dependencies = [ "bytes", "derive_more", "serde", "serde_bytes", "smallvec", "v8", ] [[package]] name = "slab" version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4614a76b2a8be0058caa9dbbaf66d988527d86d003c11a94fbd335d7661edcef" dependencies = [ "autocfg", ] [[package]] name = "smallvec" version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0" [[package]] name = "sourcemap" version = "6.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c46fdc1838ff49cf692226f5c2b0f5b7538f556863d0eca602984714667ac6e7" dependencies = [ "base64", "if_chain", "lazy_static", "regex", "rustc_version 0.2.3", "serde", "serde_json", "url", ] [[package]] name = "syn" version = "1.0.103" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a864042229133ada95abf3b54fdc62ef5ccabe9515b64717bcb9a1919e59445d" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "thiserror" version = "1.0.37" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "10deb33631e3c9018b9baf9dcbbc4f737320d2b576bac10f6aefa048fa407e3e" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" version = "1.0.37" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "982d17546b47146b28f7c22e3d08465f6b8903d0ea13c1660d9d84a6e7adcdbb" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "tinyvec" version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50" dependencies = [ "tinyvec_macros", ] [[package]] name = "tinyvec_macros" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c" [[package]] name = "toml" version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8d82e1a7758622a465f8cee077614c73484dac5b836c02ff6a40d5d1010324d7" dependencies = [ "serde", ] [[package]] name = "unicode-bidi" version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "099b7128301d285f79ddd55b9a83d5e6b9e97c92e0ea0daebee7263e932de992" [[package]] name = "unicode-ident" version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3" [[package]] name = "unicode-normalization" version = "0.1.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c5713f0fc4b5db668a2ac63cdb7bb4469d8c9fed047b1d0292cc7b0ce2ba921" dependencies = [ "tinyvec", ] [[package]] name = "url" version = "2.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d68c799ae75762b8c3fe375feb6600ef5602c883c5d21eb51c09f22b83c4643" dependencies = [ "form_urlencoded", "idna", "percent-encoding", "serde", ] [[package]] name = "v8" version = "0.54.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3b63103bd7caa4c3571e8baafe58f3e04818df70505304ed814737e655d1d8d6" dependencies = [ "bitflags", "fslock", "lazy_static", "libc", "which", ] [[package]] name = "which" version = "4.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c831fbbee9e129a8cf93e7747a82da9d95ba8e16621cae60ec2cdc849bacb7b" dependencies = [ "either", "libc", "once_cell", ] [[package]] name = "winapi" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" dependencies = [ "winapi-i686-pc-windows-gnu", "winapi-x86_64-pc-windows-gnu", ] [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windows-sys" version = "0.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7" dependencies = [ "windows_aarch64_gnullvm", "windows_aarch64_msvc", "windows_i686_gnu", "windows_i686_msvc", "windows_x86_64_gnu", "windows_x86_64_gnullvm", "windows_x86_64_msvc", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41d2aa71f6f0cbe00ae5167d90ef3cfe66527d6f613ca78ac8024c3ccab9a19e" [[package]] name = "windows_aarch64_msvc" version = "0.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd0f252f5a35cac83d6311b2e795981f5ee6e67eb1f9a7f64eb4500fbc4dcdb4" [[package]] name = "windows_i686_gnu" version = "0.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fbeae19f6716841636c28d695375df17562ca208b2b7d0dc47635a50ae6c5de7" [[package]] name = "windows_i686_msvc" version = "0.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "84c12f65daa39dd2babe6e442988fc329d6243fdce47d7d2d155b8d874862246" [[package]] name = "windows_x86_64_gnu" version = "0.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bf7b1b21b5362cbc318f686150e5bcea75ecedc74dd157d874d754a2ca44b0ed" [[package]] name = "windows_x86_64_gnullvm" version = "0.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09d525d2ba30eeb3297665bd434a54297e4170c7f1a44cad4ef58095b4cd2028" [[package]] name = "windows_x86_64_msvc" version = "0.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f40009d85759725a34da6d89a94e63d7bdc50a862acf0dbc7c8e488f1edcb6f5"
0
repos/nix-zig-stdenv/sketchpad/rusty-v8
repos/nix-zig-stdenv/sketchpad/rusty-v8/deno-core-hello-world/Cargo.toml
[package] name = "deno-core-hello-world" version = "0.1.0" edition = "2021" [profile.release] lto = true opt-level = "z" codegen-units = 1 panic = "abort" [dependencies] deno_core = "0.156.0"
0
repos/nix-zig-stdenv/sketchpad/rusty-v8/deno-core-hello-world
repos/nix-zig-stdenv/sketchpad/rusty-v8/deno-core-hello-world/src/main.rs
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. //! This example shows you how to define ops in Rust and then call them from //! JavaScript. use deno_core::op; use deno_core::Extension; use deno_core::JsRuntime; use deno_core::RuntimeOptions; // This is a hack to make the `#[op]` macro work with // deno_core examples. // You can remove this: use deno_core::*; #[op] fn op_sum(nums: Vec<f64>) -> Result<f64, deno_core::error::AnyError> { // Sum inputs let sum = nums.iter().fold(0.0, |a, v| a + v); // return as a Result<f64, AnyError> Ok(sum) } fn main() { // Build a deno_core::Extension providing custom ops let ext = Extension::builder() .ops(vec![ // An op for summing an array of numbers // The op-layer automatically deserializes inputs // and serializes the returned Result & value op_sum::decl(), ]) .build(); // Initialize a runtime instance let mut runtime = JsRuntime::new(RuntimeOptions { extensions: vec![ext], ..Default::default() }); // Now we see how to invoke the op we just defined. The runtime automatically // contains a Deno.core object with several functions for interacting with it. // You can find its definition in core.js. runtime .execute_script( "<usage>", r#" // Print helper function, calling Deno.core.print() function print(value) { Deno.core.print(value.toString()+"\n"); } const arr = [1, 2, 3]; print("The sum of"); print(arr); print("is"); print(Deno.core.ops.op_sum(arr)); // And incorrect usage try { print(Deno.core.ops.op_sum(0)); } catch(e) { print('Exception:'); print(e); } "#, ) .unwrap(); }
0
repos/nix-zig-stdenv/sketchpad
repos/nix-zig-stdenv/sketchpad/glib/default.nix
{ pkgs, cross, lib ? pkgs.lib, stdenv ? cross.stdenv, fetchpatch ? pkgs.fetchpatch, fetchurl ? pkgs.fetchurl }: with lib; let # Some packages don't get "Cflags" from pkg-config correctly # and then fail to build when directly including like <glib/...>. # This is intended to be run in postInstall of any package # which has $out/include/ containing just some disjunct directories. flattenInclude = '' for dir in "''${!outputInclude}"/include/*; do cp -r "$dir"/* "''${!outputInclude}/include/" rm -r "$dir" ln -s . "$dir" done ln -sr -t "''${!outputInclude}/include/" "''${!outputInclude}"/lib/*/include/* 2>/dev/null || true ''; in stdenv.mkDerivation (finalAttrs: { pname = "glib"; version = "2.74.0"; src = fetchurl { url = "mirror://gnome/sources/glib/${lib.versions.majorMinor finalAttrs.version}/glib-${finalAttrs.version}.tar.xz"; sha256 = "NlLH8HLXsDGmte3WI/d+vF3NKuaYWYq8yJ/znKda3TA="; }; patches = optionals stdenv.isDarwin [ (fetchpatch { name = "darwin-compilation.patch"; url = "https://raw.githubusercontent.com/NixOS/nixpkgs/c987121acf5c87436a0b05ca75cd70bf38c452ca/pkgs/development/libraries/glib/darwin-compilation.patch"; sha256 = "7d4c84277034fb8a1aad1d253344e91df89de2efa344a88627ad581c2cbd939b"; }) ] ++ optionals stdenv.hostPlatform.isMusl [ (fetchpatch { name = "quark-init-on-demand.patch"; url = "https://raw.githubusercontent.com/NixOS/nixpkgs/c987121acf5c87436a0b05ca75cd70bf38c452ca/pkgs/development/libraries/glib/quark_init_on_demand.patch"; sha256 = "sha256-Kz5o56qfK6s2614UTpjEOFGQV+pU5KutzK//ZucPhTk="; }) (fetchpatch { name = "gobject-init-on-demand.patch"; url = "https://raw.githubusercontent.com/NixOS/nixpkgs/c987121acf5c87436a0b05ca75cd70bf38c452ca/pkgs/development/libraries/glib/gobject_init_on_demand.patch"; sha256 = "sha256-LnKWzm88hQVpEt92XdE37R+GLVz78Sd4tztpTtKXuiU="; }) ] ++ [ # Fix build on Darwin # https://gitlab.gnome.org/GNOME/glib/-/merge_requests/2914 (fetchpatch { name = "gio-properly-guard-use-of-utimensat.patch"; url = "https://gitlab.gnome.org/GNOME/glib/-/commit/7f7171e68a420991b537d3e9e63263a0b2871618.patch"; sha256 = "kKEqmBqx/RlvFT3eixu+NnM7JXhHb34b9NLRfAt+9h0="; }) # https://gitlab.gnome.org/GNOME/glib/-/merge_requests/2921 (fetchpatch { url = "https://gitlab.gnome.org/GNOME/glib/-/commit/f0dd96c28751f15d0703b384bfc7c314af01caa8.patch"; sha256 = "sha256-8ucHS6ZnJuP6ajGb4/L8QfhC49FTQG1kAGHVdww/YYE="; }) ]; postPatch = '' substituteInPlace gio/gio-launch-desktop.c --replace "G_STATIC_ASSERT" "//G_STATIC_ASSERT" ''; buildInputs = with cross.pkgs; [ pcre2 ]; nativeBuildInputs = with pkgs.buildPackages; [ meson ninja pkg-config python3 ]; propagatedBuildInputs = with cross.pkgs; [ libffi zlib ]; depsBuildBuild = with cross.pkgs; [ buildPackages.stdenv.cc ]; mesonFlags = [ "-Diconv=libc" "-Dlibelf=disabled" "-Dlibmount=disabled" "-Dselinux=disabled" "-Dnls=disabled" "-Dglib_debug=disabled" "-Dxattr=false" "-Dglib_assert=false" "-Dglib_checks=false" "-Dtests=false" ]; NIX_CFLAGS_COMPILE = toString [ "-Wno-error=nonnull" # Default for release buildtype but passed manually because # we're using plain "-DG_DISABLE_CAST_CHECKS" ]; DETERMINISTIC_BUILD = 1; passthru = { inherit flattenInclude; }; meta = with lib; { description = "C library of programming buildings blocks"; homepage = "https://www.gtk.org/"; license = licenses.lgpl21Plus; platforms = platforms.unix; longDescription = '' GLib provides the core application building blocks for libraries and applications written in C. It provides the core object system used in GNOME, the main loop implementation, and a large set of utility functions for strings and common data structures. ''; }; })
0
repos/nix-zig-stdenv
repos/nix-zig-stdenv/automation/default.nix
with builtins; let versions = import ../versions.nix {}; pkgs = import <nixpkgs> { overlays = [(import ../overlay.nix { zig = versions.master; allowBroken = true; })]; }; in { inherit (pkgs) zigVersions zigCross; }
0
repos/nix-zig-stdenv
repos/nix-zig-stdenv/automation/build-package.template.yml
name: build-package on: pull_request: branches: [ master ] workflow_dispatch: inputs: version: description: 'Zig version' required: true default: master type: choice options: @versions@ target: description: 'Target' required: true default: all type: choice options: - all @targets@ package: description: 'Package to build' required: false type: string default: super-simple jobs: build-package: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Install Nix uses: cachix/install-nix-action@v18 with: nix_path: nixpkgs=channel:nixos-unstable - name: Build package run: | cd test if [[ "$target" == all ]]; then if [[ ! "$package" ]]; then ./run all_for_version "$version" else ./run build-package-for-all-targets "$version" "$package" fi else if [[ ! "$package" ]]; then ./run all_for_target "$version" "$target" else ./run build-package "$version" "$target" "$package" fi fi env: version: ${{ inputs.version }} target: ${{ inputs.target }} package: ${{ inputs.package }}
0
repos/nix-zig-stdenv
repos/nix-zig-stdenv/src/rust-support.nix
{ lib, writeShellScript, wrapper, static }: with lib; with builtins; rust-toolchain: host-cc: host: target-cc: target: let cc-wrapper = target: cc: writeShellScript "rust-cc-${target}" '' shopt -s extglob args=() while [[ $# -gt 0 ]]; do case "$1" in */self-contained/crt@([1in]|begin|end).o) shift;; */self-contained/libc.a) shift;; -lc|-liconv) shift;; *) args+=("$1") shift;; esac done export ZIG_LOCAL_CACHE_DIR="$TMPDIR/zig-cache-${target}-rust" export ZIG_GLOBAL_CACHE_DIR="$ZIG_LOCAL_CACHE_DIR" if ! ${cc} "''${args[@]}"; then find "$ZIG_LOCAL_CACHE_DIR" -name libcompiler_rt.a | while read -r f; do rm -f "$f"; touch "$f" done ${cc} "''${args[@]}" fi ''; rust-config = { target = rec { name = target; cargo = stringAsChars (x: if x == "-" then "_" else x) (toUpper name); # FIXME: libcompiler_rt.a removal for rust is a ugly hack that I eventually want to get rid of # https://github.com/ziglang/zig/issues/5320 linker = cc-wrapper target "${target-cc}/bin/${target}-cc"; flags = if static then "-C target-feature=+crt-static" else ""; }; host = rec { name = host; cargo = stringAsChars (x: if x == "-" then "_" else x) (toUpper name); linker = cc-wrapper host "${host-cc}/bin/cc"; }; }; in wrapper [ rust-toolchain ] [ { script = '' export CARGO_BUILD_TARGET=${rust-config.target.name} export CARGO_TARGET_${rust-config.host.cargo}_LINKER=${rust-config.host.linker} export CARGO_TARGET_${rust-config.target.cargo}_LINKER=${rust-config.target.linker} export CARGO_TARGET_${rust-config.target.cargo}_RUSTFLAGS="${rust-config.target.flags}" ${rust-toolchain}/bin/cargo "$@" ''; path = "bin/cargo"; } ]
0
repos/nix-zig-stdenv
repos/nix-zig-stdenv/src/utils.nix
{ lib }: with lib; rec { zigTargetToNixTarget = target: let kernel = { freestanding = l: "${head l}-unknown-none-${last l}"; linux = l: "${head l}-unknown-linux-${last l}"; macos = l: "${head l}-apple-darwin"; windows = l: "${head l}-w64-mingw32"; wasi = l: "${head l}-unknown-wasi"; }; cpu = { powerpc64 = s: "${s}abi64"; sparcv9 = s: "sparc64-${removePrefix "sparcv9-" s}"; thumb = s: "armv5tel-${removePrefix "thumb-" s}"; x86 = s: "i386-${removePrefix "x86-" s}"; }; split = splitString "-" target; in cpu."${head split}" or (_: _) (kernel."${elemAt split 1}" split); nixTargetToZigTarget = target: let kernel = { none = t: "${t.cpu.name}-freestanding-${t.abi.name}"; linux = t: "${t.cpu.name}-linux-${t.abi.name}"; darwin = t: "${t.cpu.name}-macos-none"; windows = t: "${t.cpu.name}-windows-gnu"; wasi = t: "${t.cpu.name}-wasi-musl"; }; cpu = { powerpc64 = s: removeSuffix "abi64" s; sparc64 = s: "sparcv9-${removePrefix "sparc64-" s}"; armv5tel = s: "thumb-${removePrefix "armv5tel-" s}"; i386 = s: "x86-${removePrefix "i386-" s}"; }; in cpu."${target.cpu.name}" or (_: _) (kernel."${target.kernel.name}" target); elaborate = system: let target = system.config; in systems.elaborate (system // optionalAttrs (hasSuffix "mingw32" target) { libc = "msvcrt"; } // optionalAttrs (hasSuffix "darwin" target) { libc = "libSystem"; } // optionalAttrs (hasSuffix "wasi" target) { libc = "wasilibc"; } // optionalAttrs (hasInfix "musl" target) { libc = "musl"; } // optionalAttrs (hasInfix "gnu" target) { libc = "glibc"; } ); targetToNixSystem = target: isStatic: elaborate ({ config = target; inherit isStatic; }); supportsStatic = target: let inherit (systems.elaborate target) parsed; in parsed.kernel.name != "darwin"; }
0
repos/nix-zig-stdenv
repos/nix-zig-stdenv/src/prebuilt-derive-from.nix
{ pkgs ? import <nixpkgs> {}, target }: let utils = import ./utils.nix { inherit (pkgs) lib; }; isStatic = with pkgs.lib; hasSuffix "-static" target; localSystem = with pkgs.lib; utils.targetToNixSystem (removeSuffix "-static" target) isStatic; in with pkgs.lib; import pkgs.path { inherit localSystem; overlays = [] ++ optionals (isStatic) [ (self: super: { # error: attribute 'pam' missing libcap_pam = null; }) ] ; }
0
repos/nix-zig-stdenv
repos/nix-zig-stdenv/src/stdenv.nix
{ path, mk-zig-toolchain, native-toolchain ? null, targetPkgs ? null, libc ? null }: { lib, localSystem, crossSystem, config, overlays, crossOverlays ? [] }: with lib; let # XXX: Zig doesn't support response file. Nixpkgs wants to use this for clang # while zig cc is basically clang, it's still not 100% compatible. # Probably should report this as a bug to zig upstream though. zig-prehook = prelude: targetSystem: '' ${prelude} export NIX_CC_USE_RESPONSE_FILE=0 export ZIG_LOCAL_CACHE_DIR="$TMPDIR/zig-cache-${targetSystem.config}" export ZIG_GLOBAL_CACHE_DIR="$ZIG_LOCAL_CACHE_DIR" ''; bootStages = import "${path}/pkgs/stdenv" { inherit lib localSystem overlays; crossSystem = localSystem; crossOverlays = []; # Ignore custom stdenvs when cross compiling for compatability config = builtins.removeAttrs config [ "replaceStdenv" ]; }; in lib.init bootStages ++ [ (somePrevStage: lib.last bootStages somePrevStage // { allowCustomOverrides = true; }) # First replace native compiler with zig # This gives us more deterministic environment (buildPackages: let in { inherit config overlays; selfBuild = false; stdenv = (buildPackages.stdenv.override (old: rec { targetPlatform = crossSystem; allowedRequisites = null; hasCC = true; cc = native-toolchain; preHook = zig-prehook old.preHook localSystem; # Propagate everything to the next step as we do not need to bootstrap # We exclude packages that would break nixpkg's cross-compiling setup overrides = self: super: genAttrs (filter (a: ! any (b: hasPrefix b a) [ "callPackage" "newScope" "pkgs" "stdenv" "system" "wrapBintools" "wrapCC" ]) (attrNames buildPackages)) (x: buildPackages."${x}"); })); allowCustomOverrides = true; }) # Then use zig as a cross-compiler as well (buildPackages: let adaptStdenv = if crossSystem.isStatic then buildPackages.stdenvAdapters.makeStatic else id; in { inherit config; overlays = overlays ++ crossOverlays; selfBuild = false; stdenv = adaptStdenv (buildPackages.stdenv.override (old: rec { buildPlatform = localSystem; hostPlatform = crossSystem; targetPlatform = crossSystem; # Prior overrides are surely not valid as packages built with this run on # a different platform, and so are disabled. overrides = _: _: {}; allowedRequisites = null; hasCC = true; cc = mk-zig-toolchain { inherit (buildPackages) wrapCCWith wrapBintoolsWith; inherit (buildPackages.stdenvNoCC) mkDerivation; inherit targetPkgs libc; targetSystem = crossSystem; }; preHook = zig-prehook old.preHook crossSystem; extraNativeBuildInputs = with buildPackages; old.extraNativeBuildInputs ++ lib.optionals (hostPlatform.isLinux && !buildPlatform.isLinux) [ patchelf ] ++ lib.optional (let f = p: !p.isx86 || builtins.elem p.libc [ "musl" "wasilibc" "relibc" ] || p.isiOS || p.isGenode; in f hostPlatform && !(f buildPlatform) ) updateAutotoolsGnuConfigScriptsHook # without proper `file` command, libtool sometimes fails # to recognize 64-bit DLLs ++ lib.optional (hostPlatform.config == "x86_64-w64-mingw32") file; })); }) ]
0
repos/nix-zig-stdenv
repos/nix-zig-stdenv/src/wrapper.nix
{ lib, writeShellScript, symlinkJoin }: with lib; drvs: wrappers: let mapped = map (x: { wrapper = writeShellScript "wrapper" x.script; path = x.path; }) wrappers; in symlinkJoin { name = "${(head drvs).name}-wrapped"; paths = drvs; postBuild = concatStringsSep "\n" (flatten (map (x: [ "rm -f $out/${x.path}" "ln -s ${x.wrapper} $out/${x.path}" ]) mapped)); }
0
repos/nix-zig-stdenv
repos/nix-zig-stdenv/src/toolchain.nix
{ utils, lib, writeShellScript, emptyFile, gnugrep, coreutils, localSystem, zig, llvm }: { mkDerivation, wrapCCWith, wrapBintoolsWith, libc ? null, targetSystem, targetPkgs, }: with lib; with builtins; let zig-target = utils.nixTargetToZigTarget targetSystem.parsed; # FIXME: some quirks here should be fixed upstream # meson: -Wl,--version # v8/gn: inserts --target=, we do not want to ever compile to a platform we do not expect # v8/gn: -latomic already built into compiler_rt, perhaps v8/gn just thinks we are gcc instead? write-cc-wrapper = cmd: writeShellScript "zig-${cmd}" '' shopt -s extglob args=() while [[ $# -gt 0 ]]; do case "$1" in -Wl,--version) echo "LLD 11.1.0 (compatible with GNU linkers)" exit 0;; -Wl,--no-undefined-version) shift;; -Wl,--unresolved-symbols=ignore-in-object-files) args+=("-Wl,-undefined,dynamic_lookup") shift;; -Wl,--unresolved-symbols=*) shift;; -target) shift;shift;; --target=*) shift;; -latomic) shift;; *) args+=("$1") shift;; esac done ${zig}/bin/zig ${cmd} -target ${zig-target} "''${args[@]}" ''; write-wrapper = cmd: writeShellScript "zig-${cmd}" ''${zig}/bin/zig ${cmd} "$@"''; toolchain-unwrapped = let prefix = if localSystem.config != targetSystem.config then "${targetSystem.config}-" else ""; in mkDerivation { name = "zig-toolchain"; inherit (zig) version; isClang = true; dontUnpack = true; dontConfigure = true; dontBuild = true; dontFixup = true; installPhase = '' mkdir -p $out/bin $out/lib for prog in ${llvm}/bin/*; do ln -sf $prog $out/bin/${prefix}$(basename $prog) done ln -s ${llvm}/bin/llvm-as $out/bin/${prefix}as ln -s ${llvm}/bin/llvm-dwp $out/bin/${prefix}dwp ln -s ${llvm}/bin/llvm-nm $out/bin/${prefix}nm ln -s ${llvm}/bin/llvm-objcopy $out/bin/${prefix}objcopy ln -s ${llvm}/bin/llvm-objdump $out/bin/${prefix}objdump ln -s ${llvm}/bin/llvm-readelf $out/bin/${prefix}readelf ln -s ${llvm}/bin/llvm-size $out/bin/${prefix}size ln -s ${llvm}/bin/llvm-strip $out/bin/${prefix}strip ln -s ${llvm}/bin/llvm-rc $out/bin/${prefix}windres for f in ar ranlib dlltool lib; do rm -f ${prefix}$f done ln -s ${write-cc-wrapper "cc"} $out/bin/clang ln -s ${write-cc-wrapper "c++"} $out/bin/clang++ ln -s ${write-wrapper "ar"} $out/bin/${prefix}ar ln -s ${write-wrapper "ranlib"} $out/bin/${prefix}ranlib ln -s ${write-wrapper "dlltool"} $out/bin/${prefix}dlltool ln -s ${write-wrapper "lib"} $out/bin/${prefix}lib ''; # Compatibility packages here: propagatedBuildInputs = [] ++ optionals (isAttrs targetPkgs) (with targetPkgs; [] ++ optionals (targetSystem.parsed.kernel.name == "darwin") [ # TODO: zig seems to be missing <err.h> ]); }; in wrapCCWith { inherit gnugrep coreutils libc; cc = toolchain-unwrapped; bintools = wrapBintoolsWith { inherit gnugrep coreutils libc; bintools = toolchain-unwrapped; postLinkSignHook = emptyFile; signingUtils = emptyFile; }; # XXX: -march and -mcpu are not compatible # https://github.com/ziglang/zig/issues/4911 extraBuildCommands = '' rm -f $out/nix-support/add-local-cc-flags.before.sh sed -i 's/\([^ ]\)-\([^ ]\)/\1_\2/g' $out/nix-support/cc-cflags-before || true sed -i 's/-arch [^ ]* *//g' $out/nix-support/cc-cflags || true '' + (optionalString ( targetSystem.parsed.cpu.name == "aarch64" || targetSystem.parsed.cpu.name == "aarch64_be" || targetSystem.parsed.cpu.name == "armv5tel" || targetSystem.parsed.cpu.name == "mipsel") '' # error: Unknown CPU: ... sed -i 's/-march[^ ]* *//g' $out/nix-support/cc-cflags-before || true '') + (optionalString (targetSystem.parsed.cpu.name == "s390x") '' printf " -march=''${S390X_MARCH:-arch8}" >> $out/nix-support/cc-cflags-before ''); }
0
repos/nix-zig-stdenv
repos/nix-zig-stdenv/src/prebuilt.nix
{ pkgs, crossSystem, stdenv ? pkgs.stdenvNoCC }: with builtins; with pkgs.lib; let target = crossSystem.config; cache-dynamic = import ./prebuilt-derive-from.nix { inherit pkgs target; }; cache-static = import ./prebuilt-derive-from.nix { inherit pkgs; target = "${target}-static"; }; prebuilt = fromJSON (readFile ../meta/prebuilt.json); in { static = genAttrs (prebuilt."${target}-static" or []) (pkg: cache-static.pkgs."${pkg}"); dynamic = genAttrs (prebuilt."${target}" or []) (pkg: cache-dynamic.pkgs."${pkg}"); }
0
repos/nix-zig-stdenv
repos/nix-zig-stdenv/meta/prebuilt.json
{ "x86_64-apple-darwin": [ "glib", "SDL", "glfw" ], "aarch64-apple-darwin": [ "glib", "SDL", "glfw" ], "x86_64-unknown-linux-gnu": [ "musl", "glibc", "glib", "SDL", "glfw" ], "x86_64-unknown-linux-gnu-static": [], "x86_64-unknown-linux-musl": [ "musl" ], "x86_64-unknown-linux-musl-static": [], "aarch64-unknown-linux-gnu": [ "musl", "glibc", "glib", "SDL", "glfw" ], "aarch64-unknown-linux-gnu-static": [], "aarch64-unknown-linux-musl": [ "musl" ], "aarch64-unknown-linux-musl-static": [] }
0
repos/nix-zig-stdenv
repos/nix-zig-stdenv/meta/broken-targets.json
{ "0.10.0": [ "aarch64_be-unknown-linux-gnu", "aarch64_be-unknown-linux-gnu-static", "aarch64_be-unknown-linux-musl", "aarch64_be-unknown-linux-musl-static", "aarch64_be-w64-mingw32", "aarch64_be-w64-mingw32-static", "arm-unknown-linux-gnueabi", "arm-unknown-linux-gnueabi-static", "arm-unknown-linux-gnueabihf", "arm-unknown-linux-gnueabihf-static", "arm-w64-mingw32", "arm-w64-mingw32-static", "armv5tel-unknown-linux-gnueabi", "armv5tel-unknown-linux-gnueabi-static", "armv5tel-unknown-linux-gnueabihf", "armv5tel-unknown-linux-gnueabihf-static", "armv5tel-unknown-linux-musleabi", "armv5tel-unknown-linux-musleabi-static", "armv5tel-unknown-linux-musleabihf", "armv5tel-unknown-linux-musleabihf-static", "i386-unknown-linux-gnu", "i386-unknown-linux-gnu-static", "i386-unknown-linux-musl", "i386-unknown-linux-musl-static", "i386-w64-mingw32", "i386-w64-mingw32-static", "m68k-unknown-linux-gnu", "m68k-unknown-linux-gnu-static", "m68k-unknown-linux-musl", "m68k-unknown-linux-musl-static", "mips64-unknown-linux-gnuabi64", "mips64-unknown-linux-gnuabi64-static", "mips64-unknown-linux-gnuabin32", "mips64-unknown-linux-gnuabin32-static", "mips64-unknown-linux-musl", "mips64-unknown-linux-musl-static", "mips64el-unknown-linux-gnuabi64", "mips64el-unknown-linux-gnuabi64-static", "mips64el-unknown-linux-gnuabin32", "mips64el-unknown-linux-gnuabin32-static", "mips64el-unknown-linux-musl", "mips64el-unknown-linux-musl-static", "riscv64-unknown-linux-gnu", "riscv64-unknown-linux-gnu-static", "s390x-unknown-linux-gnu", "s390x-unknown-linux-gnu-static", "s390x-unknown-linux-musl", "s390x-unknown-linux-musl-static", "sparc-unknown-linux-gnu", "sparc-unknown-linux-gnu-static", "sparc64-unknown-linux-gnu", "sparc64-unknown-linux-gnu-static", "wasm32-unknown-none-musl", "wasm32-unknown-none-musl-static" ], "0.10.1": [ "aarch64_be-unknown-linux-gnu", "aarch64_be-unknown-linux-gnu-static", "aarch64_be-unknown-linux-musl", "aarch64_be-unknown-linux-musl-static", "aarch64_be-w64-mingw32", "aarch64_be-w64-mingw32-static", "arm-w64-mingw32", "arm-w64-mingw32-static", "armv5tel-unknown-linux-gnueabi", "armv5tel-unknown-linux-gnueabi-static", "armv5tel-unknown-linux-gnueabihf", "armv5tel-unknown-linux-gnueabihf-static", "armv5tel-unknown-linux-musleabi", "armv5tel-unknown-linux-musleabi-static", "armv5tel-unknown-linux-musleabihf", "armv5tel-unknown-linux-musleabihf-static", "i386-unknown-linux-gnu", "i386-unknown-linux-gnu-static", "i386-unknown-linux-musl", "i386-unknown-linux-musl-static", "i386-w64-mingw32", "i386-w64-mingw32-static", "m68k-unknown-linux-gnu", "m68k-unknown-linux-gnu-static", "m68k-unknown-linux-musl", "m68k-unknown-linux-musl-static", "mips64-unknown-linux-gnuabi64", "mips64-unknown-linux-gnuabi64-static", "mips64-unknown-linux-gnuabin32", "mips64-unknown-linux-gnuabin32-static", "mips64-unknown-linux-musl", "mips64-unknown-linux-musl-static", "mips64el-unknown-linux-gnuabi64", "mips64el-unknown-linux-gnuabi64-static", "mips64el-unknown-linux-gnuabin32", "mips64el-unknown-linux-gnuabin32-static", "mips64el-unknown-linux-musl", "mips64el-unknown-linux-musl-static", "riscv64-unknown-linux-gnu", "riscv64-unknown-linux-gnu-static", "s390x-unknown-linux-gnu", "s390x-unknown-linux-gnu-static", "s390x-unknown-linux-musl", "s390x-unknown-linux-musl-static", "sparc-unknown-linux-gnu", "sparc-unknown-linux-gnu-static", "sparc64-unknown-linux-gnu", "sparc64-unknown-linux-gnu-static", "wasm32-unknown-none-musl", "wasm32-unknown-none-musl-static" ], "0.11.0": [ "aarch64-apple-darwin", "aarch64_be-unknown-linux-gnu", "aarch64_be-unknown-linux-gnu-static", "aarch64_be-unknown-linux-musl", "aarch64_be-unknown-linux-musl-static", "aarch64_be-w64-mingw32", "aarch64_be-w64-mingw32-static", "arm-w64-mingw32", "arm-w64-mingw32-static", "armv5tel-unknown-linux-gnueabi", "armv5tel-unknown-linux-gnueabi-static", "armv5tel-unknown-linux-gnueabihf", "armv5tel-unknown-linux-gnueabihf-static", "armv5tel-unknown-linux-musleabi", "armv5tel-unknown-linux-musleabi-static", "armv5tel-unknown-linux-musleabihf", "armv5tel-unknown-linux-musleabihf-static", "i386-unknown-linux-musl", "i386-unknown-linux-musl-static", "m68k-unknown-linux-gnu", "m68k-unknown-linux-gnu-static", "m68k-unknown-linux-musl", "m68k-unknown-linux-musl-static", "mips64-unknown-linux-gnuabi64", "mips64-unknown-linux-gnuabi64-static", "mips64-unknown-linux-gnuabin32", "mips64-unknown-linux-gnuabin32-static", "mips64el-unknown-linux-gnuabi64", "mips64el-unknown-linux-gnuabi64-static", "mips64el-unknown-linux-gnuabin32", "mips64el-unknown-linux-gnuabin32-static", "riscv64-unknown-linux-gnu", "riscv64-unknown-linux-gnu-static", "s390x-unknown-linux-gnu", "s390x-unknown-linux-gnu-static", "s390x-unknown-linux-musl", "s390x-unknown-linux-musl-static", "sparc-unknown-linux-gnu", "sparc-unknown-linux-gnu-static", "sparc64-unknown-linux-gnu", "sparc64-unknown-linux-gnu-static", "wasm32-unknown-none-musl", "wasm32-unknown-none-musl-static", "x86_64-apple-darwin" ], "0.8.0": [ "aarch64-apple-darwin", "aarch64-w64-mingw32", "aarch64-w64-mingw32-static", "aarch64_be-unknown-linux-gnu", "aarch64_be-unknown-linux-gnu-static", "aarch64_be-unknown-linux-musl", "aarch64_be-unknown-linux-musl-static", "aarch64_be-w64-mingw32", "aarch64_be-w64-mingw32-static", "arm-unknown-linux-gnueabi", "arm-unknown-linux-gnueabi-static", "arm-unknown-linux-gnueabihf", "arm-unknown-linux-gnueabihf-static", "arm-unknown-linux-musleabi", "arm-unknown-linux-musleabi-static", "arm-unknown-linux-musleabihf", "arm-unknown-linux-musleabihf-static", "arm-w64-mingw32", "arm-w64-mingw32-static", "armv5tel-unknown-linux-gnueabi", "armv5tel-unknown-linux-gnueabi-static", "armv5tel-unknown-linux-gnueabihf", "armv5tel-unknown-linux-gnueabihf-static", "armv5tel-unknown-linux-musleabi", "armv5tel-unknown-linux-musleabi-static", "armv5tel-unknown-linux-musleabihf", "armv5tel-unknown-linux-musleabihf-static", "i386-unknown-linux-gnu", "i386-unknown-linux-gnu-static", "i386-unknown-linux-musl", "i386-unknown-linux-musl-static", "i386-w64-mingw32", "i386-w64-mingw32-static", "mips-unknown-linux-gnu", "mips-unknown-linux-gnu-static", "mips64-unknown-linux-gnuabi64", "mips64-unknown-linux-gnuabi64-static", "mips64-unknown-linux-gnuabin32", "mips64-unknown-linux-gnuabin32-static", "mips64-unknown-linux-musl", "mips64-unknown-linux-musl-static", "mips64el-unknown-linux-gnuabi64", "mips64el-unknown-linux-gnuabi64-static", "mips64el-unknown-linux-gnuabin32", "mips64el-unknown-linux-gnuabin32-static", "mips64el-unknown-linux-musl", "mips64el-unknown-linux-musl-static", "mipsel-unknown-linux-gnu", "mipsel-unknown-linux-gnu-static", "powerpc-unknown-linux-gnu", "powerpc-unknown-linux-gnu-static", "powerpc64-unknown-linux-gnuabi64", "powerpc64-unknown-linux-gnuabi64-static", "powerpc64le-unknown-linux-gnu", "powerpc64le-unknown-linux-gnu-static", "riscv64-unknown-linux-gnu", "riscv64-unknown-linux-gnu-static", "riscv64-unknown-linux-musl", "riscv64-unknown-linux-musl-static", "s390x-unknown-linux-gnu", "s390x-unknown-linux-gnu-static", "s390x-unknown-linux-musl", "s390x-unknown-linux-musl-static", "sparc-unknown-linux-gnu", "sparc-unknown-linux-gnu-static", "sparc64-unknown-linux-gnu", "sparc64-unknown-linux-gnu-static", "wasm32-unknown-none-musl", "wasm32-unknown-none-musl-static", "x86_64-apple-darwin" ], "0.8.1": [ "aarch64-apple-darwin", "aarch64-w64-mingw32", "aarch64-w64-mingw32-static", "aarch64_be-unknown-linux-gnu", "aarch64_be-unknown-linux-gnu-static", "aarch64_be-unknown-linux-musl", "aarch64_be-unknown-linux-musl-static", "aarch64_be-w64-mingw32", "aarch64_be-w64-mingw32-static", "arm-unknown-linux-gnueabi", "arm-unknown-linux-gnueabi-static", "arm-unknown-linux-gnueabihf", "arm-unknown-linux-gnueabihf-static", "arm-unknown-linux-musleabi", "arm-unknown-linux-musleabi-static", "arm-unknown-linux-musleabihf", "arm-unknown-linux-musleabihf-static", "arm-w64-mingw32", "arm-w64-mingw32-static", "armv5tel-unknown-linux-gnueabi", "armv5tel-unknown-linux-gnueabi-static", "armv5tel-unknown-linux-gnueabihf", "armv5tel-unknown-linux-gnueabihf-static", "armv5tel-unknown-linux-musleabi", "armv5tel-unknown-linux-musleabi-static", "armv5tel-unknown-linux-musleabihf", "armv5tel-unknown-linux-musleabihf-static", "i386-unknown-linux-gnu", "i386-unknown-linux-gnu-static", "i386-unknown-linux-musl", "i386-unknown-linux-musl-static", "i386-w64-mingw32", "i386-w64-mingw32-static", "mips-unknown-linux-gnu", "mips-unknown-linux-gnu-static", "mips64-unknown-linux-gnuabi64", "mips64-unknown-linux-gnuabi64-static", "mips64-unknown-linux-gnuabin32", "mips64-unknown-linux-gnuabin32-static", "mips64-unknown-linux-musl", "mips64-unknown-linux-musl-static", "mips64el-unknown-linux-gnuabi64", "mips64el-unknown-linux-gnuabi64-static", "mips64el-unknown-linux-gnuabin32", "mips64el-unknown-linux-gnuabin32-static", "mips64el-unknown-linux-musl", "mips64el-unknown-linux-musl-static", "mipsel-unknown-linux-gnu", "mipsel-unknown-linux-gnu-static", "powerpc-unknown-linux-gnu", "powerpc-unknown-linux-gnu-static", "powerpc64-unknown-linux-gnuabi64", "powerpc64-unknown-linux-gnuabi64-static", "powerpc64le-unknown-linux-gnu", "powerpc64le-unknown-linux-gnu-static", "riscv64-unknown-linux-gnu", "riscv64-unknown-linux-gnu-static", "riscv64-unknown-linux-musl", "riscv64-unknown-linux-musl-static", "s390x-unknown-linux-gnu", "s390x-unknown-linux-gnu-static", "s390x-unknown-linux-musl", "s390x-unknown-linux-musl-static", "sparc-unknown-linux-gnu", "sparc-unknown-linux-gnu-static", "sparc64-unknown-linux-gnu", "sparc64-unknown-linux-gnu-static", "wasm32-unknown-none-musl", "wasm32-unknown-none-musl-static", "x86_64-apple-darwin" ], "0.9.0": [ "aarch64-apple-darwin", "aarch64_be-unknown-linux-gnu", "aarch64_be-unknown-linux-gnu-static", "aarch64_be-unknown-linux-musl", "aarch64_be-unknown-linux-musl-static", "aarch64_be-w64-mingw32", "aarch64_be-w64-mingw32-static", "arm-unknown-linux-gnueabi", "arm-unknown-linux-gnueabi-static", "arm-unknown-linux-gnueabihf", "arm-unknown-linux-gnueabihf-static", "arm-unknown-linux-musleabi", "arm-unknown-linux-musleabi-static", "arm-unknown-linux-musleabihf", "arm-unknown-linux-musleabihf-static", "arm-w64-mingw32", "arm-w64-mingw32-static", "armv5tel-unknown-linux-gnueabi", "armv5tel-unknown-linux-gnueabi-static", "armv5tel-unknown-linux-gnueabihf", "armv5tel-unknown-linux-gnueabihf-static", "armv5tel-unknown-linux-musleabi", "armv5tel-unknown-linux-musleabi-static", "armv5tel-unknown-linux-musleabihf", "armv5tel-unknown-linux-musleabihf-static", "i386-unknown-linux-gnu", "i386-unknown-linux-gnu-static", "i386-unknown-linux-musl", "i386-unknown-linux-musl-static", "i386-w64-mingw32", "i386-w64-mingw32-static", "m68k-unknown-linux-gnu", "m68k-unknown-linux-gnu-static", "m68k-unknown-linux-musl", "m68k-unknown-linux-musl-static", "mips64-unknown-linux-gnuabi64", "mips64-unknown-linux-gnuabi64-static", "mips64-unknown-linux-gnuabin32", "mips64-unknown-linux-gnuabin32-static", "mips64-unknown-linux-musl", "mips64-unknown-linux-musl-static", "mips64el-unknown-linux-gnuabi64", "mips64el-unknown-linux-gnuabi64-static", "mips64el-unknown-linux-gnuabin32", "mips64el-unknown-linux-gnuabin32-static", "mips64el-unknown-linux-musl", "mips64el-unknown-linux-musl-static", "powerpc64le-unknown-linux-gnu", "powerpc64le-unknown-linux-gnu-static", "powerpc64le-unknown-linux-musl", "powerpc64le-unknown-linux-musl-static", "riscv64-unknown-linux-gnu", "riscv64-unknown-linux-gnu-static", "s390x-unknown-linux-gnu", "s390x-unknown-linux-gnu-static", "s390x-unknown-linux-musl", "s390x-unknown-linux-musl-static", "sparc-unknown-linux-gnu", "sparc-unknown-linux-gnu-static", "sparc64-unknown-linux-gnu", "sparc64-unknown-linux-gnu-static", "wasm32-unknown-none-musl", "wasm32-unknown-none-musl-static", "x86_64-apple-darwin" ], "0.9.1": [ "aarch64-apple-darwin", "aarch64_be-unknown-linux-gnu", "aarch64_be-unknown-linux-gnu-static", "aarch64_be-unknown-linux-musl", "aarch64_be-unknown-linux-musl-static", "aarch64_be-w64-mingw32", "aarch64_be-w64-mingw32-static", "arm-unknown-linux-gnueabi", "arm-unknown-linux-gnueabi-static", "arm-unknown-linux-gnueabihf", "arm-unknown-linux-gnueabihf-static", "arm-unknown-linux-musleabi", "arm-unknown-linux-musleabi-static", "arm-unknown-linux-musleabihf", "arm-unknown-linux-musleabihf-static", "arm-w64-mingw32", "arm-w64-mingw32-static", "armv5tel-unknown-linux-gnueabi", "armv5tel-unknown-linux-gnueabi-static", "armv5tel-unknown-linux-gnueabihf", "armv5tel-unknown-linux-gnueabihf-static", "armv5tel-unknown-linux-musleabi", "armv5tel-unknown-linux-musleabi-static", "armv5tel-unknown-linux-musleabihf", "armv5tel-unknown-linux-musleabihf-static", "i386-unknown-linux-gnu", "i386-unknown-linux-gnu-static", "i386-unknown-linux-musl", "i386-unknown-linux-musl-static", "i386-w64-mingw32", "i386-w64-mingw32-static", "m68k-unknown-linux-gnu", "m68k-unknown-linux-gnu-static", "m68k-unknown-linux-musl", "m68k-unknown-linux-musl-static", "mips64-unknown-linux-gnuabi64", "mips64-unknown-linux-gnuabi64-static", "mips64-unknown-linux-gnuabin32", "mips64-unknown-linux-gnuabin32-static", "mips64-unknown-linux-musl", "mips64-unknown-linux-musl-static", "mips64el-unknown-linux-gnuabi64", "mips64el-unknown-linux-gnuabi64-static", "mips64el-unknown-linux-gnuabin32", "mips64el-unknown-linux-gnuabin32-static", "mips64el-unknown-linux-musl", "mips64el-unknown-linux-musl-static", "powerpc64le-unknown-linux-gnu", "powerpc64le-unknown-linux-gnu-static", "powerpc64le-unknown-linux-musl", "powerpc64le-unknown-linux-musl-static", "riscv64-unknown-linux-gnu", "riscv64-unknown-linux-gnu-static", "s390x-unknown-linux-gnu", "s390x-unknown-linux-gnu-static", "s390x-unknown-linux-musl", "s390x-unknown-linux-musl-static", "sparc-unknown-linux-gnu", "sparc-unknown-linux-gnu-static", "sparc64-unknown-linux-gnu", "sparc64-unknown-linux-gnu-static", "wasm32-unknown-none-musl", "wasm32-unknown-none-musl-static", "x86_64-apple-darwin" ], "master": [ "aarch64-apple-darwin", "aarch64_be-unknown-linux-gnu", "aarch64_be-unknown-linux-gnu-static", "aarch64_be-unknown-linux-musl", "aarch64_be-unknown-linux-musl-static", "aarch64_be-w64-mingw32", "aarch64_be-w64-mingw32-static", "arm-unknown-linux-musleabi", "arm-unknown-linux-musleabihf", "arm-w64-mingw32", "arm-w64-mingw32-static", "armv5tel-unknown-linux-gnueabi", "armv5tel-unknown-linux-gnueabi-static", "armv5tel-unknown-linux-gnueabihf", "armv5tel-unknown-linux-gnueabihf-static", "armv5tel-unknown-linux-musleabi", "armv5tel-unknown-linux-musleabi-static", "armv5tel-unknown-linux-musleabihf", "armv5tel-unknown-linux-musleabihf-static", "i386-unknown-linux-musl", "i386-unknown-linux-musl-static", "m68k-unknown-linux-gnu", "m68k-unknown-linux-gnu-static", "m68k-unknown-linux-musl", "m68k-unknown-linux-musl-static", "mips-unknown-linux-musl", "mips-unknown-linux-musl-static", "mips64-unknown-linux-gnuabin32", "mips64-unknown-linux-gnuabin32-static", "mips64-unknown-linux-musl", "mips64-unknown-linux-musl-static", "mips64el-unknown-linux-gnuabin32", "mips64el-unknown-linux-gnuabin32-static", "mips64el-unknown-linux-musl", "mips64el-unknown-linux-musl-static", "mipsel-unknown-linux-musl", "mipsel-unknown-linux-musl-static", "powerpc-unknown-linux-gnueabi", "powerpc-unknown-linux-gnueabi-static", "powerpc-unknown-linux-gnueabihf", "powerpc-unknown-linux-gnueabihf-static", "powerpc-unknown-linux-musl", "powerpc-unknown-linux-musl-static", "powerpc64-unknown-linux-muslabi64", "powerpc64-unknown-linux-muslabi64-static", "powerpc64le-unknown-linux-musl", "powerpc64le-unknown-linux-musl-static", "riscv64-unknown-linux-gnu", "riscv64-unknown-linux-gnu-static", "riscv64-unknown-linux-musl", "riscv64-unknown-linux-musl-static", "s390x-unknown-linux-gnu", "s390x-unknown-linux-gnu-static", "s390x-unknown-linux-musl", "s390x-unknown-linux-musl-static", "sparc-unknown-linux-gnu", "sparc-unknown-linux-gnu-static", "sparc64-unknown-linux-gnu", "sparc64-unknown-linux-gnu-static", "wasm32-unknown-none-musl", "wasm32-unknown-none-musl-static", "x86_64-apple-darwin" ] }
0
repos/nix-zig-stdenv
repos/nix-zig-stdenv/meta/versions.json
{ "master": { "version": "0.12.0-dev.2302+b729a3f00", "date": "2024-01-21", "docs": "https://ziglang.org/documentation/master/", "stdDocs": "https://ziglang.org/documentation/master/std/", "src": { "tarball": "https://ziglang.org/builds/zig-0.12.0-dev.2302+b729a3f00.tar.xz", "shasum": "19050d7b4fd61537cc9cc3912f462ab6edd29cd087f45e4cc4b495d42d9ee378", "size": "17027476" }, "bootstrap": { "tarball": "https://ziglang.org/builds/zig-bootstrap-0.12.0-dev.2302+b729a3f00.tar.xz", "shasum": "435965b79868cd2ac7ec70a976898eaf324729dec2c2a2fa5e8f9a5fc0b95a4a", "size": "45473248" }, "x86_64-macos": { "tarball": "https://ziglang.org/builds/zig-macos-x86_64-0.12.0-dev.2302+b729a3f00.tar.xz", "shasum": "70df0335f2c3b359bef80257cc6b4ffb579ed554928455e2dacd09ce215256e5", "size": "50401404" }, "aarch64-macos": { "tarball": "https://ziglang.org/builds/zig-macos-aarch64-0.12.0-dev.2302+b729a3f00.tar.xz", "shasum": "4722e8602c19f1c09d6482301e8313c4592d44ab20e34ab634d2156c25b5ab34", "size": "46877252" }, "x86_64-linux": { "tarball": "https://ziglang.org/builds/zig-linux-x86_64-0.12.0-dev.2302+b729a3f00.tar.xz", "shasum": "3d49e57b8417bcce69b63e7aa71b44bcaf69e1f496bcaf208f45a8e44811f988", "size": "48120724" }, "aarch64-linux": { "tarball": "https://ziglang.org/builds/zig-linux-aarch64-0.12.0-dev.2302+b729a3f00.tar.xz", "shasum": "841204514617b89d15d729edd15ba7efd014012ea1989ee3abd01befcd645018", "size": "44499604" }, "armv7a-linux": { "tarball": "https://ziglang.org/builds/zig-linux-armv7a-0.12.0-dev.2302+b729a3f00.tar.xz", "shasum": "ef6bb605ce883342093f4eea1e27a1110a9d58830700cd3bec467099a95f374e", "size": "45250784" }, "riscv64-linux": { "tarball": "https://ziglang.org/builds/zig-linux-riscv64-0.12.0-dev.2302+b729a3f00.tar.xz", "shasum": "3c92d1a95784e71dd41b24eaed1027371f3647b07090c251cf4e88ec1e5bb517", "size": "46572592" }, "powerpc64le-linux": { "tarball": "https://ziglang.org/builds/zig-linux-powerpc64le-0.12.0-dev.2302+b729a3f00.tar.xz", "shasum": "bda32857787e952a52faf6241f14c1b5a1eb37b4ec5380deb720c87457f6a6c3", "size": "47884692" }, "powerpc-linux": { "tarball": "https://ziglang.org/builds/zig-linux-powerpc-0.12.0-dev.2302+b729a3f00.tar.xz", "shasum": "62cc3d32306e8a48bbb8f7aec0fd1a1246cc18af5893552db9a5ae25410877f8", "size": "47637096" }, "x86-linux": { "tarball": "https://ziglang.org/builds/zig-linux-x86-0.12.0-dev.2302+b729a3f00.tar.xz", "shasum": "51a82e57029d1a747fa7248c407065679592650a90da4490b281b9c5a97f41f0", "size": "53150500" }, "x86_64-windows": { "tarball": "https://ziglang.org/builds/zig-windows-x86_64-0.12.0-dev.2302+b729a3f00.zip", "shasum": "51684f6c23ee757e8e24b5592c8af0377b0b0fd7990573aa9df47eae74b87969", "size": "82090402" }, "aarch64-windows": { "tarball": "https://ziglang.org/builds/zig-windows-aarch64-0.12.0-dev.2302+b729a3f00.zip", "shasum": "b9965a77f1085df250b1402b5bbfdda007c5a2c93b607ce1b7ba7a6348c1538b", "size": "78667354" }, "x86-windows": { "tarball": "https://ziglang.org/builds/zig-windows-x86-0.12.0-dev.2302+b729a3f00.zip", "shasum": "684b2a2f8f98132e50a7ef0af9b22595ad7e3a699bc8d54d82884ce3e7ec9304", "size": "86597816" } }, "0.11.0": { "date": "2023-08-04", "docs": "https://ziglang.org/documentation/0.11.0/", "stdDocs": "https://ziglang.org/documentation/0.11.0/std/", "notes": "https://ziglang.org/download/0.11.0/release-notes.html", "src": { "tarball": "https://ziglang.org/download/0.11.0/zig-0.11.0.tar.xz", "shasum": "72014e700e50c0d3528cef3adf80b76b26ab27730133e8202716a187a799e951", "size": "15275316" }, "bootstrap": { "tarball": "https://ziglang.org/download/0.11.0/zig-bootstrap-0.11.0.tar.xz", "shasum": "38dd9e17433c7ce5687c48fa0a757462cbfcbe75d9d5087d14ebbe00efd21fdc", "size": "43227592" }, "x86_64-freebsd": { "tarball": "https://ziglang.org/download/0.11.0/zig-freebsd-x86_64-0.11.0.tar.xz", "shasum": "ea430327f9178377b79264a1d492868dcff056cd76d43a6fb00719203749e958", "size": "46432140" }, "x86_64-macos": { "tarball": "https://ziglang.org/download/0.11.0/zig-macos-x86_64-0.11.0.tar.xz", "shasum": "1c1c6b9a906b42baae73656e24e108fd8444bb50b6e8fd03e9e7a3f8b5f05686", "size": "47189164" }, "aarch64-macos": { "tarball": "https://ziglang.org/download/0.11.0/zig-macos-aarch64-0.11.0.tar.xz", "shasum": "c6ebf927bb13a707d74267474a9f553274e64906fd21bf1c75a20bde8cadf7b2", "size": "43855096" }, "x86_64-linux": { "tarball": "https://ziglang.org/download/0.11.0/zig-linux-x86_64-0.11.0.tar.xz", "shasum": "2d00e789fec4f71790a6e7bf83ff91d564943c5ee843c5fd966efc474b423047", "size": "44961892" }, "aarch64-linux": { "tarball": "https://ziglang.org/download/0.11.0/zig-linux-aarch64-0.11.0.tar.xz", "shasum": "956eb095d8ba44ac6ebd27f7c9956e47d92937c103bf754745d0a39cdaa5d4c6", "size": "41492432" }, "armv7a-linux": { "tarball": "https://ziglang.org/download/0.11.0/zig-linux-armv7a-0.11.0.tar.xz", "shasum": "aebe8bbeca39f13f9b7304465f9aee01ab005d243836bd40f4ec808093dccc9b", "size": "42240664" }, "riscv64-linux": { "tarball": "https://ziglang.org/download/0.11.0/zig-linux-riscv64-0.11.0.tar.xz", "shasum": "24a478937eddb507e96d60bd4da00de9092b3f0920190eb45c4c99c946b00ed5", "size": "43532324" }, "powerpc64le-linux": { "tarball": "https://ziglang.org/download/0.11.0/zig-linux-powerpc64le-0.11.0.tar.xz", "shasum": "75260e87325e820a278cf9e74f130c7b3d84c0b5197afb2e3c85eff3fcedd48d", "size": "44656184" }, "powerpc-linux": { "tarball": "https://ziglang.org/download/0.11.0/zig-linux-powerpc-0.11.0.tar.xz", "shasum": "70a5f9668a66fb2a91a7c3488b15bcb568e1f9f44b95cd10075c138ad8c42864", "size": "44539972" }, "x86-linux": { "tarball": "https://ziglang.org/download/0.11.0/zig-linux-x86-0.11.0.tar.xz", "shasum": "7b0dc3e0e070ae0e0d2240b1892af6a1f9faac3516cae24e57f7a0e7b04662a8", "size": "49824456" }, "x86_64-windows": { "tarball": "https://ziglang.org/download/0.11.0/zig-windows-x86_64-0.11.0.zip", "shasum": "142caa3b804d86b4752556c9b6b039b7517a08afa3af842645c7e2dcd125f652", "size": "77216743" }, "aarch64-windows": { "tarball": "https://ziglang.org/download/0.11.0/zig-windows-aarch64-0.11.0.zip", "shasum": "5d4bd13db5ecb0ddc749231e00f125c1d31087d708e9ff9b45c4f4e13e48c661", "size": "73883137" }, "x86-windows": { "tarball": "https://ziglang.org/download/0.11.0/zig-windows-x86-0.11.0.zip", "shasum": "e72b362897f28c671633e650aa05289f2e62b154efcca977094456c8dac3aefa", "size": "81576961" } }, "0.10.1": { "date": "2023-01-19", "docs": "https://ziglang.org/documentation/0.10.1/", "stdDocs": "https://ziglang.org/documentation/0.10.1/std/", "notes": "https://ziglang.org/download/0.10.1/release-notes.html", "src": { "tarball": "https://ziglang.org/download/0.10.1/zig-0.10.1.tar.xz", "shasum": "69459bc804333df077d441ef052ffa143d53012b655a51f04cfef1414c04168c", "size": "15143112" }, "bootstrap": { "tarball": "https://ziglang.org/download/0.10.1/zig-bootstrap-0.10.1.tar.xz", "shasum": "9f5781210b9be8f832553d160851635780f9bd71816065351ab29cfd8968f5e9", "size": "43971816" }, "x86_64-macos": { "tarball": "https://ziglang.org/download/0.10.1/zig-macos-x86_64-0.10.1.tar.xz", "shasum": "02483550b89d2a3070c2ed003357fd6e6a3059707b8ee3fbc0c67f83ca898437", "size": "45119596" }, "aarch64-macos": { "tarball": "https://ziglang.org/download/0.10.1/zig-macos-aarch64-0.10.1.tar.xz", "shasum": "b9b00477ec5fa1f1b89f35a7d2a58688e019910ab80a65eac2a7417162737656", "size": "40517896" }, "x86_64-linux": { "tarball": "https://ziglang.org/download/0.10.1/zig-linux-x86_64-0.10.1.tar.xz", "shasum": "6699f0e7293081b42428f32c9d9c983854094bd15fee5489f12c4cf4518cc380", "size": "44085596" }, "aarch64-linux": { "tarball": "https://ziglang.org/download/0.10.1/zig-linux-aarch64-0.10.1.tar.xz", "shasum": "db0761664f5f22aa5bbd7442a1617dd696c076d5717ddefcc9d8b95278f71f5d", "size": "40321280" }, "riscv64-linux": { "tarball": "https://ziglang.org/download/0.10.1/zig-linux-riscv64-0.10.1.tar.xz", "shasum": "9db5b59a5112b8beb995094ba800e88b0060e9cf7cfadf4dc3e666c9010dc77b", "size": "42196008" }, "i386-linux": { "tarball": "https://ziglang.org/download/0.10.1/zig-linux-i386-0.10.1.tar.xz", "shasum": "8c710ca5966b127b0ee3efba7310601ee57aab3dd6052a082ebc446c5efb2316", "size": "48367388" }, "x86_64-windows": { "tarball": "https://ziglang.org/download/0.10.1/zig-windows-x86_64-0.10.1.zip", "shasum": "5768004e5e274c7969c3892e891596e51c5df2b422d798865471e05049988125", "size": "73259729" }, "aarch64-windows": { "tarball": "https://ziglang.org/download/0.10.1/zig-windows-aarch64-0.10.1.zip", "shasum": "ece93b0d77b2ab03c40db99ef7ccbc63e0b6bd658af12b97898960f621305428", "size": "69417459" } }, "0.10.0": { "date": "2022-10-31", "docs": "https://ziglang.org/documentation/0.10.0/", "stdDocs": "https://ziglang.org/documentation/0.10.0/std/", "notes": "https://ziglang.org/download/0.10.0/release-notes.html", "src": { "tarball": "https://ziglang.org/download/0.10.0/zig-0.10.0.tar.xz", "shasum": "d8409f7aafc624770dcd050c8fa7e62578be8e6a10956bca3c86e8531c64c136", "size": "14530912" }, "bootstrap": { "tarball": "https://ziglang.org/download/0.10.0/zig-bootstrap-0.10.0.tar.xz", "shasum": "c13dc70c4ff4c09f749adc0d473cbd3942991dd4d1bd2d860fbf257d8c1bbabf", "size": "45625516" }, "x86_64-freebsd": { "tarball": "https://ziglang.org/download/0.10.0/zig-freebsd-x86_64-0.10.0.tar.xz", "shasum": "dd77afa2a8676afbf39f7d6068eda81b0723afd728642adaac43cb2106253d65", "size": "44056504" }, "aarch64-linux": { "tarball": "https://ziglang.org/download/0.10.0/zig-linux-aarch64-0.10.0.tar.xz", "shasum": "09ef50c8be73380799804169197820ee78760723b0430fa823f56ed42b06ea0f", "size": "40387688" }, "armv7a-linux": { "tarball": "https://ziglang.org/download/0.10.0/zig-linux-armv7a-0.10.0.tar.xz", "shasum": "7201b2e89cd7cc2dde95d39485fd7d5641ba67dc6a9a58c036cb4c308d2e82de", "size": "50805936" }, "i386-linux": { "tarball": "https://ziglang.org/download/0.10.0/zig-linux-i386-0.10.0.tar.xz", "shasum": "dac8134f1328c50269f3e50b334298ec7916cb3b0ef76927703ddd1c96fd0115", "size": "48451732" }, "riscv64-linux": { "tarball": "https://ziglang.org/download/0.10.0/zig-linux-riscv64-0.10.0.tar.xz", "shasum": "2a126f3401a7a7efc4b454f0a85c133db1af5a9dfee117f172213b7cbd47bfba", "size": "42272968" }, "x86_64-linux": { "tarball": "https://ziglang.org/download/0.10.0/zig-linux-x86_64-0.10.0.tar.xz", "shasum": "631ec7bcb649cd6795abe40df044d2473b59b44e10be689c15632a0458ddea55", "size": "44142400" }, "aarch64-macos": { "tarball": "https://ziglang.org/download/0.10.0/zig-macos-aarch64-0.10.0.tar.xz", "shasum": "02f7a7839b6a1e127eeae22ea72c87603fb7298c58bc35822a951479d53c7557", "size": "40602664" }, "x86_64-macos": { "tarball": "https://ziglang.org/download/0.10.0/zig-macos-x86_64-0.10.0.tar.xz", "shasum": "3a22cb6c4749884156a94ea9b60f3a28cf4e098a69f08c18fbca81c733ebfeda", "size": "45175104" }, "x86_64-windows": { "tarball": "https://ziglang.org/download/0.10.0/zig-windows-x86_64-0.10.0.zip", "shasum": "a66e2ff555c6e48781de1bcb0662ef28ee4b88af3af2a577f7b1950e430897ee", "size": "73181558" }, "aarch64-windows": { "tarball": "https://ziglang.org/download/0.10.0/zig-windows-aarch64-0.10.0.zip", "shasum": "1bbda8d123d44f3ae4fa90d0da04b1e9093c3f9ddae3429a4abece1e1c0bf19a", "size": "69332389" } }, "0.9.1": { "date": "2022-02-14", "docs": "https://ziglang.org/documentation/0.9.1/", "stdDocs": "https://ziglang.org/documentation/0.9.1/std/", "notes": "https://ziglang.org/download/0.9.1/release-notes.html", "src": { "tarball": "https://ziglang.org/download/0.9.1/zig-0.9.1.tar.xz", "shasum": "38cf4e84481f5facc766ba72783e7462e08d6d29a5d47e3b75c8ee3142485210", "size": "13940828" }, "bootstrap": { "tarball": "https://ziglang.org/download/0.9.1/zig-bootstrap-0.9.1.tar.xz", "shasum": "0a8e221c71860d8975c15662b3ed3bd863e81c4fe383455a596e5e0e490d6109", "size": "42488812" }, "x86_64-freebsd": { "tarball": "https://ziglang.org/download/0.9.1/zig-freebsd-x86_64-0.9.1.tar.xz", "shasum": "4e06009bd3ede34b72757eec1b5b291b30aa0d5046dadd16ecb6b34a02411254", "size": "39028848" }, "aarch64-linux": { "tarball": "https://ziglang.org/download/0.9.1/zig-linux-aarch64-0.9.1.tar.xz", "shasum": "5d99a39cded1870a3fa95d4de4ce68ac2610cca440336cfd252ffdddc2b90e66", "size": "37034860" }, "armv7a-linux": { "tarball": "https://ziglang.org/download/0.9.1/zig-linux-armv7a-0.9.1.tar.xz", "shasum": "6de64456cb4757a555816611ea697f86fba7681d8da3e1863fa726a417de49be", "size": "37974652" }, "i386-linux": { "tarball": "https://ziglang.org/download/0.9.1/zig-linux-i386-0.9.1.tar.xz", "shasum": "e776844fecd2e62fc40d94718891057a1dbca1816ff6013369e9a38c874374ca", "size": "44969172" }, "riscv64-linux": { "tarball": "https://ziglang.org/download/0.9.1/zig-linux-riscv64-0.9.1.tar.xz", "shasum": "208dea53662c2c52777bd9e3076115d2126a4f71aed7f2ff3b8fe224dc3881aa", "size": "39390868" }, "x86_64-linux": { "tarball": "https://ziglang.org/download/0.9.1/zig-linux-x86_64-0.9.1.tar.xz", "shasum": "be8da632c1d3273f766b69244d80669fe4f5e27798654681d77c992f17c237d7", "size": "41011464" }, "aarch64-macos": { "tarball": "https://ziglang.org/download/0.9.1/zig-macos-aarch64-0.9.1.tar.xz", "shasum": "8c473082b4f0f819f1da05de2dbd0c1e891dff7d85d2c12b6ee876887d438287", "size": "38995640" }, "x86_64-macos": { "tarball": "https://ziglang.org/download/0.9.1/zig-macos-x86_64-0.9.1.tar.xz", "shasum": "2d94984972d67292b55c1eb1c00de46580e9916575d083003546e9a01166754c", "size": "43713044" }, "i386-windows": { "tarball": "https://ziglang.org/download/0.9.1/zig-windows-i386-0.9.1.zip", "shasum": "74a640ed459914b96bcc572183a8db687bed0af08c30d2ea2f8eba03ae930f69", "size": "67929868" }, "x86_64-windows": { "tarball": "https://ziglang.org/download/0.9.1/zig-windows-x86_64-0.9.1.zip", "shasum": "443da53387d6ae8ba6bac4b3b90e9fef4ecbe545e1c5fa3a89485c36f5c0e3a2", "size": "65047697" }, "aarch64-windows": { "tarball": "https://ziglang.org/download/0.9.1/zig-windows-aarch64-0.9.1.zip", "shasum": "621bf95f54dc3ff71466c5faae67479419951d7489e40e87fd26d195825fb842", "size": "61478151" } }, "0.9.0": { "date": "2021-12-20", "docs": "https://ziglang.org/documentation/0.9.0/", "stdDocs": "https://ziglang.org/documentation/0.9.0/std/", "notes": "https://ziglang.org/download/0.9.0/release-notes.html", "src": { "tarball": "https://ziglang.org/download/0.9.0/zig-0.9.0.tar.xz", "shasum": "cd1be83b12f8269cc5965e59877b49fdd8fa638efb6995ac61eb4cea36a2e381", "size": "13928772" }, "bootstrap": { "tarball": "https://ziglang.org/download/0.9.0/zig-bootstrap-0.9.0.tar.xz", "shasum": "16b0bdf0bc0a5ed1e0950e08481413d806192e06443a512347526647b2baeabc", "size": "42557736" }, "x86_64-freebsd": { "tarball": "https://ziglang.org/download/0.9.0/zig-freebsd-x86_64-0.9.0.tar.xz", "shasum": "c95afe679b7cc4110dc2ecd3606c83a699718b7a958d6627f74c20886333e194", "size": "41293236" }, "aarch64-linux": { "tarball": "https://ziglang.org/download/0.9.0/zig-linux-aarch64-0.9.0.tar.xz", "shasum": "1524fedfdbade2dbc9bae1ed98ad38fa7f2114c9a3e94da0d652573c75efbc5a", "size": "40008396" }, "armv7a-linux": { "tarball": "https://ziglang.org/download/0.9.0/zig-linux-armv7a-0.9.0.tar.xz", "shasum": "50225dee6e6448a63ee96383a34d9fe3bba34ae8da1a0c8619bde2cdfc1df87d", "size": "41196876" }, "i386-linux": { "tarball": "https://ziglang.org/download/0.9.0/zig-linux-i386-0.9.0.tar.xz", "shasum": "b0dcf688349268c883292acdd55eaa3c13d73b9146e4b990fad95b84a2ac528b", "size": "47408656" }, "riscv64-linux": { "tarball": "https://ziglang.org/download/0.9.0/zig-linux-riscv64-0.9.0.tar.xz", "shasum": "85466de07504767ed37f59782672ad41bbdf43d6480fafd07f45543278b07620", "size": "44171420" }, "x86_64-linux": { "tarball": "https://ziglang.org/download/0.9.0/zig-linux-x86_64-0.9.0.tar.xz", "shasum": "5c55344a877d557fb1b28939785474eb7f4f2f327aab55293998f501f7869fa6", "size": "43420796" }, "aarch64-macos": { "tarball": "https://ziglang.org/download/0.9.0/zig-macos-aarch64-0.9.0.tar.xz", "shasum": "3991c70594d61d09fb4b316157a7c1d87b1d4ec159e7a5ecd11169ff74cad832", "size": "39013392" }, "x86_64-macos": { "tarball": "https://ziglang.org/download/0.9.0/zig-macos-x86_64-0.9.0.tar.xz", "shasum": "c5280eeec4d6e5ea5ce5b448dc9a7c4bdd85ecfed4c1b96aa0835e48b36eccf0", "size": "43764596" }, "i386-windows": { "tarball": "https://ziglang.org/download/0.9.0/zig-windows-i386-0.9.0.zip", "shasum": "bb839434afc75092015cf4c33319d31463c18512bc01dd719aedf5dcbc368466", "size": "67946715" }, "x86_64-windows": { "tarball": "https://ziglang.org/download/0.9.0/zig-windows-x86_64-0.9.0.zip", "shasum": "084ea2646850aaf068234b0f1a92b914ed629be47075e835f8a67d55c21d880e", "size": "65045849" }, "aarch64-windows": { "tarball": "https://ziglang.org/download/0.9.0/zig-windows-aarch64-0.9.0.zip", "shasum": "f9018725e3fb2e8992b17c67034726971156eb190685018a9ac8c3a9f7a22340", "size": "61461921" } }, "0.8.1": { "date": "2021-09-06", "docs": "https://ziglang.org/documentation/0.8.1/", "stdDocs": "https://ziglang.org/documentation/0.8.1/std/", "notes": "https://ziglang.org/download/0.8.1/release-notes.html", "src": { "tarball": "https://ziglang.org/download/0.8.1/zig-0.8.1.tar.xz", "shasum": "8c428e14a0a89cb7a15a6768424a37442292858cdb695e2eb503fa3c7bf47f1a", "size": "12650228" }, "bootstrap": { "tarball": "https://ziglang.org/download/0.8.1/zig-bootstrap-0.8.1.tar.xz", "shasum": "fa1239247f830ecd51c42537043f5220e4d1dfefdc54356fa419616a0efb3902", "size": "43613464" }, "x86_64-freebsd": { "tarball": "https://ziglang.org/download/0.8.1/zig-freebsd-x86_64-0.8.1.tar.xz", "shasum": "fc4f6478bcf3a9fce1b8ef677a91694f476dd35be6d6c9c4f44a8b76eedbe176", "size": "39150924" }, "aarch64-linux": { "tarball": "https://ziglang.org/download/0.8.1/zig-linux-aarch64-0.8.1.tar.xz", "shasum": "2166dc9f2d8df387e8b4122883bb979d739281e1ff3f3d5483fec3a23b957510", "size": "37605932" }, "armv7a-linux": { "tarball": "https://ziglang.org/download/0.8.1/zig-linux-armv7a-0.8.1.tar.xz", "shasum": "5ba58141805e2519f38cf8e715933cbf059f4f3dade92c71838cce341045de05", "size": "39185876" }, "i386-linux": { "tarball": "https://ziglang.org/download/0.8.1/zig-linux-i386-0.8.1.tar.xz", "shasum": "2f3e84f30492b5f1c5f97cecc0166f07a8a8d50c5f85dbb3a6ef2a4ee6f915e6", "size": "44782932" }, "riscv64-linux": { "tarball": "https://ziglang.org/download/0.8.1/zig-linux-riscv64-0.8.1.tar.xz", "shasum": "4adfaf147b025917c03367462fe5018aaa9edbc6439ef9cd0da2b074ae960554", "size": "41234480" }, "x86_64-linux": { "tarball": "https://ziglang.org/download/0.8.1/zig-linux-x86_64-0.8.1.tar.xz", "shasum": "6c032fc61b5d77a3f3cf781730fa549f8f059ffdb3b3f6ad1c2994d2b2d87983", "size": "41250060" }, "aarch64-macos": { "tarball": "https://ziglang.org/download/0.8.1/zig-macos-aarch64-0.8.1.tar.xz", "shasum": "5351297e3b8408213514b29c0a938002c5cf9f97eee28c2f32920e1227fd8423", "size": "35340712" }, "x86_64-macos": { "tarball": "https://ziglang.org/download/0.8.1/zig-macos-x86_64-0.8.1.tar.xz", "shasum": "16b0e1defe4c1807f2e128f72863124bffdd906cefb21043c34b673bf85cd57f", "size": "39946200" }, "i386-windows": { "tarball": "https://ziglang.org/download/0.8.1/zig-windows-i386-0.8.1.zip", "shasum": "099605051eb0452a947c8eab8fbbc7e43833c8376d267e94e41131c289a1c535", "size": "64152358" }, "x86_64-windows": { "tarball": "https://ziglang.org/download/0.8.1/zig-windows-x86_64-0.8.1.zip", "shasum": "43573db14cd238f7111d6bdf37492d363f11ecd1eba802567a172f277d003926", "size": "61897838" } }, "0.8.0": { "date": "2021-06-04", "docs": "https://ziglang.org/documentation/0.8.0/", "stdDocs": "https://ziglang.org/documentation/0.8.0/std/", "notes": "https://ziglang.org/download/0.8.0/release-notes.html", "src": { "tarball": "https://ziglang.org/download/0.8.0/zig-0.8.0.tar.xz", "shasum": "03a828d00c06b2e3bb8b7ff706997fd76bf32503b08d759756155b6e8c981e77", "size": "12614896" }, "bootstrap": { "tarball": "https://ziglang.org/download/0.8.0/zig-bootstrap-0.8.0.tar.xz", "shasum": "10600bc9c01f92e343f40d6ecc0ad05d67d27c3e382bce75524c0639cd8ca178", "size": "43574248" }, "x86_64-freebsd": { "tarball": "https://ziglang.org/download/0.8.0/zig-freebsd-x86_64-0.8.0.tar.xz", "shasum": "0d3ccc436c8c0f50fd55462f72f8492d98723c7218ffc2a8a1831967d81b4bdc", "size": "39125332" }, "aarch64-linux": { "tarball": "https://ziglang.org/download/0.8.0/zig-linux-aarch64-0.8.0.tar.xz", "shasum": "ee204ca2c2037952cf3f8b10c609373a08a291efa4af7b3c73be0f2b27720470", "size": "37575428" }, "armv7a-linux": { "tarball": "https://ziglang.org/download/0.8.0/zig-linux-armv7a-0.8.0.tar.xz", "shasum": "d00b8bd97b79f45d6f5da956983bafeaa082e6c2ae8c6e1c6d4faa22fa29b320", "size": "38884212" }, "i386-linux": { "tarball": "https://ziglang.org/download/0.8.0/zig-linux-i386-0.8.0.tar.xz", "shasum": "96e43ee6ed81c3c63401f456bd1c58ee6d42373a43cb324f5cf4974ca0998865", "size": "42136032" }, "riscv64-linux": { "tarball": "https://ziglang.org/download/0.8.0/zig-linux-riscv64-0.8.0.tar.xz", "shasum": "75997527a78cdab64c40c43d9df39c01c4cdb557bb3992a869838371a204cfea", "size": "40016268" }, "x86_64-linux": { "tarball": "https://ziglang.org/download/0.8.0/zig-linux-x86_64-0.8.0.tar.xz", "shasum": "502625d3da3ae595c5f44a809a87714320b7a40e6dff4a895b5fa7df3391d01e", "size": "41211184" }, "aarch64-macos": { "tarball": "https://ziglang.org/download/0.8.0/zig-macos-aarch64-0.8.0.tar.xz", "shasum": "b32d13f66d0e1ff740b3326d66a469ee6baddbd7211fa111c066d3bd57683111", "size": "35292180" }, "x86_64-macos": { "tarball": "https://ziglang.org/download/0.8.0/zig-macos-x86_64-0.8.0.tar.xz", "shasum": "279f9360b5cb23103f0395dc4d3d0d30626e699b1b4be55e98fd985b62bc6fbe", "size": "39969312" }, "i386-windows": { "tarball": "https://ziglang.org/download/0.8.0/zig-windows-i386-0.8.0.zip", "shasum": "b6ec9aa6cd6f3872fcb30d43ff411802d82008a0c4142ee49e208a09b2c1c5fe", "size": "61507213" }, "x86_64-windows": { "tarball": "https://ziglang.org/download/0.8.0/zig-windows-x86_64-0.8.0.zip", "shasum": "8580fbbf3afb72e9b495c7f8aeac752a03475ae0bbcf5d787f3775c7e1f4f807", "size": "61766193" } } }
0
repos/nix-zig-stdenv
repos/nix-zig-stdenv/test/default.nix
{ allow-broken ? true }: with builtins; let overlay = (self: super: { super-simple = let src = self.writeText "hello.c" '' #include <stdio.h> int main() { printf("hello world\n"); return 0; } ''; in self.stdenv.mkDerivation { name = "hello"; dontUnpack = true; dontConfigure = true; buildPhase = "$CC ${src} -o hello"; installPhase = "install -Dm755 hello -t $out"; }; }); layer = import <nixpkgs> { overlays = [ overlay (import ../overlay.nix { allowBroken = allow-broken; }) ]; }; in with layer; with layer.lib; { inherit zigVersions; list-versions = attrNames zigVersions; list-targets = { version }: attrNames zigVersions.${version}.targets; install-version = { version }: zigVersions."${version}".zig; build-package = { version, target, package }: zigVersions."${version}".targets."${target}".pkgs."${package}"; }
0
repos
repos/zeit/README.md
# zeit A time library written in zig. ## Usage [API Documentation](https://rockorager.github.io/zeit/) ```zig const std = @import("std"); const zeit = @import("zeit"); pub fn main() void { const allocator = std.heap.page_allocator; var env = try std.process.getEnvMap(allocator); defer env.deinit(); // Get an instant in time. The default gets "now" in UTC const now = zeit.instant(.{}); // Load our local timezone. This needs an allocator. Optionally pass in a // *const std.process.EnvMap to support TZ and TZDIR environment variables const local = zeit.local(alloc, &env); // Convert our instant to a new timezone const now_local = now.in(&local); // Generate date/time info for this instant const dt = now_local.time(); // Print it out std.debug.print("{}", .{dt}); // zeit.Time{ // .year = 2024, // .month = zeit.Month.mar, // .day = 16, // .hour = 8, // .minute = 38, // .second = 29, // .millisecond = 496, // .microsecond = 706, // .nanosecond = 64 // .offset = -18000, // } // Load an arbitrary location using IANA location syntax. The location name // comes from an enum which will automatically map IANA location names to // Windows names, as needed. Pass an optional EnvMap to support TZDIR const vienna = zeit.loadTimeZone(alloc, .@"Europe/Vienna", &env); defer vienna.deinit(); // Parse an Instant from an ISO8601 or RFC3339 string const iso = zeit.instant(.{ .source = .{ .iso8601 = "2024-03-16T08:38:29.496-1200", }, }); const rfc3339 = zeit.instant(.{ .source = .{ .rfc3339 = "2024-03-16T08:38:29.496706064-1200", }, }); } ```
0
repos
repos/zeit/build.zig.zon
.{ .name = "zeit", .version = "0.0.0", .dependencies = .{}, .paths = .{ "LICENSE", "build.zig", "build.zig.zon", "src", }, }
0
repos
repos/zeit/build.zig
const std = @import("std"); /// Allow the full zeit API to be usable at build time pub usingnamespace @import("src/zeit.zig"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); _ = b.addModule("zeit", .{ .root_source_file = b.path("src/zeit.zig"), .target = target, .optimize = optimize, }); const lib_unit_tests = b.addTest(.{ .root_source_file = b.path("src/zeit.zig"), .target = target, .optimize = optimize, }); const run_lib_unit_tests = b.addRunArtifact(lib_unit_tests); const test_step = b.step("test", "Run unit tests"); test_step.dependOn(&run_lib_unit_tests.step); const gen_step = b.step("generate", "Update timezone names"); const gen = b.addExecutable(.{ .name = "generate", .root_source_file = b.path("gen/main.zig"), .target = target, .optimize = optimize, }); const fmt = b.addFmt( .{ .paths = &.{"src/location.zig"} }, ); const gen_run = b.addRunArtifact(gen); fmt.step.dependOn(&gen_run.step); gen_step.dependOn(&fmt.step); // Docs { const docs_step = b.step("docs", "Build the zeit docs"); const docs_obj = b.addObject(.{ .name = "zeit", .root_source_file = b.path("src/zeit.zig"), .target = target, .optimize = optimize, }); const docs = docs_obj.getEmittedDocs(); docs_step.dependOn(&b.addInstallDirectory(.{ .source_dir = docs, .install_dir = .prefix, .install_subdir = "docs", }).step); } }
0
repos/zeit
repos/zeit/gen/main.zig
//! Generates zig code for well-known timezones. Makes an enum of the "posix" style name //! ("America/Chicago") and a function to return the timezone name as text. The name as text is //! portable by platform: on Windows it will return the Windows name of this timezone //! //! Source data available at https://github.com/unicode-org/cldr/blob/main/common/supplemental/windowsZones.xml const std = @import("std"); pub fn main() !void { const allocator = std.heap.page_allocator; const data = @embedFile("windowsZones.xml"); var zones = std.ArrayList(MapZone).init(allocator); var read_idx: usize = 0; while (read_idx < data.len) { const eol = std.mem.indexOfScalarPos(u8, data, read_idx, '\n') orelse data.len; defer read_idx = eol + 1; const input_line = data[read_idx..eol]; const line = std.mem.trimRight(u8, std.mem.trim(u8, input_line, " \t<>"), "/"); if (!std.mem.startsWith(u8, line, "mapZone")) continue; var idx: usize = 0; const windows = blk: { idx = std.mem.indexOfScalarPos(u8, line, idx, '"') orelse unreachable; const start = idx + 1; idx = std.mem.indexOfScalarPos(u8, line, start, '"') orelse unreachable; const end = idx; break :blk line[start..end]; }; const territory = blk: { idx = std.mem.indexOfScalarPos(u8, line, idx + 1, '"') orelse unreachable; const start = idx + 1; idx = std.mem.indexOfScalarPos(u8, line, start, '"') orelse unreachable; const end = idx; break :blk line[start..end]; }; const posix = blk: { idx = std.mem.indexOfScalarPos(u8, line, idx + 1, '"') orelse unreachable; const start = idx + 1; idx = std.mem.indexOfScalarPos(u8, line, start, '"') orelse unreachable; const end = idx; break :blk line[start..end]; }; var iter = std.mem.splitScalar(u8, posix, ' '); while (iter.next()) |psx| { const map_zone: MapZone = .{ .windows = windows, .territory = territory, .posix = psx, }; if (psx.len == 0) continue; for (zones.items) |item| { if (std.mem.eql(u8, item.windows, map_zone.windows) and std.mem.eql(u8, item.posix, map_zone.posix)) break; } else try zones.append(map_zone); } } std.mem.sort(MapZone, zones.items, {}, lessThan); const out = try std.fs.cwd().createFile("src/location.zig", .{}); defer out.close(); try writeFile(zones.items, out.writer().any()); } fn lessThan(_: void, lhs: MapZone, rhs: MapZone) bool { return std.mem.order(u8, lhs.posix, rhs.posix).compare(.lt); } const MapZone = struct { windows: []const u8, territory: []const u8, posix: []const u8, }; fn writeFile(items: []const MapZone, writer: std.io.AnyWriter) !void { try writer.writeAll( \\//!This file is generated. Do not edit directly! Run `zig build generate` to update after obtaining \\//!the latest dataset. \\ \\const builtin = @import("builtin"); \\pub const Location = enum { \\ ); for (items) |item| { try writer.print("@\"{s}\",\n", .{item.posix}); } try writer.writeAll("\n"); try writer.writeAll( \\ pub fn asText(self: Location) []const u8 { \\ switch (builtin.os.tag) { \\ .windows => {}, \\ else => return @tagName(self), \\ } ); try writer.writeAll(" return switch (self) {\n"); for (items) |item| { try writer.print(".@\"{s}\" => \"{s}\",\n", .{ item.posix, item.windows }); } try writer.writeAll("};}};"); }
0
repos/zeit
repos/zeit/gen/windowsZones.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE supplementalData SYSTEM "../../common/dtd/ldmlSupplemental.dtd"> <!-- Copyright © 1991-2013 Unicode, Inc. CLDR data files are interpreted according to the LDML specification (http://unicode.org/reports/tr35/) For terms of use, see http://www.unicode.org/copyright.html --> <supplementalData> <version number="$Revision$"/> <windowsZones> <mapTimezones otherVersion="7e11800" typeVersion="2021a"> <!-- (UTC-12:00) International Date Line West --> <mapZone other="Dateline Standard Time" territory="001" type="Etc/GMT+12"/> <mapZone other="Dateline Standard Time" territory="ZZ" type="Etc/GMT+12"/> <!-- (UTC-11:00) Coordinated Universal Time-11 --> <mapZone other="UTC-11" territory="001" type="Etc/GMT+11"/> <mapZone other="UTC-11" territory="AS" type="Pacific/Pago_Pago"/> <mapZone other="UTC-11" territory="NU" type="Pacific/Niue"/> <mapZone other="UTC-11" territory="UM" type="Pacific/Midway"/> <mapZone other="UTC-11" territory="ZZ" type="Etc/GMT+11"/> <!-- (UTC-10:00) Aleutian Islands --> <mapZone other="Aleutian Standard Time" territory="001" type="America/Adak"/> <mapZone other="Aleutian Standard Time" territory="US" type="America/Adak"/> <!-- (UTC-10:00) Hawaii --> <mapZone other="Hawaiian Standard Time" territory="001" type="Pacific/Honolulu"/> <mapZone other="Hawaiian Standard Time" territory="CK" type="Pacific/Rarotonga"/> <mapZone other="Hawaiian Standard Time" territory="PF" type="Pacific/Tahiti"/> <mapZone other="Hawaiian Standard Time" territory="US" type="Pacific/Honolulu"/> <mapZone other="Hawaiian Standard Time" territory="ZZ" type="Etc/GMT+10"/> <!-- (UTC-09:30) Marquesas Islands --> <mapZone other="Marquesas Standard Time" territory="001" type="Pacific/Marquesas"/> <mapZone other="Marquesas Standard Time" territory="PF" type="Pacific/Marquesas"/> <!-- (UTC-09:00) Alaska --> <mapZone other="Alaskan Standard Time" territory="001" type="America/Anchorage"/> <mapZone other="Alaskan Standard Time" territory="US" type="America/Anchorage America/Juneau America/Metlakatla America/Nome America/Sitka America/Yakutat"/> <!-- (UTC-09:00) Coordinated Universal Time-09 --> <mapZone other="UTC-09" territory="001" type="Etc/GMT+9"/> <mapZone other="UTC-09" territory="PF" type="Pacific/Gambier"/> <mapZone other="UTC-09" territory="ZZ" type="Etc/GMT+9"/> <!-- (UTC-08:00) Baja California --> <mapZone other="Pacific Standard Time (Mexico)" territory="001" type="America/Tijuana"/> <mapZone other="Pacific Standard Time (Mexico)" territory="MX" type="America/Tijuana"/> <!-- (UTC-08:00) Coordinated Universal Time-08 --> <mapZone other="UTC-08" territory="001" type="Etc/GMT+8"/> <mapZone other="UTC-08" territory="PN" type="Pacific/Pitcairn"/> <mapZone other="UTC-08" territory="ZZ" type="Etc/GMT+8"/> <!-- (UTC-08:00) Pacific Time (US & Canada) --> <mapZone other="Pacific Standard Time" territory="001" type="America/Los_Angeles"/> <mapZone other="Pacific Standard Time" territory="CA" type="America/Vancouver"/> <mapZone other="Pacific Standard Time" territory="US" type="America/Los_Angeles"/> <mapZone other="Pacific Standard Time" territory="ZZ" type="PST8PDT"/> <!-- (UTC-07:00) Arizona --> <mapZone other="US Mountain Standard Time" territory="001" type="America/Phoenix"/> <mapZone other="US Mountain Standard Time" territory="CA" type="America/Creston America/Dawson_Creek America/Fort_Nelson"/> <mapZone other="US Mountain Standard Time" territory="MX" type="America/Hermosillo"/> <mapZone other="US Mountain Standard Time" territory="US" type="America/Phoenix"/> <mapZone other="US Mountain Standard Time" territory="ZZ" type="Etc/GMT+7"/> <!-- (UTC-07:00) Chihuahua, La Paz, Mazatlan --> <mapZone other="Mountain Standard Time (Mexico)" territory="001" type="America/Mazatlan"/> <mapZone other="Mountain Standard Time (Mexico)" territory="MX" type="America/Mazatlan"/> <!-- (UTC-07:00) Mountain Time (US & Canada) --> <mapZone other="Mountain Standard Time" territory="001" type="America/Denver"/> <mapZone other="Mountain Standard Time" territory="CA" type="America/Edmonton America/Cambridge_Bay America/Inuvik"/> <mapZone other="Mountain Standard Time" territory="MX" type="America/Ciudad_Juarez"/> <mapZone other="Mountain Standard Time" territory="US" type="America/Denver America/Boise"/> <mapZone other="Mountain Standard Time" territory="ZZ" type="MST7MDT"/> <!-- (UTC-07:00) Yukon --> <mapZone other="Yukon Standard Time" territory="001" type="America/Whitehorse"/> <mapZone other="Yukon Standard Time" territory="CA" type="America/Whitehorse America/Dawson"/> <!-- (UTC-06:00) Central America --> <mapZone other="Central America Standard Time" territory="001" type="America/Guatemala"/> <mapZone other="Central America Standard Time" territory="BZ" type="America/Belize"/> <mapZone other="Central America Standard Time" territory="CR" type="America/Costa_Rica"/> <mapZone other="Central America Standard Time" territory="EC" type="Pacific/Galapagos"/> <mapZone other="Central America Standard Time" territory="GT" type="America/Guatemala"/> <mapZone other="Central America Standard Time" territory="HN" type="America/Tegucigalpa"/> <mapZone other="Central America Standard Time" territory="NI" type="America/Managua"/> <mapZone other="Central America Standard Time" territory="SV" type="America/El_Salvador"/> <mapZone other="Central America Standard Time" territory="ZZ" type="Etc/GMT+6"/> <!-- (UTC-06:00) Central Time (US & Canada) --> <mapZone other="Central Standard Time" territory="001" type="America/Chicago"/> <mapZone other="Central Standard Time" territory="CA" type="America/Winnipeg America/Rankin_Inlet America/Resolute"/> <mapZone other="Central Standard Time" territory="MX" type="America/Matamoros America/Ojinaga"/> <mapZone other="Central Standard Time" territory="US" type="America/Chicago America/Indiana/Knox America/Indiana/Tell_City America/Menominee America/North_Dakota/Beulah America/North_Dakota/Center America/North_Dakota/New_Salem"/> <mapZone other="Central Standard Time" territory="ZZ" type="CST6CDT"/> <!-- (UTC-06:00) Easter Island --> <mapZone other="Easter Island Standard Time" territory="001" type="Pacific/Easter"/> <mapZone other="Easter Island Standard Time" territory="CL" type="Pacific/Easter"/> <!-- (UTC-06:00) Guadalajara, Mexico City, Monterrey --> <mapZone other="Central Standard Time (Mexico)" territory="001" type="America/Mexico_City"/> <mapZone other="Central Standard Time (Mexico)" territory="MX" type="America/Mexico_City America/Bahia_Banderas America/Merida America/Monterrey America/Chihuahua "/> <!-- (UTC-06:00) Saskatchewan --> <mapZone other="Canada Central Standard Time" territory="001" type="America/Regina"/> <mapZone other="Canada Central Standard Time" territory="CA" type="America/Regina America/Swift_Current"/> <!-- (UTC-05:00) Bogota, Lima, Quito, Rio Branco --> <mapZone other="SA Pacific Standard Time" territory="001" type="America/Bogota"/> <mapZone other="SA Pacific Standard Time" territory="BR" type="America/Rio_Branco America/Eirunepe"/> <mapZone other="SA Pacific Standard Time" territory="CA" type="America/Coral_Harbour"/> <mapZone other="SA Pacific Standard Time" territory="CO" type="America/Bogota"/> <mapZone other="SA Pacific Standard Time" territory="EC" type="America/Guayaquil"/> <mapZone other="SA Pacific Standard Time" territory="JM" type="America/Jamaica"/> <mapZone other="SA Pacific Standard Time" territory="KY" type="America/Cayman"/> <mapZone other="SA Pacific Standard Time" territory="PA" type="America/Panama"/> <mapZone other="SA Pacific Standard Time" territory="PE" type="America/Lima"/> <mapZone other="SA Pacific Standard Time" territory="ZZ" type="Etc/GMT+5"/> <!-- (UTC-05:00) Chetumal --> <mapZone other="Eastern Standard Time (Mexico)" territory="001" type="America/Cancun"/> <mapZone other="Eastern Standard Time (Mexico)" territory="MX" type="America/Cancun"/> <!-- (UTC-05:00) Eastern Time (US & Canada) --> <mapZone other="Eastern Standard Time" territory="001" type="America/New_York"/> <mapZone other="Eastern Standard Time" territory="BS" type="America/Nassau"/> <mapZone other="Eastern Standard Time" territory="CA" type="America/Toronto America/Iqaluit"/> <mapZone other="Eastern Standard Time" territory="US" type="America/New_York America/Detroit America/Indiana/Petersburg America/Indiana/Vincennes America/Indiana/Winamac America/Kentucky/Monticello America/Louisville"/> <mapZone other="Eastern Standard Time" territory="ZZ" type="EST5EDT"/> <!-- (UTC-05:00) Haiti --> <mapZone other="Haiti Standard Time" territory="001" type="America/Port-au-Prince"/> <mapZone other="Haiti Standard Time" territory="HT" type="America/Port-au-Prince"/> <!-- (UTC-05:00) Havana --> <mapZone other="Cuba Standard Time" territory="001" type="America/Havana"/> <mapZone other="Cuba Standard Time" territory="CU" type="America/Havana"/> <!-- (UTC-05:00) Indiana (East) --> <mapZone other="US Eastern Standard Time" territory="001" type="America/Indianapolis"/> <mapZone other="US Eastern Standard Time" territory="US" type="America/Indianapolis America/Indiana/Marengo America/Indiana/Vevay"/> <!-- (UTC-05:00) Turks and Caicos --> <mapZone other="Turks And Caicos Standard Time" territory="001" type="America/Grand_Turk"/> <mapZone other="Turks And Caicos Standard Time" territory="TC" type="America/Grand_Turk"/> <!-- (UTC-04:00) Asuncion --> <mapZone other="Paraguay Standard Time" territory="001" type="America/Asuncion"/> <mapZone other="Paraguay Standard Time" territory="PY" type="America/Asuncion"/> <!-- (UTC-04:00) Atlantic Time (Canada) --> <mapZone other="Atlantic Standard Time" territory="001" type="America/Halifax"/> <mapZone other="Atlantic Standard Time" territory="BM" type="Atlantic/Bermuda"/> <mapZone other="Atlantic Standard Time" territory="CA" type="America/Halifax America/Glace_Bay America/Goose_Bay America/Moncton"/> <mapZone other="Atlantic Standard Time" territory="GL" type="America/Thule"/> <!-- (UTC-04:00) Caracas --> <mapZone other="Venezuela Standard Time" territory="001" type="America/Caracas"/> <mapZone other="Venezuela Standard Time" territory="VE" type="America/Caracas"/> <!-- (UTC-04:00) Cuiaba --> <mapZone other="Central Brazilian Standard Time" territory="001" type="America/Cuiaba"/> <mapZone other="Central Brazilian Standard Time" territory="BR" type="America/Cuiaba America/Campo_Grande"/> <!-- (UTC-04:00) Georgetown, La Paz, Manaus, San Juan --> <mapZone other="SA Western Standard Time" territory="001" type="America/La_Paz"/> <mapZone other="SA Western Standard Time" territory="AG" type="America/Antigua"/> <mapZone other="SA Western Standard Time" territory="AI" type="America/Anguilla"/> <mapZone other="SA Western Standard Time" territory="AW" type="America/Aruba"/> <mapZone other="SA Western Standard Time" territory="BB" type="America/Barbados"/> <mapZone other="SA Western Standard Time" territory="BL" type="America/St_Barthelemy"/> <mapZone other="SA Western Standard Time" territory="BO" type="America/La_Paz"/> <mapZone other="SA Western Standard Time" territory="BQ" type="America/Kralendijk"/> <mapZone other="SA Western Standard Time" territory="BR" type="America/Manaus America/Boa_Vista America/Porto_Velho"/> <mapZone other="SA Western Standard Time" territory="CA" type="America/Blanc-Sablon"/> <mapZone other="SA Western Standard Time" territory="CW" type="America/Curacao"/> <mapZone other="SA Western Standard Time" territory="DM" type="America/Dominica"/> <mapZone other="SA Western Standard Time" territory="DO" type="America/Santo_Domingo"/> <mapZone other="SA Western Standard Time" territory="GD" type="America/Grenada"/> <mapZone other="SA Western Standard Time" territory="GP" type="America/Guadeloupe"/> <mapZone other="SA Western Standard Time" territory="GY" type="America/Guyana"/> <mapZone other="SA Western Standard Time" territory="KN" type="America/St_Kitts"/> <mapZone other="SA Western Standard Time" territory="LC" type="America/St_Lucia"/> <mapZone other="SA Western Standard Time" territory="MF" type="America/Marigot"/> <mapZone other="SA Western Standard Time" territory="MQ" type="America/Martinique"/> <mapZone other="SA Western Standard Time" territory="MS" type="America/Montserrat"/> <mapZone other="SA Western Standard Time" territory="PR" type="America/Puerto_Rico"/> <mapZone other="SA Western Standard Time" territory="SX" type="America/Lower_Princes"/> <mapZone other="SA Western Standard Time" territory="TT" type="America/Port_of_Spain"/> <mapZone other="SA Western Standard Time" territory="VC" type="America/St_Vincent"/> <mapZone other="SA Western Standard Time" territory="VG" type="America/Tortola"/> <mapZone other="SA Western Standard Time" territory="VI" type="America/St_Thomas"/> <mapZone other="SA Western Standard Time" territory="ZZ" type="Etc/GMT+4"/> <!-- (UTC-04:00) Santiago --> <mapZone other="Pacific SA Standard Time" territory="001" type="America/Santiago"/> <mapZone other="Pacific SA Standard Time" territory="CL" type="America/Santiago"/> <!-- (UTC-03:30) Newfoundland --> <mapZone other="Newfoundland Standard Time" territory="001" type="America/St_Johns"/> <mapZone other="Newfoundland Standard Time" territory="CA" type="America/St_Johns"/> <!-- (UTC-03:00) Araguaina --> <mapZone other="Tocantins Standard Time" territory="001" type="America/Araguaina"/> <mapZone other="Tocantins Standard Time" territory="BR" type="America/Araguaina"/> <!-- (UTC-03:00) Brasilia --> <mapZone other="E. South America Standard Time" territory="001" type="America/Sao_Paulo"/> <mapZone other="E. South America Standard Time" territory="BR" type="America/Sao_Paulo"/> <!-- (UTC-03:00) Cayenne, Fortaleza --> <mapZone other="SA Eastern Standard Time" territory="001" type="America/Cayenne"/> <mapZone other="SA Eastern Standard Time" territory="AQ" type="Antarctica/Rothera Antarctica/Palmer"/> <mapZone other="SA Eastern Standard Time" territory="BR" type="America/Fortaleza America/Belem America/Maceio America/Recife America/Santarem"/> <mapZone other="SA Eastern Standard Time" territory="FK" type="Atlantic/Stanley"/> <mapZone other="SA Eastern Standard Time" territory="GF" type="America/Cayenne"/> <mapZone other="SA Eastern Standard Time" territory="SR" type="America/Paramaribo"/> <mapZone other="SA Eastern Standard Time" territory="ZZ" type="Etc/GMT+3"/> <!-- (UTC-03:00) City of Buenos Aires --> <mapZone other="Argentina Standard Time" territory="001" type="America/Buenos_Aires"/> <mapZone other="Argentina Standard Time" territory="AR" type="America/Buenos_Aires America/Argentina/La_Rioja America/Argentina/Rio_Gallegos America/Argentina/Salta America/Argentina/San_Juan America/Argentina/San_Luis America/Argentina/Tucuman America/Argentina/Ushuaia America/Catamarca America/Cordoba America/Jujuy America/Mendoza"/> <!-- (UTC-03:00) Greenland --> <mapZone other="Greenland Standard Time" territory="001" type="America/Godthab"/> <mapZone other="Greenland Standard Time" territory="GL" type="America/Godthab"/> <!-- (UTC-03:00) Montevideo --> <mapZone other="Montevideo Standard Time" territory="001" type="America/Montevideo"/> <mapZone other="Montevideo Standard Time" territory="UY" type="America/Montevideo"/> <!-- (UTC-03:00) Punta Arenas --> <mapZone other="Magallanes Standard Time" territory="001" type="America/Punta_Arenas"/> <mapZone other="Magallanes Standard Time" territory="CL" type="America/Punta_Arenas"/> <!-- (UTC-03:00) Saint Pierre and Miquelon --> <mapZone other="Saint Pierre Standard Time" territory="001" type="America/Miquelon"/> <mapZone other="Saint Pierre Standard Time" territory="PM" type="America/Miquelon"/> <!-- (UTC-03:00) Salvador --> <mapZone other="Bahia Standard Time" territory="001" type="America/Bahia"/> <mapZone other="Bahia Standard Time" territory="BR" type="America/Bahia"/> <!-- (UTC-02:00) Coordinated Universal Time-02 --> <mapZone other="UTC-02" territory="001" type="Etc/GMT+2"/> <mapZone other="UTC-02" territory="BR" type="America/Noronha"/> <mapZone other="UTC-02" territory="GS" type="Atlantic/South_Georgia"/> <mapZone other="UTC-02" territory="ZZ" type="Etc/GMT+2"/> <!-- (UTC-01:00) Azores --> <mapZone other="Azores Standard Time" territory="001" type="Atlantic/Azores"/> <mapZone other="Azores Standard Time" territory="GL" type="America/Scoresbysund"/> <mapZone other="Azores Standard Time" territory="PT" type="Atlantic/Azores"/> <!-- (UTC-01:00) Cabo Verde Is. --> <mapZone other="Cape Verde Standard Time" territory="001" type="Atlantic/Cape_Verde"/> <mapZone other="Cape Verde Standard Time" territory="CV" type="Atlantic/Cape_Verde"/> <mapZone other="Cape Verde Standard Time" territory="ZZ" type="Etc/GMT+1"/> <!-- (UTC) Coordinated Universal Time --> <mapZone other="UTC" territory="001" type="Etc/UTC"/> <mapZone other="UTC" territory="ZZ" type="Etc/UTC Etc/GMT"/> <!-- (UTC+00:00) Dublin, Edinburgh, Lisbon, London --> <mapZone other="GMT Standard Time" territory="001" type="Europe/London"/> <mapZone other="GMT Standard Time" territory="ES" type="Atlantic/Canary"/> <mapZone other="GMT Standard Time" territory="FO" type="Atlantic/Faeroe"/> <mapZone other="GMT Standard Time" territory="GB" type="Europe/London"/> <mapZone other="GMT Standard Time" territory="GG" type="Europe/Guernsey"/> <mapZone other="GMT Standard Time" territory="IE" type="Europe/Dublin"/> <mapZone other="GMT Standard Time" territory="IM" type="Europe/Isle_of_Man"/> <mapZone other="GMT Standard Time" territory="JE" type="Europe/Jersey"/> <mapZone other="GMT Standard Time" territory="PT" type="Europe/Lisbon Atlantic/Madeira"/> <!-- (UTC+00:00) Monrovia, Reykjavik --> <mapZone other="Greenwich Standard Time" territory="001" type="Atlantic/Reykjavik"/> <mapZone other="Greenwich Standard Time" territory="BF" type="Africa/Ouagadougou"/> <mapZone other="Greenwich Standard Time" territory="CI" type="Africa/Abidjan"/> <mapZone other="Greenwich Standard Time" territory="GH" type="Africa/Accra"/> <mapZone other="Greenwich Standard Time" territory="GL" type="America/Danmarkshavn"/> <mapZone other="Greenwich Standard Time" territory="GM" type="Africa/Banjul"/> <mapZone other="Greenwich Standard Time" territory="GN" type="Africa/Conakry"/> <mapZone other="Greenwich Standard Time" territory="GW" type="Africa/Bissau"/> <mapZone other="Greenwich Standard Time" territory="IS" type="Atlantic/Reykjavik"/> <mapZone other="Greenwich Standard Time" territory="LR" type="Africa/Monrovia"/> <mapZone other="Greenwich Standard Time" territory="ML" type="Africa/Bamako"/> <mapZone other="Greenwich Standard Time" territory="MR" type="Africa/Nouakchott"/> <mapZone other="Greenwich Standard Time" territory="SH" type="Atlantic/St_Helena"/> <mapZone other="Greenwich Standard Time" territory="SL" type="Africa/Freetown"/> <mapZone other="Greenwich Standard Time" territory="SN" type="Africa/Dakar"/> <mapZone other="Greenwich Standard Time" territory="TG" type="Africa/Lome"/> <!-- (UTC+00:00) Sao Tome --> <mapZone other="Sao Tome Standard Time" territory="001" type="Africa/Sao_Tome"/> <mapZone other="Sao Tome Standard Time" territory="ST" type="Africa/Sao_Tome"/> <!-- (UTC+01:00) Casablanca --> <mapZone other="Morocco Standard Time" territory="001" type="Africa/Casablanca"/> <mapZone other="Morocco Standard Time" territory="EH" type="Africa/El_Aaiun"/> <mapZone other="Morocco Standard Time" territory="MA" type="Africa/Casablanca"/> <!-- (UTC+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna --> <mapZone other="W. Europe Standard Time" territory="001" type="Europe/Berlin"/> <mapZone other="W. Europe Standard Time" territory="AD" type="Europe/Andorra"/> <mapZone other="W. Europe Standard Time" territory="AT" type="Europe/Vienna"/> <mapZone other="W. Europe Standard Time" territory="CH" type="Europe/Zurich"/> <mapZone other="W. Europe Standard Time" territory="DE" type="Europe/Berlin Europe/Busingen"/> <mapZone other="W. Europe Standard Time" territory="GI" type="Europe/Gibraltar"/> <mapZone other="W. Europe Standard Time" territory="IT" type="Europe/Rome"/> <mapZone other="W. Europe Standard Time" territory="LI" type="Europe/Vaduz"/> <mapZone other="W. Europe Standard Time" territory="LU" type="Europe/Luxembourg"/> <mapZone other="W. Europe Standard Time" territory="MC" type="Europe/Monaco"/> <mapZone other="W. Europe Standard Time" territory="MT" type="Europe/Malta"/> <mapZone other="W. Europe Standard Time" territory="NL" type="Europe/Amsterdam"/> <mapZone other="W. Europe Standard Time" territory="NO" type="Europe/Oslo"/> <mapZone other="W. Europe Standard Time" territory="SE" type="Europe/Stockholm"/> <mapZone other="W. Europe Standard Time" territory="SJ" type="Arctic/Longyearbyen"/> <mapZone other="W. Europe Standard Time" territory="SM" type="Europe/San_Marino"/> <mapZone other="W. Europe Standard Time" territory="VA" type="Europe/Vatican"/> <!-- (UTC+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague --> <mapZone other="Central Europe Standard Time" territory="001" type="Europe/Budapest"/> <mapZone other="Central Europe Standard Time" territory="AL" type="Europe/Tirane"/> <mapZone other="Central Europe Standard Time" territory="CZ" type="Europe/Prague"/> <mapZone other="Central Europe Standard Time" territory="HU" type="Europe/Budapest"/> <mapZone other="Central Europe Standard Time" territory="ME" type="Europe/Podgorica"/> <mapZone other="Central Europe Standard Time" territory="RS" type="Europe/Belgrade"/> <mapZone other="Central Europe Standard Time" territory="SI" type="Europe/Ljubljana"/> <mapZone other="Central Europe Standard Time" territory="SK" type="Europe/Bratislava"/> <!-- (UTC+01:00) Brussels, Copenhagen, Madrid, Paris --> <mapZone other="Romance Standard Time" territory="001" type="Europe/Paris"/> <mapZone other="Romance Standard Time" territory="BE" type="Europe/Brussels"/> <mapZone other="Romance Standard Time" territory="DK" type="Europe/Copenhagen"/> <mapZone other="Romance Standard Time" territory="ES" type="Europe/Madrid Africa/Ceuta"/> <mapZone other="Romance Standard Time" territory="FR" type="Europe/Paris"/> <!-- (UTC+01:00) Sarajevo, Skopje, Warsaw, Zagreb --> <mapZone other="Central European Standard Time" territory="001" type="Europe/Warsaw"/> <mapZone other="Central European Standard Time" territory="BA" type="Europe/Sarajevo"/> <mapZone other="Central European Standard Time" territory="HR" type="Europe/Zagreb"/> <mapZone other="Central European Standard Time" territory="MK" type="Europe/Skopje"/> <mapZone other="Central European Standard Time" territory="PL" type="Europe/Warsaw"/> <!-- (UTC+01:00) West Central Africa --> <mapZone other="W. Central Africa Standard Time" territory="001" type="Africa/Lagos"/> <mapZone other="W. Central Africa Standard Time" territory="AO" type="Africa/Luanda"/> <mapZone other="W. Central Africa Standard Time" territory="BJ" type="Africa/Porto-Novo"/> <mapZone other="W. Central Africa Standard Time" territory="CD" type="Africa/Kinshasa"/> <mapZone other="W. Central Africa Standard Time" territory="CF" type="Africa/Bangui"/> <mapZone other="W. Central Africa Standard Time" territory="CG" type="Africa/Brazzaville"/> <mapZone other="W. Central Africa Standard Time" territory="CM" type="Africa/Douala"/> <mapZone other="W. Central Africa Standard Time" territory="DZ" type="Africa/Algiers"/> <mapZone other="W. Central Africa Standard Time" territory="GA" type="Africa/Libreville"/> <mapZone other="W. Central Africa Standard Time" territory="GQ" type="Africa/Malabo"/> <mapZone other="W. Central Africa Standard Time" territory="NE" type="Africa/Niamey"/> <mapZone other="W. Central Africa Standard Time" territory="NG" type="Africa/Lagos"/> <mapZone other="W. Central Africa Standard Time" territory="TD" type="Africa/Ndjamena"/> <mapZone other="W. Central Africa Standard Time" territory="TN" type="Africa/Tunis"/> <mapZone other="W. Central Africa Standard Time" territory="ZZ" type="Etc/GMT-1"/> <!-- (UTC+02:00) Amman --> <mapZone other="Jordan Standard Time" territory="001" type="Asia/Amman"/> <mapZone other="Jordan Standard Time" territory="JO" type="Asia/Amman"/> <!-- (UTC+02:00) Athens, Bucharest --> <mapZone other="GTB Standard Time" territory="001" type="Europe/Bucharest"/> <mapZone other="GTB Standard Time" territory="CY" type="Asia/Nicosia Asia/Famagusta"/> <mapZone other="GTB Standard Time" territory="GR" type="Europe/Athens"/> <mapZone other="GTB Standard Time" territory="RO" type="Europe/Bucharest"/> <!-- (UTC+02:00) Beirut --> <mapZone other="Middle East Standard Time" territory="001" type="Asia/Beirut"/> <mapZone other="Middle East Standard Time" territory="LB" type="Asia/Beirut"/> <!-- (UTC+02:00) Cairo --> <mapZone other="Egypt Standard Time" territory="001" type="Africa/Cairo"/> <mapZone other="Egypt Standard Time" territory="EG" type="Africa/Cairo"/> <!-- (UTC+02:00) Chisinau --> <mapZone other="E. Europe Standard Time" territory="001" type="Europe/Chisinau"/> <mapZone other="E. Europe Standard Time" territory="MD" type="Europe/Chisinau"/> <!-- (UTC+02:00) Damascus --> <mapZone other="Syria Standard Time" territory="001" type="Asia/Damascus"/> <mapZone other="Syria Standard Time" territory="SY" type="Asia/Damascus"/> <!-- (UTC+02:00) Gaza, Hebron --> <mapZone other="West Bank Standard Time" territory="001" type="Asia/Hebron"/> <mapZone other="West Bank Standard Time" territory="PS" type="Asia/Hebron Asia/Gaza"/> <!-- (UTC+02:00) Harare, Pretoria --> <mapZone other="South Africa Standard Time" territory="001" type="Africa/Johannesburg"/> <mapZone other="South Africa Standard Time" territory="BI" type="Africa/Bujumbura"/> <mapZone other="South Africa Standard Time" territory="BW" type="Africa/Gaborone"/> <mapZone other="South Africa Standard Time" territory="CD" type="Africa/Lubumbashi"/> <mapZone other="South Africa Standard Time" territory="LS" type="Africa/Maseru"/> <mapZone other="South Africa Standard Time" territory="MW" type="Africa/Blantyre"/> <mapZone other="South Africa Standard Time" territory="MZ" type="Africa/Maputo"/> <mapZone other="South Africa Standard Time" territory="RW" type="Africa/Kigali"/> <mapZone other="South Africa Standard Time" territory="SZ" type="Africa/Mbabane"/> <mapZone other="South Africa Standard Time" territory="ZA" type="Africa/Johannesburg"/> <mapZone other="South Africa Standard Time" territory="ZM" type="Africa/Lusaka"/> <mapZone other="South Africa Standard Time" territory="ZW" type="Africa/Harare"/> <mapZone other="South Africa Standard Time" territory="ZZ" type="Etc/GMT-2"/> <!-- (UTC+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius --> <mapZone other="FLE Standard Time" territory="001" type="Europe/Kiev"/> <mapZone other="FLE Standard Time" territory="AX" type="Europe/Mariehamn"/> <mapZone other="FLE Standard Time" territory="BG" type="Europe/Sofia"/> <mapZone other="FLE Standard Time" territory="EE" type="Europe/Tallinn"/> <mapZone other="FLE Standard Time" territory="FI" type="Europe/Helsinki"/> <mapZone other="FLE Standard Time" territory="LT" type="Europe/Vilnius"/> <mapZone other="FLE Standard Time" territory="LV" type="Europe/Riga"/> <mapZone other="FLE Standard Time" territory="UA" type="Europe/Kiev"/> <!-- (UTC+02:00) Jerusalem --> <mapZone other="Israel Standard Time" territory="001" type="Asia/Jerusalem"/> <mapZone other="Israel Standard Time" territory="IL" type="Asia/Jerusalem"/> <!-- (UTC+02:00) Juba --> <mapZone other="South Sudan Standard Time" territory="001" type="Africa/Juba"/> <mapZone other="South Sudan Standard Time" territory="SS" type="Africa/Juba"/> <!-- (UTC+02:00) Kaliningrad --> <mapZone other="Kaliningrad Standard Time" territory="001" type="Europe/Kaliningrad"/> <mapZone other="Kaliningrad Standard Time" territory="RU" type="Europe/Kaliningrad"/> <!-- (UTC+02:00) Khartoum --> <mapZone other="Sudan Standard Time" territory="001" type="Africa/Khartoum"/> <mapZone other="Sudan Standard Time" territory="SD" type="Africa/Khartoum"/> <!-- (UTC+02:00) Tripoli --> <mapZone other="Libya Standard Time" territory="001" type="Africa/Tripoli"/> <mapZone other="Libya Standard Time" territory="LY" type="Africa/Tripoli"/> <!-- (UTC+02:00) Windhoek --> <mapZone other="Namibia Standard Time" territory="001" type="Africa/Windhoek"/> <mapZone other="Namibia Standard Time" territory="NA" type="Africa/Windhoek"/> <!-- (UTC+03:00) Baghdad --> <mapZone other="Arabic Standard Time" territory="001" type="Asia/Baghdad"/> <mapZone other="Arabic Standard Time" territory="IQ" type="Asia/Baghdad"/> <!-- (UTC+03:00) Istanbul --> <mapZone other="Turkey Standard Time" territory="001" type="Europe/Istanbul"/> <mapZone other="Turkey Standard Time" territory="TR" type="Europe/Istanbul"/> <!-- (UTC+03:00) Kuwait, Riyadh --> <mapZone other="Arab Standard Time" territory="001" type="Asia/Riyadh"/> <mapZone other="Arab Standard Time" territory="BH" type="Asia/Bahrain"/> <mapZone other="Arab Standard Time" territory="KW" type="Asia/Kuwait"/> <mapZone other="Arab Standard Time" territory="QA" type="Asia/Qatar"/> <mapZone other="Arab Standard Time" territory="SA" type="Asia/Riyadh"/> <mapZone other="Arab Standard Time" territory="YE" type="Asia/Aden"/> <!-- (UTC+03:00) Minsk --> <mapZone other="Belarus Standard Time" territory="001" type="Europe/Minsk"/> <mapZone other="Belarus Standard Time" territory="BY" type="Europe/Minsk"/> <!-- (UTC+03:00) Moscow, St. Petersburg --> <mapZone other="Russian Standard Time" territory="001" type="Europe/Moscow"/> <mapZone other="Russian Standard Time" territory="RU" type="Europe/Moscow Europe/Kirov"/> <mapZone other="Russian Standard Time" territory="UA" type="Europe/Simferopol"/> <!-- (UTC+03:00) Nairobi --> <mapZone other="E. Africa Standard Time" territory="001" type="Africa/Nairobi"/> <mapZone other="E. Africa Standard Time" territory="AQ" type="Antarctica/Syowa"/> <mapZone other="E. Africa Standard Time" territory="DJ" type="Africa/Djibouti"/> <mapZone other="E. Africa Standard Time" territory="ER" type="Africa/Asmera"/> <mapZone other="E. Africa Standard Time" territory="ET" type="Africa/Addis_Ababa"/> <mapZone other="E. Africa Standard Time" territory="KE" type="Africa/Nairobi"/> <mapZone other="E. Africa Standard Time" territory="KM" type="Indian/Comoro"/> <mapZone other="E. Africa Standard Time" territory="MG" type="Indian/Antananarivo"/> <mapZone other="E. Africa Standard Time" territory="SO" type="Africa/Mogadishu"/> <mapZone other="E. Africa Standard Time" territory="TZ" type="Africa/Dar_es_Salaam"/> <mapZone other="E. Africa Standard Time" territory="UG" type="Africa/Kampala"/> <mapZone other="E. Africa Standard Time" territory="YT" type="Indian/Mayotte"/> <mapZone other="E. Africa Standard Time" territory="ZZ" type="Etc/GMT-3"/> <!-- (UTC+03:30) Tehran --> <mapZone other="Iran Standard Time" territory="001" type="Asia/Tehran"/> <mapZone other="Iran Standard Time" territory="IR" type="Asia/Tehran"/> <!-- (UTC+04:00) Abu Dhabi, Muscat --> <mapZone other="Arabian Standard Time" territory="001" type="Asia/Dubai"/> <mapZone other="Arabian Standard Time" territory="AE" type="Asia/Dubai"/> <mapZone other="Arabian Standard Time" territory="OM" type="Asia/Muscat"/> <mapZone other="Arabian Standard Time" territory="ZZ" type="Etc/GMT-4"/> <!-- (UTC+04:00) Astrakhan, Ulyanovsk --> <mapZone other="Astrakhan Standard Time" territory="001" type="Europe/Astrakhan"/> <mapZone other="Astrakhan Standard Time" territory="RU" type="Europe/Astrakhan Europe/Ulyanovsk"/> <!-- (UTC+04:00) Baku --> <mapZone other="Azerbaijan Standard Time" territory="001" type="Asia/Baku"/> <mapZone other="Azerbaijan Standard Time" territory="AZ" type="Asia/Baku"/> <!-- (UTC+04:00) Izhevsk, Samara --> <mapZone other="Russia Time Zone 3" territory="001" type="Europe/Samara"/> <mapZone other="Russia Time Zone 3" territory="RU" type="Europe/Samara"/> <!-- (UTC+04:00) Port Louis --> <mapZone other="Mauritius Standard Time" territory="001" type="Indian/Mauritius"/> <mapZone other="Mauritius Standard Time" territory="MU" type="Indian/Mauritius"/> <mapZone other="Mauritius Standard Time" territory="RE" type="Indian/Reunion"/> <mapZone other="Mauritius Standard Time" territory="SC" type="Indian/Mahe"/> <!-- (UTC+04:00) Saratov --> <mapZone other="Saratov Standard Time" territory="001" type="Europe/Saratov"/> <mapZone other="Saratov Standard Time" territory="RU" type="Europe/Saratov"/> <!-- (UTC+04:00) Tbilisi --> <mapZone other="Georgian Standard Time" territory="001" type="Asia/Tbilisi"/> <mapZone other="Georgian Standard Time" territory="GE" type="Asia/Tbilisi"/> <!-- (UTC+04:00) Volgograd --> <mapZone other="Volgograd Standard Time" territory="001" type="Europe/Volgograd"/> <mapZone other="Volgograd Standard Time" territory="RU" type="Europe/Volgograd"/> <!-- (UTC+04:00) Yerevan --> <mapZone other="Caucasus Standard Time" territory="001" type="Asia/Yerevan"/> <mapZone other="Caucasus Standard Time" territory="AM" type="Asia/Yerevan"/> <!-- (UTC+04:30) Kabul --> <mapZone other="Afghanistan Standard Time" territory="001" type="Asia/Kabul"/> <mapZone other="Afghanistan Standard Time" territory="AF" type="Asia/Kabul"/> <!-- (UTC+05:00) Ashgabat, Tashkent --> <mapZone other="West Asia Standard Time" territory="001" type="Asia/Tashkent"/> <mapZone other="West Asia Standard Time" territory="AQ" type="Antarctica/Mawson"/> <!-- Microsoft may create a new zone dedicated for Almaty and Qostanay. --> <mapZone other="West Asia Standard Time" territory="KZ" type="Asia/Oral Asia/Almaty Asia/Aqtau Asia/Aqtobe Asia/Atyrau Asia/Qostanay"/> <mapZone other="West Asia Standard Time" territory="MV" type="Indian/Maldives"/> <mapZone other="West Asia Standard Time" territory="TF" type="Indian/Kerguelen"/> <mapZone other="West Asia Standard Time" territory="TJ" type="Asia/Dushanbe"/> <mapZone other="West Asia Standard Time" territory="TM" type="Asia/Ashgabat"/> <mapZone other="West Asia Standard Time" territory="UZ" type="Asia/Tashkent Asia/Samarkand"/> <mapZone other="West Asia Standard Time" territory="ZZ" type="Etc/GMT-5"/> <!-- (UTC+05:00) Ekaterinburg --> <mapZone other="Ekaterinburg Standard Time" territory="001" type="Asia/Yekaterinburg"/> <mapZone other="Ekaterinburg Standard Time" territory="RU" type="Asia/Yekaterinburg"/> <!-- (UTC+05:00) Islamabad, Karachi --> <mapZone other="Pakistan Standard Time" territory="001" type="Asia/Karachi"/> <mapZone other="Pakistan Standard Time" territory="PK" type="Asia/Karachi"/> <!-- (UTC+05:00) Qyzylorda --> <mapZone other="Qyzylorda Standard Time" territory="001" type="Asia/Qyzylorda"/> <mapZone other="Qyzylorda Standard Time" territory="KZ" type="Asia/Qyzylorda"/> <!-- (UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi --> <mapZone other="India Standard Time" territory="001" type="Asia/Calcutta"/> <mapZone other="India Standard Time" territory="IN" type="Asia/Calcutta"/> <!-- (UTC+05:30) Sri Jayawardenepura --> <mapZone other="Sri Lanka Standard Time" territory="001" type="Asia/Colombo"/> <mapZone other="Sri Lanka Standard Time" territory="LK" type="Asia/Colombo"/> <!-- (UTC+05:45) Kathmandu --> <mapZone other="Nepal Standard Time" territory="001" type="Asia/Katmandu"/> <mapZone other="Nepal Standard Time" territory="NP" type="Asia/Katmandu"/> <!-- (UTC+06:00) Astana --> <!-- Microsoft probably keeps Central Asia Standard Time, but change Astana to something else. --> <mapZone other="Central Asia Standard Time" territory="001" type="Asia/Bishkek"/> <mapZone other="Central Asia Standard Time" territory="AQ" type="Antarctica/Vostok"/> <mapZone other="Central Asia Standard Time" territory="CN" type="Asia/Urumqi"/> <mapZone other="Central Asia Standard Time" territory="IO" type="Indian/Chagos"/> <mapZone other="Central Asia Standard Time" territory="KG" type="Asia/Bishkek"/> <mapZone other="Central Asia Standard Time" territory="ZZ" type="Etc/GMT-6"/> <!-- (UTC+06:00) Dhaka --> <mapZone other="Bangladesh Standard Time" territory="001" type="Asia/Dhaka"/> <mapZone other="Bangladesh Standard Time" territory="BD" type="Asia/Dhaka"/> <mapZone other="Bangladesh Standard Time" territory="BT" type="Asia/Thimphu"/> <!-- (UTC+06:00) Omsk --> <mapZone other="Omsk Standard Time" territory="001" type="Asia/Omsk"/> <mapZone other="Omsk Standard Time" territory="RU" type="Asia/Omsk"/> <!-- (UTC+06:30) Yangon (Rangoon) --> <mapZone other="Myanmar Standard Time" territory="001" type="Asia/Rangoon"/> <mapZone other="Myanmar Standard Time" territory="CC" type="Indian/Cocos"/> <mapZone other="Myanmar Standard Time" territory="MM" type="Asia/Rangoon"/> <!-- (UTC+07:00) Bangkok, Hanoi, Jakarta --> <mapZone other="SE Asia Standard Time" territory="001" type="Asia/Bangkok"/> <mapZone other="SE Asia Standard Time" territory="AQ" type="Antarctica/Davis"/> <mapZone other="SE Asia Standard Time" territory="CX" type="Indian/Christmas"/> <mapZone other="SE Asia Standard Time" territory="ID" type="Asia/Jakarta Asia/Pontianak"/> <mapZone other="SE Asia Standard Time" territory="KH" type="Asia/Phnom_Penh"/> <mapZone other="SE Asia Standard Time" territory="LA" type="Asia/Vientiane"/> <mapZone other="SE Asia Standard Time" territory="TH" type="Asia/Bangkok"/> <mapZone other="SE Asia Standard Time" territory="VN" type="Asia/Saigon"/> <mapZone other="SE Asia Standard Time" territory="ZZ" type="Etc/GMT-7"/> <!-- (UTC+07:00) Barnaul, Gorno-Altaysk --> <mapZone other="Altai Standard Time" territory="001" type="Asia/Barnaul"/> <mapZone other="Altai Standard Time" territory="RU" type="Asia/Barnaul"/> <!-- (UTC+07:00) Hovd --> <mapZone other="W. Mongolia Standard Time" territory="001" type="Asia/Hovd"/> <mapZone other="W. Mongolia Standard Time" territory="MN" type="Asia/Hovd"/> <!-- (UTC+07:00) Krasnoyarsk --> <mapZone other="North Asia Standard Time" territory="001" type="Asia/Krasnoyarsk"/> <mapZone other="North Asia Standard Time" territory="RU" type="Asia/Krasnoyarsk Asia/Novokuznetsk"/> <!-- (UTC+07:00) Novosibirsk --> <mapZone other="N. Central Asia Standard Time" territory="001" type="Asia/Novosibirsk"/> <mapZone other="N. Central Asia Standard Time" territory="RU" type="Asia/Novosibirsk"/> <!-- (UTC+07:00) Tomsk --> <mapZone other="Tomsk Standard Time" territory="001" type="Asia/Tomsk"/> <mapZone other="Tomsk Standard Time" territory="RU" type="Asia/Tomsk"/> <!-- (UTC+08:00) Beijing, Chongqing, Hong Kong, Urumqi --> <mapZone other="China Standard Time" territory="001" type="Asia/Shanghai"/> <mapZone other="China Standard Time" territory="CN" type="Asia/Shanghai"/> <mapZone other="China Standard Time" territory="HK" type="Asia/Hong_Kong"/> <mapZone other="China Standard Time" territory="MO" type="Asia/Macau"/> <!-- (UTC+08:00) Irkutsk --> <mapZone other="North Asia East Standard Time" territory="001" type="Asia/Irkutsk"/> <mapZone other="North Asia East Standard Time" territory="RU" type="Asia/Irkutsk"/> <!-- (UTC+08:00) Kuala Lumpur, Singapore --> <mapZone other="Singapore Standard Time" territory="001" type="Asia/Singapore"/> <mapZone other="Singapore Standard Time" territory="BN" type="Asia/Brunei"/> <mapZone other="Singapore Standard Time" territory="ID" type="Asia/Makassar"/> <mapZone other="Singapore Standard Time" territory="MY" type="Asia/Kuala_Lumpur Asia/Kuching"/> <mapZone other="Singapore Standard Time" territory="PH" type="Asia/Manila"/> <mapZone other="Singapore Standard Time" territory="SG" type="Asia/Singapore"/> <mapZone other="Singapore Standard Time" territory="ZZ" type="Etc/GMT-8"/> <!-- (UTC+08:00) Perth --> <mapZone other="W. Australia Standard Time" territory="001" type="Australia/Perth"/> <mapZone other="W. Australia Standard Time" territory="AU" type="Australia/Perth"/> <!-- (UTC+08:00) Taipei --> <mapZone other="Taipei Standard Time" territory="001" type="Asia/Taipei"/> <mapZone other="Taipei Standard Time" territory="TW" type="Asia/Taipei"/> <!-- (UTC+08:00) Ulaanbaatar --> <mapZone other="Ulaanbaatar Standard Time" territory="001" type="Asia/Ulaanbaatar"/> <mapZone other="Ulaanbaatar Standard Time" territory="MN" type="Asia/Ulaanbaatar Asia/Choibalsan"/> <!-- (UTC+08:45) Eucla --> <mapZone other="Aus Central W. Standard Time" territory="001" type="Australia/Eucla"/> <mapZone other="Aus Central W. Standard Time" territory="AU" type="Australia/Eucla"/> <!-- (UTC+09:00) Chita --> <mapZone other="Transbaikal Standard Time" territory="001" type="Asia/Chita"/> <mapZone other="Transbaikal Standard Time" territory="RU" type="Asia/Chita"/> <!-- (UTC+09:00) Osaka, Sapporo, Tokyo --> <mapZone other="Tokyo Standard Time" territory="001" type="Asia/Tokyo"/> <mapZone other="Tokyo Standard Time" territory="ID" type="Asia/Jayapura"/> <mapZone other="Tokyo Standard Time" territory="JP" type="Asia/Tokyo"/> <mapZone other="Tokyo Standard Time" territory="PW" type="Pacific/Palau"/> <mapZone other="Tokyo Standard Time" territory="TL" type="Asia/Dili"/> <mapZone other="Tokyo Standard Time" territory="ZZ" type="Etc/GMT-9"/> <!-- (UTC+09:00) Pyongyang --> <mapZone other="North Korea Standard Time" territory="001" type="Asia/Pyongyang"/> <mapZone other="North Korea Standard Time" territory="KP" type="Asia/Pyongyang"/> <!-- (UTC+09:00) Seoul --> <mapZone other="Korea Standard Time" territory="001" type="Asia/Seoul"/> <mapZone other="Korea Standard Time" territory="KR" type="Asia/Seoul"/> <!-- (UTC+09:00) Yakutsk --> <mapZone other="Yakutsk Standard Time" territory="001" type="Asia/Yakutsk"/> <mapZone other="Yakutsk Standard Time" territory="RU" type="Asia/Yakutsk Asia/Khandyga"/> <!-- (UTC+09:30) Adelaide --> <mapZone other="Cen. Australia Standard Time" territory="001" type="Australia/Adelaide"/> <mapZone other="Cen. Australia Standard Time" territory="AU" type="Australia/Adelaide Australia/Broken_Hill"/> <!-- (UTC+09:30) Darwin --> <mapZone other="AUS Central Standard Time" territory="001" type="Australia/Darwin"/> <mapZone other="AUS Central Standard Time" territory="AU" type="Australia/Darwin"/> <!-- (UTC+10:00) Brisbane --> <mapZone other="E. Australia Standard Time" territory="001" type="Australia/Brisbane"/> <mapZone other="E. Australia Standard Time" territory="AU" type="Australia/Brisbane Australia/Lindeman"/> <!-- (UTC+10:00) Canberra, Melbourne, Sydney --> <mapZone other="AUS Eastern Standard Time" territory="001" type="Australia/Sydney"/> <mapZone other="AUS Eastern Standard Time" territory="AU" type="Australia/Sydney Australia/Melbourne"/> <!-- (UTC+10:00) Guam, Port Moresby --> <mapZone other="West Pacific Standard Time" territory="001" type="Pacific/Port_Moresby"/> <mapZone other="West Pacific Standard Time" territory="AQ" type="Antarctica/DumontDUrville"/> <mapZone other="West Pacific Standard Time" territory="FM" type="Pacific/Truk"/> <mapZone other="West Pacific Standard Time" territory="GU" type="Pacific/Guam"/> <mapZone other="West Pacific Standard Time" territory="MP" type="Pacific/Saipan"/> <mapZone other="West Pacific Standard Time" territory="PG" type="Pacific/Port_Moresby"/> <mapZone other="West Pacific Standard Time" territory="ZZ" type="Etc/GMT-10"/> <!-- (UTC+10:00) Hobart --> <mapZone other="Tasmania Standard Time" territory="001" type="Australia/Hobart"/> <mapZone other="Tasmania Standard Time" territory="AU" type="Australia/Hobart Antarctica/Macquarie"/> <!-- (UTC+10:00) Vladivostok --> <mapZone other="Vladivostok Standard Time" territory="001" type="Asia/Vladivostok"/> <mapZone other="Vladivostok Standard Time" territory="RU" type="Asia/Vladivostok Asia/Ust-Nera"/> <!-- (UTC+10:30) Lord Howe Island --> <mapZone other="Lord Howe Standard Time" territory="001" type="Australia/Lord_Howe"/> <mapZone other="Lord Howe Standard Time" territory="AU" type="Australia/Lord_Howe"/> <!-- (UTC+11:00) Bougainville Island --> <mapZone other="Bougainville Standard Time" territory="001" type="Pacific/Bougainville"/> <mapZone other="Bougainville Standard Time" territory="PG" type="Pacific/Bougainville"/> <!-- (UTC+11:00) Chokurdakh --> <mapZone other="Russia Time Zone 10" territory="001" type="Asia/Srednekolymsk"/> <mapZone other="Russia Time Zone 10" territory="RU" type="Asia/Srednekolymsk"/> <!-- (UTC+11:00) Magadan --> <mapZone other="Magadan Standard Time" territory="001" type="Asia/Magadan"/> <mapZone other="Magadan Standard Time" territory="RU" type="Asia/Magadan"/> <!-- (UTC+11:00) Norfolk Island --> <mapZone other="Norfolk Standard Time" territory="001" type="Pacific/Norfolk"/> <mapZone other="Norfolk Standard Time" territory="NF" type="Pacific/Norfolk"/> <!-- (UTC+11:00) Sakhalin --> <mapZone other="Sakhalin Standard Time" territory="001" type="Asia/Sakhalin"/> <mapZone other="Sakhalin Standard Time" territory="RU" type="Asia/Sakhalin"/> <!-- (UTC+11:00) Solomon Is., New Caledonia --> <mapZone other="Central Pacific Standard Time" territory="001" type="Pacific/Guadalcanal"/> <mapZone other="Central Pacific Standard Time" territory="AQ" type="Antarctica/Casey"/> <mapZone other="Central Pacific Standard Time" territory="FM" type="Pacific/Ponape Pacific/Kosrae"/> <mapZone other="Central Pacific Standard Time" territory="NC" type="Pacific/Noumea"/> <mapZone other="Central Pacific Standard Time" territory="SB" type="Pacific/Guadalcanal"/> <mapZone other="Central Pacific Standard Time" territory="VU" type="Pacific/Efate"/> <mapZone other="Central Pacific Standard Time" territory="ZZ" type="Etc/GMT-11"/> <!-- (UTC+12:00) Anadyr, Petropavlovsk-Kamchatsky --> <mapZone other="Russia Time Zone 11" territory="001" type="Asia/Kamchatka"/> <mapZone other="Russia Time Zone 11" territory="RU" type="Asia/Kamchatka Asia/Anadyr"/> <!-- (UTC+12:00) Auckland, Wellington --> <mapZone other="New Zealand Standard Time" territory="001" type="Pacific/Auckland"/> <mapZone other="New Zealand Standard Time" territory="AQ" type="Antarctica/McMurdo"/> <mapZone other="New Zealand Standard Time" territory="NZ" type="Pacific/Auckland"/> <!-- (UTC+12:00) Coordinated Universal Time+12 --> <mapZone other="UTC+12" territory="001" type="Etc/GMT-12"/> <mapZone other="UTC+12" territory="KI" type="Pacific/Tarawa"/> <mapZone other="UTC+12" territory="MH" type="Pacific/Majuro Pacific/Kwajalein"/> <mapZone other="UTC+12" territory="NR" type="Pacific/Nauru"/> <mapZone other="UTC+12" territory="TV" type="Pacific/Funafuti"/> <mapZone other="UTC+12" territory="UM" type="Pacific/Wake"/> <mapZone other="UTC+12" territory="WF" type="Pacific/Wallis"/> <mapZone other="UTC+12" territory="ZZ" type="Etc/GMT-12"/> <!-- (UTC+12:00) Fiji --> <mapZone other="Fiji Standard Time" territory="001" type="Pacific/Fiji"/> <mapZone other="Fiji Standard Time" territory="FJ" type="Pacific/Fiji"/> <!-- (UTC+12:45) Chatham Islands --> <mapZone other="Chatham Islands Standard Time" territory="001" type="Pacific/Chatham"/> <mapZone other="Chatham Islands Standard Time" territory="NZ" type="Pacific/Chatham"/> <!-- (UTC+13:00) Coordinated Universal Time+13 --> <mapZone other="UTC+13" territory="001" type="Etc/GMT-13"/> <mapZone other="UTC+13" territory="KI" type="Pacific/Enderbury"/> <mapZone other="UTC+13" territory="TK" type="Pacific/Fakaofo"/> <mapZone other="UTC+13" territory="ZZ" type="Etc/GMT-13"/> <!-- (UTC+13:00) Nuku'alofa --> <mapZone other="Tonga Standard Time" territory="001" type="Pacific/Tongatapu"/> <mapZone other="Tonga Standard Time" territory="TO" type="Pacific/Tongatapu"/> <!-- (UTC+13:00) Samoa --> <mapZone other="Samoa Standard Time" territory="001" type="Pacific/Apia"/> <mapZone other="Samoa Standard Time" territory="WS" type="Pacific/Apia"/> <!-- (UTC+14:00) Kiritimati Island --> <mapZone other="Line Islands Standard Time" territory="001" type="Pacific/Kiritimati"/> <mapZone other="Line Islands Standard Time" territory="KI" type="Pacific/Kiritimati"/> <mapZone other="Line Islands Standard Time" territory="ZZ" type="Etc/GMT-14"/> </mapTimezones> </windowsZones> </supplementalData>
0
repos/zeit
repos/zeit/src/zeit.zig
const std = @import("std"); const builtin = @import("builtin"); const location = @import("location.zig"); pub const timezone = @import("timezone.zig"); const assert = std.debug.assert; pub const TimeZone = timezone.TimeZone; pub const Location = location.Location; const ns_per_us = std.time.ns_per_us; const ns_per_ms = std.time.ns_per_ms; const ns_per_s = std.time.ns_per_s; const ns_per_min = std.time.ns_per_min; const ns_per_hour = std.time.ns_per_hour; const ns_per_day = std.time.ns_per_day; const s_per_min = std.time.s_per_min; const s_per_hour = std.time.s_per_hour; const s_per_day = std.time.s_per_day; const days_per_era = 365 * 400 + 97; pub const utc: TimeZone = .{ .fixed = .{ .name = "UTC", .offset = 0, .is_dst = false, } }; pub fn local(alloc: std.mem.Allocator, maybe_env: ?*const std.process.EnvMap) !TimeZone { switch (builtin.os.tag) { .windows => { const win = try timezone.Windows.local(alloc); return .{ .windows = win }; }, else => { if (maybe_env) |env| { if (env.get("TZ")) |tz| { return localFromEnv(alloc, tz, env); } } const f = try std.fs.cwd().openFile("/etc/localtime", .{}); return .{ .tzinfo = try timezone.TZInfo.parse(alloc, f.reader()) }; }, } } // Returns the local time zone from the given TZ environment variable // TZ can be one of three things: // 1. A POSIX TZ string (TZ=CST6CDT,M3.2.0,M11.1.0) // 2. An absolute path, prefixed with ':' (TZ=:/etc/localtime) // 3. A relative path, prefixed with ':' fn localFromEnv( alloc: std.mem.Allocator, tz: []const u8, env: *const std.process.EnvMap, ) !TimeZone { assert(tz.len != 0); // TZ is empty string // Return early we we are a posix TZ string if (tz[0] != ':') return .{ .posix = try timezone.Posix.parse(tz) }; assert(tz.len > 1); // TZ not long enough if (tz[1] == '/') { const f = try std.fs.cwd().openFile(tz[1..], .{}); return .{ .tzinfo = try timezone.TZInfo.parse(alloc, f.reader()) }; } if (std.meta.stringToEnum(Location, tz[1..])) |loc| return loadTimeZone(alloc, loc, env) else return error.UnknownLocation; } pub fn loadTimeZone( alloc: std.mem.Allocator, loc: Location, maybe_env: ?*const std.process.EnvMap, ) !TimeZone { switch (builtin.os.tag) { .windows => { const tz = try timezone.Windows.loadFromName(alloc, loc); return .{ .windows = tz }; }, else => {}, } var dir: std.fs.Dir = blk: { // If we have an env and a TZDIR, use that if (maybe_env) |env| { if (env.get("TZDIR")) |tzdir| { const dir = try std.fs.openDirAbsolute(tzdir, .{}); break :blk dir; } } // Otherwise check well-known locations const zone_dirs = [_][]const u8{ "/usr/share/zoneinfo/", "/usr/share/lib/zoneinfo/", "/usr/lib/locale/TZ/", "/share/zoneinfo/", "/etc/zoneinfo/", }; for (zone_dirs) |zone_dir| { const dir = std.fs.openDirAbsolute(zone_dir, .{}) catch continue; break :blk dir; } else return error.FileNotFound; }; defer dir.close(); const f = try dir.openFile(loc.asText(), .{}); return .{ .tzinfo = try timezone.TZInfo.parse(alloc, f.reader()) }; } /// An Instant in time. Instants occur at a precise time and place, thus must /// always carry with them a timezone. pub const Instant = struct { /// the instant of time, in nanoseconds timestamp: i128, /// every instant occurs in a timezone. This is the timezone timezone: *const TimeZone, pub const Config = struct { source: Source = .now, timezone: *const TimeZone = &utc, }; /// possible sources to create an Instant pub const Source = union(enum) { /// the current system time now, /// a specific unix timestamp (in seconds) unix_timestamp: i64, /// a specific unix timestamp (in nanoseconds) unix_nano: i128, /// create an Instant from a calendar date and time time: Time, /// parse a datetime from an ISO8601 string /// Supports most ISO8601 formats, _except_: /// - Week numbers (ie YYYY-Www) /// - Fractional minutes (ie YYYY-MM-DDTHH:MM.mmm) /// /// Strings can be in the extended or compact format and use ' ' or "T" /// as the time delimiter /// Examples of paresable strings: /// YYYY-MM-DD /// YYYY-MM-DDTHH /// YYYY-MM-DDTHH:MM /// YYYY-MM-DDTHH:MM:SS /// YYYY-MM-DDTHH:MM:SS.sss /// YYYY-MM-DDTHH:MM:SS.ssssss /// YYYY-MM-DDTHH:MM:SSZ /// YYYY-MM-DDTHH:MM:SS+hh:mm /// YYYYMMDDTHHMMSSZ iso8601: []const u8, /// Parse a datetime from an RFC3339 string. RFC3339 is similar to /// ISO8601 but is more strict, and allows for arbitrary fractional /// seconds. Using this field will use the same parser `iso8601`, but is /// provided for clarity /// Format: YYYY-MM-DDTHH:MM:SS.sss+hh:mm rfc3339: []const u8, /// Parse a datetime from an RFC5322 date-time spec rfc5322: []const u8, /// Parse a datetime from an RFC2822 date-time spec. This is an alias for RFC5322 rfc2822: []const u8, }; /// convert this Instant to another timezone pub fn in(self: Instant, zone: *const TimeZone) Instant { return .{ .timestamp = self.timestamp, .timezone = zone, }; } // convert the nanosecond timestamp into a unix timestamp (in seconds) pub fn unixTimestamp(self: Instant) i64 { return @intCast(@divFloor(self.timestamp, ns_per_s)); } // generate a calendar date and time for this instant pub fn time(self: Instant) Time { const adjusted = self.timezone.adjust(self.unixTimestamp()); const days = daysSinceEpoch(adjusted.timestamp); const date = civilFromDays(days); var seconds = @mod(adjusted.timestamp, s_per_day); const hours = @divFloor(seconds, s_per_hour); seconds -= hours * s_per_hour; const minutes = @divFloor(seconds, s_per_min); seconds -= minutes * s_per_min; // get the nanoseconds from the original timestamp var nanos = @mod(self.timestamp, ns_per_s); const millis = @divFloor(nanos, ns_per_ms); nanos -= millis * ns_per_ms; const micros = @divFloor(nanos, ns_per_us); nanos -= micros * ns_per_us; return .{ .year = date.year, .month = date.month, .day = date.day, .hour = @intCast(hours), .minute = @intCast(minutes), .second = @intCast(seconds), .millisecond = @intCast(millis), .microsecond = @intCast(micros), .nanosecond = @intCast(nanos), .offset = @intCast(adjusted.timestamp - self.unixTimestamp()), }; } /// add the duration to the Instant pub fn add(self: Instant, duration: Duration) Instant { const ns = duration.days * ns_per_day + duration.hours * ns_per_hour + duration.minutes * ns_per_min + duration.seconds * ns_per_s + duration.milliseconds * ns_per_ms + duration.microseconds * ns_per_us + duration.nanoseconds; return .{ .timestamp = self.timestamp + ns, .timezone = self.timezone, }; } /// subtract the duration from the Instant pub fn subtract(self: Instant, duration: Duration) Instant { const ns = duration.days * ns_per_day + duration.hours * ns_per_hour + duration.minutes * ns_per_min + duration.seconds * ns_per_s + duration.milliseconds * ns_per_ms + duration.microseconds * ns_per_us + duration.nanoseconds; return .{ .timestamp = self.timestamp - ns, .timezone = self.timezone, }; } }; /// create a new Instant pub fn instant(cfg: Instant.Config) !Instant { const ts: i128 = switch (cfg.source) { .now => std.time.nanoTimestamp(), .unix_timestamp => |unix| unix * ns_per_s, .unix_nano => |nano| nano, .time => |time| time.instant().timestamp, .iso8601, .rfc3339, => |iso| blk: { const t = try Time.fromISO8601(iso); break :blk t.instant().timestamp; }, .rfc2822, .rfc5322, => |eml| blk: { const t = try Time.fromRFC5322(eml); break :blk t.instant().timestamp; }, }; return .{ .timestamp = ts, .timezone = cfg.timezone, }; } test "instant" { const original = Instant{ .timestamp = std.time.nanoTimestamp(), .timezone = &utc, }; const time = original.time(); const round_trip = time.instant(); try std.testing.expectEqual(original.timestamp, round_trip.timestamp); } pub const Month = enum(u4) { jan = 1, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec, /// returns the last day of the month /// Neri/Schneider algorithm pub fn lastDay(self: Month, year: i32) u5 { const m: u5 = @intFromEnum(self); if (m == 2) return if (isLeapYear(year)) 29 else 28; return 30 | (m ^ (m >> 3)); } /// returns the full name of the month, eg "January" pub fn name(self: Month) []const u8 { return switch (self) { .jan => "January", .feb => "February", .mar => "March", .apr => "April", .may => "May", .jun => "June", .jul => "July", .aug => "August", .sep => "September", .oct => "October", .nov => "November", .dec => "December", }; } /// returns the short name of the month, eg "Jan" pub fn shortName(self: Month) []const u8 { return self.name()[0..3]; } test "lastDayOfMonth" { try std.testing.expectEqual(29, Month.feb.lastDay(2000)); try std.testing.expectEqual(31, Month.jan.lastDay(2001)); try std.testing.expectEqual(28, Month.feb.lastDay(2001)); try std.testing.expectEqual(31, Month.mar.lastDay(2001)); try std.testing.expectEqual(30, Month.apr.lastDay(2001)); try std.testing.expectEqual(31, Month.may.lastDay(2001)); try std.testing.expectEqual(30, Month.jun.lastDay(2001)); try std.testing.expectEqual(31, Month.jul.lastDay(2001)); try std.testing.expectEqual(31, Month.aug.lastDay(2001)); try std.testing.expectEqual(30, Month.sep.lastDay(2001)); try std.testing.expectEqual(31, Month.oct.lastDay(2001)); try std.testing.expectEqual(30, Month.nov.lastDay(2001)); try std.testing.expectEqual(31, Month.dec.lastDay(2001)); } /// the number of days in a year before this month pub fn daysBefore(self: Month, year: i32) u9 { var m = @intFromEnum(self) - 1; var result: u9 = 0; while (m > 0) : (m -= 1) { const month: Month = @enumFromInt(m); result += month.lastDay(year); } return result; } test "daysBefore" { try std.testing.expectEqual(60, Month.mar.daysBefore(2000)); try std.testing.expectEqual(0, Month.jan.daysBefore(2001)); try std.testing.expectEqual(31, Month.feb.daysBefore(2001)); try std.testing.expectEqual(59, Month.mar.daysBefore(2001)); } }; pub const Duration = struct { days: usize = 0, hours: usize = 0, minutes: usize = 0, seconds: usize = 0, milliseconds: usize = 0, microseconds: usize = 0, nanoseconds: usize = 0, }; pub const Weekday = enum(u3) { sun = 0, mon, tue, wed, thu, fri, sat, /// number of days from self until other. Returns 0 when self == other pub fn daysUntil(self: Weekday, other: Weekday) u3 { const d = @intFromEnum(other) -% @intFromEnum(self); return if (d <= 6) @intCast(d) else @intCast(d +% 7); } /// returns the full name of the day, eg "Tuesday" pub fn name(self: Weekday) []const u8 { return switch (self) { .sun => "Sunday", .mon => "Monday", .tue => "Tuesday", .wed => "Wednesday", .thu => "Thursday", .fri => "Friday", .sat => "Saturday", }; } /// returns the short name of the day, eg "Tue" pub fn shortName(self: Weekday) []const u8 { return self.name()[0..3]; } test "daysUntil" { const wed: Weekday = .wed; try std.testing.expectEqual(0, wed.daysUntil(.wed)); try std.testing.expectEqual(6, wed.daysUntil(.tue)); } }; pub const Date = struct { year: i32, month: Month, day: u5, // 1-31 }; pub const TimeComparison = enum(u2) { after, before, equal, }; pub const Time = struct { year: i32 = 1970, month: Month = .jan, day: u5 = 1, // 1-31 hour: u5 = 0, // 0-23 minute: u6 = 0, // 0-59 second: u6 = 0, // 0-60 millisecond: u10 = 0, // 0-999 microsecond: u10 = 0, // 0-999 nanosecond: u10 = 0, // 0-999 offset: i32 = 0, // offset from UTC in seconds /// Creates a UTC Instant for this time pub fn instant(self: Time) Instant { const days = daysFromCivil(.{ .year = self.year, .month = self.month, .day = self.day, }); return .{ .timestamp = @as(i128, days) * ns_per_day + @as(i128, self.hour) * ns_per_hour + @as(i128, self.minute) * ns_per_min + @as(i128, self.second) * ns_per_s + @as(i128, self.millisecond) * ns_per_ms + @as(i128, self.microsecond) * ns_per_us + @as(i128, self.nanosecond) - @as(i128, self.offset) * ns_per_s, .timezone = &utc, }; } pub fn fromISO8601(iso: []const u8) !Time { const parseInt = std.fmt.parseInt; var time: Time = .{}; const State = enum { year, month_or_ordinal, day, hour, minute, minute_fraction_or_second, second_fraction_or_offset, }; var state: State = .year; var i: usize = 0; while (i < iso.len) { switch (state) { .year => { if (iso.len <= 4) { // year only data const int = try parseInt(i32, iso, 10); time.year = int * std.math.pow(i32, 10, @as(i32, @intCast(4 - iso.len))); break; } else { time.year = try parseInt(i32, iso[0..4], 10); state = .month_or_ordinal; i += 4; if (iso[i] == '-') i += 1; } }, .month_or_ordinal => { const token_end = std.mem.indexOfAnyPos(u8, iso, i, "- T") orelse iso.len; switch (token_end - i) { 2 => { const m: u4 = try parseInt(u4, iso[i..token_end], 10); time.month = @enumFromInt(m); state = .day; }, 3 => { // ordinal const doy = try parseInt(u9, iso[i..token_end], 10); var m: u4 = 1; var days: u9 = 0; while (m <= 12) : (m += 1) { const month: Month = @enumFromInt(m); if (days + month.lastDay(time.year) < doy) { days += month.lastDay(time.year); continue; } time.month = month; time.day = @intCast(doy - days); break; } state = .hour; }, 4 => { // MMDD const m: u4 = try parseInt(u4, iso[i .. i + 2], 10); time.month = @enumFromInt(m); time.day = try parseInt(u4, iso[i + 2 .. token_end], 10); state = .hour; }, else => return error.InvalidISO8601, } i = token_end + 1; }, .day => { time.day = try parseInt(u5, iso[i .. i + 2], 10); // add 3 instead of 2 because we either have a trailing ' ', // 'T', or EOF i += 3; state = .hour; }, .hour => { time.hour = try parseInt(u5, iso[i .. i + 2], 10); i += 2; state = .minute; }, .minute => { if (iso[i] == ':') i += 1; time.minute = try parseInt(u6, iso[i .. i + 2], 10); i += 2; state = .minute_fraction_or_second; }, .minute_fraction_or_second => { const b = iso[i]; if (b == '.') return error.UnhandledFormat; // TODO: if (b == ':') i += 1; time.second = try parseInt(u6, iso[i .. i + 2], 10); i += 2; state = .second_fraction_or_offset; }, .second_fraction_or_offset => { switch (iso[i]) { 'Z' => break, '+', '-' => { const sign: i32 = if (iso[i] == '-') -1 else 1; i += 1; const hour = try parseInt(u5, iso[i .. i + 2], 10); i += 2; time.offset = sign * hour * s_per_hour; if (i >= iso.len - 1) break; if (iso[i] == ':') i += 1; const minute = try parseInt(u6, iso[i .. i + 2], 10); time.offset += sign * minute * s_per_min; i += 2; break; }, '.' => { i += 1; const frac_end = std.mem.indexOfAnyPos(u8, iso, i, "Z+-") orelse iso.len; const rhs = try parseInt(u64, iso[i..frac_end], 10); const sigs = frac_end - i; // convert sigs to nanoseconds const pow = std.math.pow(u64, 10, @as(u64, @intCast(9 - sigs))); var nanos = rhs * pow; time.millisecond = @intCast(@divFloor(nanos, ns_per_ms)); nanos -= @as(u64, time.millisecond) * ns_per_ms; time.microsecond = @intCast(@divFloor(nanos, ns_per_us)); nanos -= @as(u64, time.microsecond) * ns_per_us; time.nanosecond = @intCast(nanos); i = frac_end; }, else => return error.InvalidISO8601, } }, } } return time; } test "fromISO8601" { { const year = try Time.fromISO8601("2000"); try std.testing.expectEqual(2000, year.year); } { const ym = try Time.fromISO8601("200002"); try std.testing.expectEqual(2000, ym.year); try std.testing.expectEqual(.feb, ym.month); const ym_ext = try Time.fromISO8601("2000-02"); try std.testing.expectEqual(2000, ym_ext.year); try std.testing.expectEqual(.feb, ym_ext.month); } { const ymd = try Time.fromISO8601("20000212"); try std.testing.expectEqual(2000, ymd.year); try std.testing.expectEqual(.feb, ymd.month); try std.testing.expectEqual(12, ymd.day); const ymd_ext = try Time.fromISO8601("2000-02-12"); try std.testing.expectEqual(2000, ymd_ext.year); try std.testing.expectEqual(.feb, ymd_ext.month); try std.testing.expectEqual(12, ymd_ext.day); } { const ordinal = try Time.fromISO8601("2000031"); try std.testing.expectEqual(2000, ordinal.year); try std.testing.expectEqual(.jan, ordinal.month); try std.testing.expectEqual(31, ordinal.day); const ordinal_ext = try Time.fromISO8601("2000-043"); try std.testing.expectEqual(2000, ordinal_ext.year); try std.testing.expectEqual(.feb, ordinal_ext.month); try std.testing.expectEqual(12, ordinal_ext.day); } { const ymdh = try Time.fromISO8601("20000212 11"); try std.testing.expectEqual(2000, ymdh.year); try std.testing.expectEqual(.feb, ymdh.month); try std.testing.expectEqual(12, ymdh.day); try std.testing.expectEqual(11, ymdh.hour); const ymdh_ext = try Time.fromISO8601("2000-02-12T11"); try std.testing.expectEqual(2000, ymdh_ext.year); try std.testing.expectEqual(.feb, ymdh_ext.month); try std.testing.expectEqual(12, ymdh_ext.day); try std.testing.expectEqual(11, ymdh_ext.hour); } { const full = try Time.fromISO8601("20000212 111213Z"); try std.testing.expectEqual(2000, full.year); try std.testing.expectEqual(.feb, full.month); try std.testing.expectEqual(12, full.day); try std.testing.expectEqual(11, full.hour); try std.testing.expectEqual(12, full.minute); try std.testing.expectEqual(13, full.second); const full_ext = try Time.fromISO8601("2000-02-12T11:12:13Z"); try std.testing.expectEqual(2000, full_ext.year); try std.testing.expectEqual(.feb, full_ext.month); try std.testing.expectEqual(12, full_ext.day); try std.testing.expectEqual(11, full_ext.hour); try std.testing.expectEqual(12, full_ext.minute); try std.testing.expectEqual(13, full_ext.second); } { const s_frac = try Time.fromISO8601("2000-02-12T11:12:13.123Z"); try std.testing.expectEqual(123, s_frac.millisecond); try std.testing.expectEqual(0, s_frac.microsecond); try std.testing.expectEqual(0, s_frac.nanosecond); } { const offset = try Time.fromISO8601("2000-02-12T11:12:13.123-12:00"); try std.testing.expectEqual(-12 * s_per_hour, offset.offset); } { const offset = try Time.fromISO8601("2000-02-12T11:12:13+12:30"); try std.testing.expectEqual(12 * s_per_hour + 30 * s_per_min, offset.offset); } { const offset = try Time.fromISO8601("20000212T111213+1230"); try std.testing.expectEqual(12 * s_per_hour + 30 * s_per_min, offset.offset); } } pub fn fromRFC5322(eml: []const u8) !Time { const parseInt = std.fmt.parseInt; var time: Time = .{}; var i: usize = 0; // day { // consume until a digit while (i < eml.len and !std.ascii.isDigit(eml[i])) : (i += 1) {} const end = std.mem.indexOfScalarPos(u8, eml, i, ' ') orelse return error.InvalidFormat; time.day = try parseInt(u5, eml[i..end], 10); i = end + 1; } // month { // consume until an alpha while (i < eml.len and !std.ascii.isAlphabetic(eml[i])) : (i += 1) {} assert(eml.len >= i + 3); var buf: [3]u8 = undefined; buf[0] = std.ascii.toLower(eml[i]); buf[1] = std.ascii.toLower(eml[i + 1]); buf[2] = std.ascii.toLower(eml[i + 2]); time.month = std.meta.stringToEnum(Month, &buf) orelse return error.InvalidFormat; i += 3; } // year { // consume until a digit while (i < eml.len and !std.ascii.isDigit(eml[i])) : (i += 1) {} assert(eml.len >= i + 4); time.year = try parseInt(i32, eml[i .. i + 4], 10); i += 4; } // hour { // consume until a digit while (i < eml.len and !std.ascii.isDigit(eml[i])) : (i += 1) {} const end = std.mem.indexOfScalarPos(u8, eml, i, ':') orelse return error.InvalidFormat; time.hour = try parseInt(u5, eml[i..end], 10); i = end + 1; } // minute { // consume until a digit while (i < eml.len and !std.ascii.isDigit(eml[i])) : (i += 1) {} assert(i + 2 < eml.len); time.minute = try parseInt(u6, eml[i .. i + 2], 10); i += 2; } // second and zone { assert(i < eml.len); // seconds are optional if (eml[i] == ':') { i += 1; assert(i + 2 < eml.len); time.second = try parseInt(u6, eml[i .. i + 2], 10); i += 2; } // consume whitespace while (i < eml.len and std.ascii.isWhitespace(eml[i])) : (i += 1) {} assert(i + 5 <= eml.len); const hours = try parseInt(i32, eml[i .. i + 3], 10); const minutes = try parseInt(i32, eml[i + 3 .. i + 5], 10); const offset_minutes: i32 = if (hours > 0) hours * 60 + minutes else hours * 60 - minutes; time.offset = offset_minutes * 60; } return time; } test "fromRFC5322" { { const time = try Time.fromRFC5322("Thu, 13 Feb 1969 23:32:54 -0330"); try std.testing.expectEqual(1969, time.year); try std.testing.expectEqual(.feb, time.month); try std.testing.expectEqual(13, time.day); try std.testing.expectEqual(23, time.hour); try std.testing.expectEqual(32, time.minute); try std.testing.expectEqual(54, time.second); try std.testing.expectEqual(-12_600, time.offset); } { // FWS everywhere const time = try Time.fromRFC5322(" Thu, 13 \tFeb 1969\t\r\n 23:32:54 -0330"); try std.testing.expectEqual(1969, time.year); try std.testing.expectEqual(.feb, time.month); try std.testing.expectEqual(13, time.day); try std.testing.expectEqual(23, time.hour); try std.testing.expectEqual(32, time.minute); try std.testing.expectEqual(54, time.second); try std.testing.expectEqual(-12_600, time.offset); } } pub const Format = union(enum) { rfc3339, // YYYY-MM-DD-THH:MM:SS.sss+00:00 }; pub fn bufPrint(self: Time, buf: []u8, fmt: Format) ![]u8 { switch (fmt) { .rfc3339 => { if (self.year < 0) return error.InvalidTime; if (self.offset == 0) return std.fmt.bufPrint( buf, "{d:0>4}-{d:0>2}-{d:0>2}T{d:0>2}:{d:0>2}:{d:0>2}.{d:0>3}Z", .{ @as(u32, @intCast(self.year)), @intFromEnum(self.month), self.day, self.hour, self.minute, self.second, self.millisecond, }, ) else { const h = @divFloor(@abs(self.offset), s_per_hour); const min = @divFloor(@abs(self.offset) - h * s_per_hour, s_per_min); const sign: u8 = if (self.offset > 0) '+' else '-'; return std.fmt.bufPrint( buf, "{d:0>4}-{d:0>2}-{d:0>2}T{d:0>2}:{d:0>2}:{d:0>2}.{d:0>3}{c}{d:0>2}:{d:0>2}", .{ @as(u32, @intCast(self.year)), @intFromEnum(self.month), self.day, self.hour, self.minute, self.second, self.millisecond, sign, h, min, }, ); } }, } } pub fn compare(self: Time, time: Time) TimeComparison { const self_instant = self.instant(); const time_instant = time.instant(); if (self_instant.timestamp > time_instant.timestamp) { return .after; } else if (self_instant.timestamp < time_instant.timestamp) { return .before; } else { return .equal; } } pub fn after(self: Time, time: Time) bool { const self_instant = self.instant(); const time_instant = time.instant(); return self_instant.timestamp > time_instant.timestamp; } pub fn before(self: Time, time: Time) bool { const self_instant = self.instant(); const time_instant = time.instant(); return self_instant.timestamp < time_instant.timestamp; } pub fn eql(self: Time, time: Time) bool { const self_instant = self.instant(); const time_instant = time.instant(); return self_instant.timestamp == time_instant.timestamp; } }; pub fn daysSinceEpoch(timestamp: i64) i64 { return @divTrunc(timestamp, s_per_day); } test "days since epoch" { try std.testing.expectEqual(0, daysSinceEpoch(0)); try std.testing.expectEqual(-1, daysSinceEpoch(-(s_per_day + 1))); try std.testing.expectEqual(1, daysSinceEpoch(s_per_day + 1)); try std.testing.expectEqual(19797, daysSinceEpoch(1710523947)); } pub fn isLeapYear(year: i32) bool { // Neri/Schneider algorithm const d: i32 = if (@mod(year, 100) != 0) 4 else 16; return (year & (d - 1)) == 0; // if (@mod(year, 4) != 0) // return false; // if (@mod(year, 100) != 0) // return true; // return (0 == @mod(year, 400)); } /// returns the weekday given a number of days since the unix epoch /// https://howardhinnant.github.io/date_algorithms.html#weekday_from_days pub fn weekdayFromDays(days: i64) Weekday { if (days >= -4) return @enumFromInt(@mod((days + 4), 7)) else return @enumFromInt(@mod((days + 5), 7) + 6); } test "weekdayFromDays" { try std.testing.expectEqual(.thu, weekdayFromDays(0)); } /// return the civil date from the number of days since the epoch /// This is an implementation of Howard Hinnant's algorithm /// https://howardhinnant.github.io/date_algorithms.html#civil_from_days pub fn civilFromDays(days: i64) Date { // shift epoch from 1970-01-01 to 0000-03-01 const z = days + 719468; // Compute era const era = if (z >= 0) @divFloor(z, days_per_era) else @divFloor(z - days_per_era - 1, days_per_era); const doe: u32 = @intCast(z - era * days_per_era); // [0, days_per_era-1] const yoe: u32 = @intCast( @divFloor( doe - @divFloor(doe, 1460) + @divFloor(doe, 36524) - @divFloor(doe, 146096), 365, ), ); // [0, 399] const y: i32 = @intCast(yoe + era * 400); const doy = doe - (365 * yoe + @divFloor(yoe, 4) - @divFloor(yoe, 100)); // [0, 365] const mp = @divFloor(5 * doy + 2, 153); // [0, 11] const d = doy - @divFloor(153 * mp + 2, 5) + 1; // [1, 31] const m = if (mp < 10) mp + 3 else mp - 9; // [1, 12] return .{ .year = if (m <= 2) y + 1 else y, .month = @enumFromInt(m), .day = @truncate(d), }; } /// return the number of days since the epoch from the civil date pub fn daysFromCivil(date: Date) i64 { const m = @intFromEnum(date.month); const y = if (m <= 2) date.year - 1 else date.year; const era = if (y >= 0) @divFloor(y, 400) else @divFloor(y - 399, 400); const yoe: u32 = @intCast(y - era * 400); const doy = blk: { const a: u32 = if (m > 2) m - 3 else m + 9; const b = a * 153 + 2; break :blk @divFloor(b, 5) + date.day - 1; }; const doe: i32 = @intCast(yoe * 365 + @divFloor(yoe, 4) - @divFloor(yoe, 100) + doy); return era * days_per_era + doe - 719468; } test { std.testing.refAllDecls(@This()); _ = @import("timezone.zig"); }
0
repos/zeit
repos/zeit/src/timezone.zig
const std = @import("std"); const builtin = @import("builtin"); const zeit = @import("zeit.zig"); const assert = std.debug.assert; const Month = zeit.Month; const Weekday = zeit.Weekday; const s_per_min = std.time.s_per_min; const s_per_hour = std.time.s_per_hour; const s_per_day = std.time.s_per_day; pub const TimeZone = union(enum) { fixed: Fixed, posix: Posix, tzinfo: TZInfo, windows: switch (builtin.os.tag) { .windows => Windows, else => Noop, }, pub fn adjust(self: TimeZone, timestamp: i64) AdjustedTime { return switch (self) { inline else => |tz| tz.adjust(timestamp), }; } pub fn deinit(self: TimeZone) void { return switch (self) { .fixed => {}, .posix => {}, .tzinfo => |tz| tz.deinit(), .windows => |tz| tz.deinit(), }; } }; pub const AdjustedTime = struct { designation: []const u8, timestamp: i64, is_dst: bool, }; /// A Noop timezone we use for the windows struct when not on windows pub const Noop = struct { pub fn adjust(_: Noop, timestamp: i64) AdjustedTime { return .{ .designation = "noop", .timestamp = timestamp, .is_dst = false, }; } pub fn deinit(_: Noop) void {} }; /// A fixed timezone pub const Fixed = struct { name: []const u8, offset: i64, is_dst: bool, pub fn adjust(self: Fixed, timestamp: i64) AdjustedTime { return .{ .designation = self.name, .timestamp = timestamp + self.offset, .is_dst = self.is_dst, }; } }; /// A parsed representation of a Posix TZ string /// std offset dst [offset],start[/time],end[/time] /// std and dst can be quoted with <> /// offsets and times can be [+-]hh[:mm[:ss]] /// start and end are of the form J<n>, <n> or M<m>.<w>.<d> pub const Posix = struct { /// abbreviation for standard time std: []const u8, /// standard time offset in seconds std_offset: i64, /// abbreviation for daylight saving time dst: ?[]const u8 = null, /// offset when in dst, defaults to one hour less than std_offset if not present dst_offset: ?i64 = null, start: ?DSTSpec = null, end: ?DSTSpec = null, const DSTSpec = union(enum) { /// J<n>: julian day between 1 and 365, Leap day is never counted even in leap /// years julian: struct { day: u9, time: i64 = 7200, }, /// <n>: julian day between 0 and 365. Leap day counts julian_leap: struct { day: u9, time: i64 = 7200, }, /// M<m>.<w>.<d>: day d of week w of month m. Day is 0 (sunday) to 6. week /// is 1 to 5, where 5 would mean last d day of the month. mwd: struct { month: Month, week: u6, day: Weekday, time: i64 = 7200, }, fn parse(str: []const u8) !DSTSpec { assert(str.len > 0); switch (str[0]) { 'J' => { const julian = try std.fmt.parseInt(u9, str[1..], 10); return .{ .julian = .{ .day = julian } }; }, '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' => |_| { const julian = try std.fmt.parseInt(u9, str, 10); return .{ .julian_leap = .{ .day = julian } }; }, 'M' => { var i: usize = 1; const m_end = std.mem.indexOfScalarPos(u8, str, i, '.') orelse return error.InvalidPosix; const month = try std.fmt.parseInt(u4, str[i..m_end], 10); i = m_end + 1; const w_end = std.mem.indexOfScalarPos(u8, str, i, '.') orelse return error.InvalidPosix; const week = try std.fmt.parseInt(u6, str[i..w_end], 10); i = w_end + 1; const day = try std.fmt.parseInt(u3, str[i..], 10); return .{ .mwd = .{ .month = @enumFromInt(month), .week = week, .day = @enumFromInt(day), }, }; }, else => {}, } return error.InvalidPosix; } }; pub fn parse(str: []const u8) !Posix { var std_: []const u8 = ""; var std_offset: i64 = 0; var dst: ?[]const u8 = null; var dst_offset: ?i64 = null; var start: ?DSTSpec = null; var end: ?DSTSpec = null; const State = enum { std, std_offset, dst, dst_offset, start, end, }; var state: State = .std; var i: usize = 0; while (i < str.len) : (i += 1) { switch (state) { .std => { switch (str[i]) { '<' => { // quoted. Consume until > const end_qt = std.mem.indexOfScalar(u8, str[i..], '>') orelse return error.InvalidPosix; std_ = str[i + 1 .. end_qt + i]; i = end_qt; state = .std_offset; }, else => { i = std.mem.indexOfAnyPos(u8, str, i, "+-0123456789") orelse return error.InvalidPosix; std_ = str[0..i]; // backup one so this gets parsed as an offset i -= 1; state = .std_offset; }, } }, .std_offset => { const offset_start = i; while (i < str.len) : (i += 1) { switch (str[i]) { '+', '-', ':', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', => { if (i == str.len - 1) std_offset = parseTime(str[offset_start..]); }, else => { std_offset = parseTime(str[offset_start..i]); i -= 1; state = .dst; break; }, } } }, .dst => { switch (str[i]) { '<' => { // quoted. Consume until > const dst_start = i + 1; i = std.mem.indexOfScalarPos(u8, str, i, '>') orelse return error.InvalidPosix; dst = str[dst_start..i]; }, else => { const dst_start = i; i += 1; while (i < str.len) : (i += 1) { switch (str[i]) { ',' => { dst = str[dst_start..i]; state = .start; break; }, '+', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' => { dst = str[dst_start..i]; // backup one so this gets parsed as an offset i -= 1; state = .dst_offset; break; }, else => { if (i == str.len - 1) dst = str[dst_start..]; }, } } }, } }, .dst_offset => { const offset_start = i; while (i < str.len) : (i += 1) { switch (str[i]) { '+', '-', ':', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', => { if (i == str.len - 1) std_offset = parseTime(str[offset_start..]); }, ',' => { dst_offset = parseTime(str[offset_start..i]); state = .start; break; }, else => {}, } } }, .start => { const comma_idx = std.mem.indexOfScalarPos(u8, str, i, ',') orelse return error.InvalidPosix; if (std.mem.indexOfScalarPos(u8, str[0..comma_idx], i, '/')) |idx| { start = try DSTSpec.parse(str[i..idx]); switch (start.?) { .julian => |*j| j.time = parseTime(str[idx + 1 .. comma_idx]), .julian_leap => |*j| j.time = parseTime(str[idx + 1 .. comma_idx]), .mwd => |*m| m.time = parseTime(str[idx + 1 .. comma_idx]), } } else { start = try DSTSpec.parse(str[i..comma_idx]); } state = .end; i = comma_idx; }, .end => { if (std.mem.indexOfScalarPos(u8, str, i, '/')) |idx| { end = try DSTSpec.parse(str[i..idx]); switch (end.?) { .julian => |*j| j.time = parseTime(str[idx + 1 ..]), .julian_leap => |*j| j.time = parseTime(str[idx + 1 ..]), .mwd => |*m| m.time = parseTime(str[idx + 1 ..]), } } else { end = try DSTSpec.parse(str[i..]); } break; }, } } return .{ .std = std_, .std_offset = std_offset, .dst = dst, .dst_offset = dst_offset, .start = start, .end = end, }; } fn parseTime(str: []const u8) i64 { const State = enum { hour, minute, second, }; var is_neg = false; var state: State = .hour; var offset_h: i64 = 0; var offset_m: i64 = 0; var offset_s: i64 = 0; var i: usize = 0; while (i < str.len) : (i += 1) { switch (state) { .hour => { switch (str[i]) { '-' => is_neg = true, '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' => |d| { offset_h = offset_h * 10 + @as(i64, d - '0'); }, ':' => state = .minute, else => {}, } }, .minute => { switch (str[i]) { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' => |d| { offset_m = offset_m * 10 + @as(i64, d - '0'); }, ':' => state = .second, else => {}, } }, .second => { switch (str[i]) { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' => |d| { offset_s = offset_s * 10 + @as(i64, d - '0'); }, else => {}, } }, } } const offset = offset_h * s_per_hour + offset_m * s_per_min + offset_s; return if (is_neg) -offset else offset; } /// reports true if the unix timestamp occurs when DST is in effect fn isDST(self: Posix, timestamp: i64) bool { const start = self.start orelse return false; const end = self.end orelse return false; const days_from_epoch = @divFloor(timestamp, s_per_day); const civil = zeit.civilFromDays(days_from_epoch); const civil_month = @intFromEnum(civil.month); const start_s: i64 = switch (start) { .julian => |rule| blk: { const days = days_from_epoch - civil.month.daysBefore(civil.year) - civil.day + rule.day + 1; var s = (@as(i64, days - 1)) * s_per_day + rule.time; if (zeit.isLeapYear(civil.year) and rule.day >= 60) { s += s_per_day; } break :blk s + self.std_offset; }, .julian_leap => |rule| blk: { const days = days_from_epoch - civil.month.daysBefore(civil.year) - civil.day + rule.day; break :blk @as(i64, days) * s_per_day + rule.time + self.std_offset; }, .mwd => |rule| blk: { const rule_month = @intFromEnum(rule.month); if (civil_month < rule_month) return false; // bail early if we are greater than this month. we know we only // rely on the end time. We yield a value that is before the // timestamp if (civil_month > rule_month) break :blk timestamp - 1; // we are in the same month // first_of_month is the weekday on the first of the month const first_of_month = zeit.weekdayFromDays(days_from_epoch - civil.day + 1); // days is the first "rule day" of the month (ie the first // Sunday of the month) var days: u9 = first_of_month.daysUntil(rule.day); var i: usize = 1; while (i < rule.week) : (i += 1) { if (days + 7 >= rule.month.lastDay(civil.year)) break; days += 7; } // days_from_epoch is the number of days to the DST day from the // epoch const dst_days_from_epoch: i64 = days_from_epoch - civil.day + days; break :blk @as(i64, dst_days_from_epoch) * s_per_day + rule.time + self.std_offset; }, }; const end_s: i64 = switch (end) { .julian => |rule| blk: { const days = days_from_epoch - civil.month.daysBefore(civil.year) - civil.day + rule.day + 1; var s = (@as(i64, days) - 1) * s_per_day + rule.time; if (zeit.isLeapYear(civil.year) and rule.day >= 60) { s += s_per_day; } break :blk s + self.std_offset; }, .julian_leap => |rule| blk: { const days = days_from_epoch - civil.month.daysBefore(civil.year) - civil.day + rule.day + 1; break :blk @as(i64, days) * s_per_day + rule.time + self.std_offset; }, .mwd => |rule| blk: { const rule_month = @intFromEnum(rule.month); if (civil_month > rule_month) return false; // bail early if we are less than this month. we know we only // rely on the start time. We yield a value that is after the // timestamp if (civil_month < rule_month) break :blk timestamp + 1; // first_of_month is the weekday on the first of the month const first_of_month = zeit.weekdayFromDays(days_from_epoch - civil.day + 1); // days is the first "rule day" of the month (ie the first // Sunday of the month) var days: u9 = first_of_month.daysUntil(rule.day); var i: usize = 1; while (i < rule.week) : (i += 1) { if (days + 7 >= rule.month.lastDay(civil.year)) break; days += 7; } // days_from_epoch is the number of days to the DST day from the // epoch const dst_days_from_epoch: i64 = days_from_epoch - civil.day + days; break :blk @as(i64, dst_days_from_epoch) * s_per_day + rule.time + self.std_offset; }, }; return timestamp >= start_s and timestamp < end_s; } pub fn adjust(self: Posix, timestamp: i64) AdjustedTime { if (self.dst) |dst| { return .{ .designation = dst, .timestamp = timestamp - (self.dst_offset orelse self.std_offset - s_per_hour), .is_dst = true, }; } else { return .{ .designation = self.std, .timestamp = timestamp - self.std_offset, .is_dst = false, }; } } }; pub const TZInfo = struct { allocator: std.mem.Allocator, transitions: []const Transition, timetypes: []const Timetype, leapseconds: []const Leapsecond, footer: ?[]const u8, posix_tz: ?Posix, const Leapsecond = struct { occurrence: i48, correction: i16, }; const Timetype = struct { offset: i32, flags: u8, name_data: [6:0]u8, pub fn name(self: *const Timetype) [:0]const u8 { return std.mem.sliceTo(self.name_data[0..], 0); } pub fn isDst(self: Timetype) bool { return (self.flags & 0x01) > 0; } pub fn standardTimeIndicator(self: Timetype) bool { return (self.flags & 0x02) > 0; } pub fn utIndicator(self: Timetype) bool { return (self.flags & 0x04) > 0; } }; const Transition = struct { ts: i64, timetype: *Timetype, }; const Header = extern struct { magic: [4]u8, version: u8, reserved: [15]u8, counts: extern struct { isutcnt: u32, isstdcnt: u32, leapcnt: u32, timecnt: u32, typecnt: u32, charcnt: u32, }, }; pub fn parse(allocator: std.mem.Allocator, reader: anytype) !TZInfo { var legacy_header = try reader.readStruct(Header); if (!std.mem.eql(u8, &legacy_header.magic, "TZif")) return error.BadHeader; if (legacy_header.version != 0 and legacy_header.version != '2' and legacy_header.version != '3') return error.BadVersion; if (builtin.target.cpu.arch.endian() != std.builtin.Endian.big) { std.mem.byteSwapAllFields(@TypeOf(legacy_header.counts), &legacy_header.counts); } if (legacy_header.version == 0) { return parseBlock(allocator, reader, legacy_header, true); } else { // If the format is modern, just skip over the legacy data const skipv = legacy_header.counts.timecnt * 5 + legacy_header.counts.typecnt * 6 + legacy_header.counts.charcnt + legacy_header.counts.leapcnt * 8 + legacy_header.counts.isstdcnt + legacy_header.counts.isutcnt; try reader.skipBytes(skipv, .{}); var header = try reader.readStruct(Header); if (!std.mem.eql(u8, &header.magic, "TZif")) return error.BadHeader; if (header.version != '2' and header.version != '3') return error.BadVersion; if (builtin.target.cpu.arch.endian() != std.builtin.Endian.big) { std.mem.byteSwapAllFields(@TypeOf(header.counts), &header.counts); } return parseBlock(allocator, reader, header, false); } } fn parseBlock(allocator: std.mem.Allocator, reader: anytype, header: Header, legacy: bool) !TZInfo { if (header.counts.isstdcnt != 0 and header.counts.isstdcnt != header.counts.typecnt) return error.Malformed; // rfc8536: isstdcnt [...] MUST either be zero or equal to "typecnt" if (header.counts.isutcnt != 0 and header.counts.isutcnt != header.counts.typecnt) return error.Malformed; // rfc8536: isutcnt [...] MUST either be zero or equal to "typecnt" if (header.counts.typecnt == 0) return error.Malformed; // rfc8536: typecnt [...] MUST NOT be zero if (header.counts.charcnt == 0) return error.Malformed; // rfc8536: charcnt [...] MUST NOT be zero if (header.counts.charcnt > 256 + 6) return error.Malformed; // Not explicitly banned by rfc8536 but nonsensical var leapseconds = try allocator.alloc(Leapsecond, header.counts.leapcnt); errdefer allocator.free(leapseconds); var transitions = try allocator.alloc(Transition, header.counts.timecnt); errdefer allocator.free(transitions); var timetypes = try allocator.alloc(Timetype, header.counts.typecnt); errdefer allocator.free(timetypes); // Parse transition types var i: usize = 0; while (i < header.counts.timecnt) : (i += 1) { transitions[i].ts = if (legacy) try reader.readInt(i32, .big) else try reader.readInt(i64, .big); } i = 0; while (i < header.counts.timecnt) : (i += 1) { const tt = try reader.readByte(); if (tt >= timetypes.len) return error.Malformed; // rfc8536: Each type index MUST be in the range [0, "typecnt" - 1] transitions[i].timetype = &timetypes[tt]; } // Parse time types i = 0; while (i < header.counts.typecnt) : (i += 1) { const offset = try reader.readInt(i32, .big); if (offset < -2147483648) return error.Malformed; // rfc8536: utoff [...] MUST NOT be -2**31 const dst = try reader.readByte(); if (dst != 0 and dst != 1) return error.Malformed; // rfc8536: (is)dst [...] The value MUST be 0 or 1. const idx = try reader.readByte(); if (idx > header.counts.charcnt - 1) return error.Malformed; // rfc8536: (desig)idx [...] Each index MUST be in the range [0, "charcnt" - 1] timetypes[i] = .{ .offset = offset, .flags = dst, .name_data = undefined, }; // Temporarily cache idx in name_data to be processed after we've read the designator names below timetypes[i].name_data[0] = idx; } var designators_data: [256 + 6]u8 = undefined; try reader.readNoEof(designators_data[0..header.counts.charcnt]); const designators = designators_data[0..header.counts.charcnt]; if (designators[designators.len - 1] != 0) return error.Malformed; // rfc8536: charcnt [...] includes the trailing NUL (0x00) octet // Iterate through the timetypes again, setting the designator names for (timetypes) |*tt| { const name = std.mem.sliceTo(designators[tt.name_data[0]..], 0); // We are mandating the "SHOULD" 6-character limit so we can pack the struct better, and to conform to POSIX. if (name.len > 6) return error.Malformed; // rfc8536: Time zone designations SHOULD consist of at least three (3) and no more than six (6) ASCII characters. @memcpy(tt.name_data[0..name.len], name); tt.name_data[name.len] = 0; } // Parse leap seconds i = 0; while (i < header.counts.leapcnt) : (i += 1) { const occur: i64 = if (legacy) try reader.readInt(i32, .big) else try reader.readInt(i64, .big); if (occur < 0) return error.Malformed; // rfc8536: occur [...] MUST be nonnegative if (i > 0 and leapseconds[i - 1].occurrence + 2419199 > occur) return error.Malformed; // rfc8536: occur [...] each later value MUST be at least 2419199 greater than the previous value if (occur > std.math.maxInt(i48)) return error.Malformed; // Unreasonably far into the future const corr = try reader.readInt(i32, .big); if (i == 0 and corr != -1 and corr != 1) return error.Malformed; // rfc8536: The correction value in the first leap-second record, if present, MUST be either one (1) or minus one (-1) if (i > 0 and leapseconds[i - 1].correction != corr + 1 and leapseconds[i - 1].correction != corr - 1) return error.Malformed; // rfc8536: The correction values in adjacent leap-second records MUST differ by exactly one (1) if (corr > std.math.maxInt(i16)) return error.Malformed; // Unreasonably large correction leapseconds[i] = .{ .occurrence = @as(i48, @intCast(occur)), .correction = @as(i16, @intCast(corr)), }; } // Parse standard/wall indicators i = 0; while (i < header.counts.isstdcnt) : (i += 1) { const stdtime = try reader.readByte(); if (stdtime == 1) { timetypes[i].flags |= 0x02; } } // Parse UT/local indicators i = 0; while (i < header.counts.isutcnt) : (i += 1) { const ut = try reader.readByte(); if (ut == 1) { timetypes[i].flags |= 0x04; if (!timetypes[i].standardTimeIndicator()) return error.Malformed; // rfc8536: standard/wall value MUST be one (1) if the UT/local value is one (1) } } // Footer var footer: ?[]const u8 = null; var posix: ?Posix = null; if (!legacy) { if ((try reader.readByte()) != '\n') return error.Malformed; // An rfc8536 footer must start with a newline var footerdata_buf: [128]u8 = undefined; const footer_mem = reader.readUntilDelimiter(&footerdata_buf, '\n') catch |err| switch (err) { error.StreamTooLong => return error.OverlargeFooter, // Read more than 128 bytes, much larger than any reasonable POSIX TZ string else => return err, }; if (footer_mem.len != 0) { footer = try allocator.dupe(u8, footer_mem); posix = try Posix.parse(footer.?); } } errdefer if (footer) |ft| allocator.free(ft); return .{ .allocator = allocator, .transitions = transitions, .timetypes = timetypes, .leapseconds = leapseconds, .footer = footer, .posix_tz = posix, }; } pub fn deinit(self: TZInfo) void { if (self.footer) |footer| { self.allocator.free(footer); } self.allocator.free(self.leapseconds); self.allocator.free(self.transitions); self.allocator.free(self.timetypes); } /// adjust a unix timestamp to the timezone pub fn adjust(self: TZInfo, timestamp: i64) AdjustedTime { // if we are past the last transition and have a footer, we use the // footer data if ((self.transitions.len == 0 or self.transitions[self.transitions.len - 1].ts <= timestamp) and self.posix_tz != null) { const posix = self.posix_tz.?; return posix.adjust(timestamp); } const transition: Transition = blk: for (self.transitions, 0..) |transition, i| { // TODO: implement what go does, which is a copy of c for how to // handle times before the first transition how to handle this if (i == 0 and transition.ts > timestamp) @panic("unimplemented. please complain to tim"); if (transition.ts <= timestamp) continue; // we use the latest transition before ts, which is one less than // our current iter break :blk self.transitions[i - 1]; } else self.transitions[self.transitions.len - 1]; return .{ .designation = transition.timetype.name(), .timestamp = timestamp + transition.timetype.offset, .is_dst = transition.timetype.isDst(), }; } }; pub const Windows = struct { const windows = struct { const BOOL = std.os.windows.BOOL; const BOOLEAN = std.os.windows.BOOLEAN; const DWORD = std.os.windows.DWORD; const FILETIME = std.os.windows.FILETIME; const LONG = std.os.windows.LONG; const USHORT = std.os.windows.USHORT; const WCHAR = std.os.windows.WCHAR; const WINAPI = std.os.windows.WINAPI; const WORD = std.os.windows.WORD; const epoch = std.time.epoch.windows; const ERROR_SUCCESS = 0x00; const ERROR_NO_MORE_ITEMS = 0x103; pub const TIME_ZONE_ID_INVALID = @as(DWORD, std.math.maxInt(DWORD)); const DYNAMIC_TIME_ZONE_INFORMATION = extern struct { Bias: LONG, StandardName: [32]WCHAR, StandardDate: SYSTEMTIME, StandardBias: LONG, DaylightName: [32]WCHAR, DaylightDate: SYSTEMTIME, DaylightBias: LONG, TimeZoneKeyName: [128]WCHAR, DynamicDaylightTimeDisabled: BOOLEAN, }; const SYSTEMTIME = extern struct { wYear: WORD, wMonth: WORD, wDayOfWeek: WORD, wDay: WORD, wHour: WORD, wMinute: WORD, wSecond: WORD, wMilliseconds: WORD, }; const TIME_ZONE_INFORMATION = extern struct { Bias: LONG, StandardName: [32]WCHAR, StandardDate: SYSTEMTIME, StandardBias: LONG, DaylightName: [32]WCHAR, DaylightDate: SYSTEMTIME, DaylightBias: LONG, }; pub extern "advapi32" fn EnumDynamicTimeZoneInformation(dwIndex: DWORD, lpTimeZoneInformation: *DYNAMIC_TIME_ZONE_INFORMATION) callconv(WINAPI) DWORD; pub extern "kernel32" fn GetDynamicTimeZoneInformation(pTimeZoneInformation: *DYNAMIC_TIME_ZONE_INFORMATION) callconv(WINAPI) DWORD; pub extern "kernel32" fn GetTimeZoneInformationForYear(wYear: USHORT, pdtzi: ?*const DYNAMIC_TIME_ZONE_INFORMATION, ptzi: *TIME_ZONE_INFORMATION) callconv(WINAPI) BOOL; pub extern "kernel32" fn SystemTimeToTzSpecificLocalTimeEx(lpTimeZoneInfo: ?*const DYNAMIC_TIME_ZONE_INFORMATION, lpUniversalTime: *const SYSTEMTIME, lpLocalTime: *SYSTEMTIME) callconv(WINAPI) BOOL; }; zoneinfo: windows.DYNAMIC_TIME_ZONE_INFORMATION, allocator: std.mem.Allocator, standard_name: []const u8, dst_name: []const u8, /// retrieves the local timezone settings for this machine pub fn local(allocator: std.mem.Allocator) !Windows { var info: windows.DYNAMIC_TIME_ZONE_INFORMATION = undefined; const result = windows.GetDynamicTimeZoneInformation(&info); if (result == windows.TIME_ZONE_ID_INVALID) return error.TimeZoneIdInvalid; const std_idx = std.mem.indexOfScalar(u16, &info.StandardName, 0x00) orelse info.StandardName.len; const dst_idx = std.mem.indexOfScalar(u16, &info.DaylightName, 0x00) orelse info.DaylightName.len; const standard_name = try std.unicode.utf16LeToUtf8Alloc(allocator, info.StandardName[0..std_idx]); const dst_name = try std.unicode.utf16LeToUtf8Alloc(allocator, info.DaylightName[0..dst_idx]); return .{ .zoneinfo = info, .allocator = allocator, .standard_name = standard_name, .dst_name = dst_name, }; } pub fn deinit(self: Windows) void { self.allocator.free(self.standard_name); self.allocator.free(self.dst_name); } /// Adjusts the time to the timezone /// 1. Convert timestamp to windows.SYSTEMTIME using internal methods /// 2. Convert SYSTEMTIME to target timezone using windows api /// 3. Get the relevant TIME_ZONE_INFORMATION for the year /// 4. Determine if we are in DST or not /// 5. Return result pub fn adjust(self: Windows, timestamp: i64) AdjustedTime { const instant = zeit.instant(.{ .source = .{ .unix_timestamp = timestamp } }) catch unreachable; const time = instant.time(); const systemtime: windows.SYSTEMTIME = .{ .wYear = @intCast(time.year), .wMonth = @intFromEnum(time.month), .wDayOfWeek = 0, // not used in calculation .wDay = time.day, .wHour = time.hour, .wMinute = time.minute, .wSecond = time.second, .wMilliseconds = time.millisecond, }; var localtime: windows.SYSTEMTIME = undefined; if (windows.SystemTimeToTzSpecificLocalTimeEx(&self.zoneinfo, &systemtime, &localtime) == 0) { const err = std.os.windows.kernel32.GetLastError(); std.log.err("{}", .{err}); @panic("TODO"); } var tzi: windows.TIME_ZONE_INFORMATION = undefined; if (windows.GetTimeZoneInformationForYear(localtime.wYear, &self.zoneinfo, &tzi) == 0) { const err = std.os.windows.kernel32.GetLastError(); std.log.err("{}", .{err}); @panic("TODO"); } const is_dst = isDST(timestamp, &tzi, &localtime); return .{ .designation = if (is_dst) self.dst_name else self.standard_name, .timestamp = systemtimeToUnixTimestamp(localtime), .is_dst = is_dst, }; } fn systemtimeToUnixTimestamp(sys: windows.SYSTEMTIME) i64 { const lzt = systemtimetoZeitTime(sys); return lzt.instant().unixTimestamp(); } fn systemtimetoZeitTime(sys: windows.SYSTEMTIME) zeit.Time { return .{ .year = sys.wYear, .month = @enumFromInt(sys.wMonth), .day = @intCast(sys.wDay), .hour = @intCast(sys.wHour), .minute = @intCast(sys.wMinute), .second = @intCast(sys.wSecond), .millisecond = @intCast(sys.wMilliseconds), }; } fn isDST(timestamp: i64, tzi: *const windows.TIME_ZONE_INFORMATION, time: *const windows.SYSTEMTIME) bool { // If wMonth on StandardDate is 0, the timezone doesn't have DST if (tzi.StandardDate.wMonth == 0) return false; const start = tzi.DaylightDate; const end = tzi.StandardDate; // Before DST starts if (time.wMonth < start.wMonth) return false; // After DST ends if (time.wMonth > end.wMonth) return false; // In the months between if (time.wMonth > start.wMonth and time.wMonth < end.wMonth) return true; const days_from_epoch = @divFloor(timestamp, s_per_day); // first_of_month is the weekday on the first of the month const first_of_month = zeit.weekdayFromDays(days_from_epoch - time.wDay + 1); // In the start transition month if (time.wMonth == start.wMonth) { // days is the first "rule day" of the month (ie the first // Sunday of the month) var days: u9 = first_of_month.daysUntil(@enumFromInt(start.wDayOfWeek)); var i: usize = 1; while (i < start.wDay) : (i += 1) { const month: zeit.Month = @enumFromInt(start.wDay); if (days + 7 >= month.lastDay(time.wYear)) break; days += 7; } if (time.wDay == days) { if (time.wHour == start.wHour) { return time.wMinute >= start.wMinute; } return time.wHour >= start.wHour; } return time.wDay >= days; } // In the end transition month if (time.wMonth == end.wMonth) { // days is the first "rule day" of the month (ie the first // Sunday of the month) var days: u9 = first_of_month.daysUntil(@enumFromInt(end.wDayOfWeek)); var i: usize = 1; while (i < end.wDay) : (i += 1) { const month: zeit.Month = @enumFromInt(end.wDay); if (days + 7 >= month.lastDay(time.wYear)) break; days += 7; } if (time.wDay == days) { if (time.wHour == end.wHour) { return time.wMinute >= end.wMinute; } return time.wHour >= end.wHour; } return time.wDay >= days; } return false; } pub fn loadFromName(allocator: std.mem.Allocator, name: []const u8) !Windows { var buf: [128]u16 = undefined; const n = try std.unicode.utf8ToUtf16Le(&buf, name); const target = buf[0..n]; var result: windows.DWORD = windows.ERROR_SUCCESS; var i: windows.DWORD = 0; var dtzi: windows.DYNAMIC_TIME_ZONE_INFORMATION = undefined; while (result == windows.ERROR_SUCCESS) : (i += 1) { result = windows.EnumDynamicTimeZoneInformation(i, &dtzi); const name_idx = std.mem.indexOfScalar(u16, &dtzi.TimeZoneKeyName, 0x00) orelse dtzi.TimeZoneKeyName.len; if (std.mem.eql(u16, target, dtzi.TimeZoneKeyName[0..name_idx])) break; } else return error.TimezoneNotFound; const std_idx = std.mem.indexOfScalar(u16, &dtzi.StandardName, 0x00) orelse dtzi.StandardName.len; const dst_idx = std.mem.indexOfScalar(u16, &dtzi.DaylightName, 0x00) orelse dtzi.DaylightName.len; const standard_name = try std.unicode.utf16LeToUtf8Alloc(allocator, dtzi.StandardName[0..std_idx]); const dst_name = try std.unicode.utf16LeToUtf8Alloc(allocator, dtzi.DaylightName[0..dst_idx]); return .{ .zoneinfo = dtzi, .allocator = allocator, .standard_name = standard_name, .dst_name = dst_name, }; } }; test "timezone.zig: test Fixed" { const fixed: Fixed = .{ .name = "test", .offset = -600, .is_dst = false, }; const adjusted = fixed.adjust(0); try std.testing.expectEqual(-600, adjusted.timestamp); } test "timezone.zig: Posix.isDST" { const t = try Posix.parse("CST6CDT,M3.2.0,M11.1.0"); try std.testing.expectEqual(false, t.isDST(1704088800)); // Jan 1 2024 00:00:00 CST try std.testing.expectEqual(false, t.isDST(1733032800)); // Dec 1 2024 00:00:00 CST try std.testing.expectEqual(true, t.isDST(1717218000)); // Jun 1 2024 00:00:00 CST // One second after DST starts try std.testing.expectEqual(true, t.isDST(1710057601)); // One second before DST starts try std.testing.expectEqual(false, t.isDST(1710057599)); // One second before DST ends try std.testing.expectEqual(true, t.isDST(1730620799)); // One second after DST ends try std.testing.expectEqual(false, t.isDST(1730620801)); const j = try Posix.parse("CST6CDT,J1,J4"); try std.testing.expectEqual(true, j.isDST(1704268800)); } test "timezone.zig: Posix.parseTime" { try std.testing.expectEqual(0, Posix.parseTime("00:00:00")); try std.testing.expectEqual(-3600, Posix.parseTime("-1")); try std.testing.expectEqual(-7200, Posix.parseTime("-02:00:00")); try std.testing.expectEqual(3660, Posix.parseTime("+1:01")); } test "timezone.zig: Posix.parse" { { const t = try Posix.parse("<UTC>-1"); try std.testing.expectEqualStrings("UTC", t.std); try std.testing.expectEqual(-3600, t.std_offset); } { const t = try Posix.parse("<UTC>1"); try std.testing.expectEqualStrings("UTC", t.std); try std.testing.expectEqual(3600, t.std_offset); } { const t = try Posix.parse("<UTC>+1"); try std.testing.expectEqualStrings("UTC", t.std); try std.testing.expectEqual(3600, t.std_offset); } { const t = try Posix.parse("UTC+1"); try std.testing.expectEqualStrings("UTC", t.std); try std.testing.expectEqual(3600, t.std_offset); } { const t = try Posix.parse("UTC+1:01"); try std.testing.expectEqualStrings("UTC", t.std); try std.testing.expectEqual(3660, t.std_offset); } { const t = try Posix.parse("UTC-1:01:01"); try std.testing.expectEqualStrings("UTC", t.std); try std.testing.expectEqual(-3661, t.std_offset); } { const t = try Posix.parse("CST1CDT"); try std.testing.expectEqualStrings("CST", t.std); try std.testing.expectEqual(3600, t.std_offset); try std.testing.expectEqualStrings("CDT", t.dst.?); } { const t = try Posix.parse("CST1<CDT>"); try std.testing.expectEqualStrings("CST", t.std); try std.testing.expectEqual(3600, t.std_offset); try std.testing.expectEqualStrings("CDT", t.dst.?); } { const t = try Posix.parse("CST1CDT,J100,J200"); try std.testing.expectEqualStrings("CST", t.std); try std.testing.expectEqual(3600, t.std_offset); try std.testing.expectEqualStrings("CDT", t.dst.?); try std.testing.expectEqual(100, t.start.?.julian.day); try std.testing.expectEqual(200, t.end.?.julian.day); } { const t = try Posix.parse("CST1CDT,100,200"); try std.testing.expectEqualStrings("CST", t.std); try std.testing.expectEqual(3600, t.std_offset); try std.testing.expectEqualStrings("CDT", t.dst.?); try std.testing.expectEqual(100, t.start.?.julian_leap.day); try std.testing.expectEqual(200, t.end.?.julian_leap.day); } { const t = try Posix.parse("CST1CDT,M3.5.1,M11.3.0"); try std.testing.expectEqualStrings("CST", t.std); try std.testing.expectEqual(3600, t.std_offset); try std.testing.expectEqualStrings("CDT", t.dst.?); try std.testing.expectEqual(.mar, t.start.?.mwd.month); try std.testing.expectEqual(5, t.start.?.mwd.week); try std.testing.expectEqual(.mon, t.start.?.mwd.day); try std.testing.expectEqual(.nov, t.end.?.mwd.month); try std.testing.expectEqual(3, t.end.?.mwd.week); try std.testing.expectEqual(.sun, t.end.?.mwd.day); } { const t = try Posix.parse("CST1CDT,M3.5.1/02:00:00,M11.3.0/1"); try std.testing.expectEqualStrings("CST", t.std); try std.testing.expectEqual(3600, t.std_offset); try std.testing.expectEqualStrings("CDT", t.dst.?); try std.testing.expectEqual(.mar, t.start.?.mwd.month); try std.testing.expectEqual(5, t.start.?.mwd.week); try std.testing.expectEqual(.mon, t.start.?.mwd.day); try std.testing.expectEqual(7200, t.start.?.mwd.time); try std.testing.expectEqual(.nov, t.end.?.mwd.month); try std.testing.expectEqual(3, t.end.?.mwd.week); try std.testing.expectEqual(.sun, t.end.?.mwd.day); try std.testing.expectEqual(3600, t.end.?.mwd.time); } } test "timezone.zig: Posix.adjust" { const t = try Posix.parse("UTC+1"); const adjusted = t.adjust(0); try std.testing.expectEqual(-3600, adjusted.timestamp); } test "timezone.zig: Posix.DSTSpec.parse" { { const spec = try Posix.DSTSpec.parse("J365"); try std.testing.expectEqual(365, spec.julian.day); } { const spec = try Posix.DSTSpec.parse("365"); try std.testing.expectEqual(365, spec.julian_leap.day); } { const spec = try Posix.DSTSpec.parse("M3.5.1"); try std.testing.expectEqual(.mar, spec.mwd.month); try std.testing.expectEqual(5, spec.mwd.week); try std.testing.expectEqual(.mon, spec.mwd.day); } { const spec = try Posix.DSTSpec.parse("M11.3.0"); try std.testing.expectEqual(.nov, spec.mwd.month); try std.testing.expectEqual(3, spec.mwd.week); try std.testing.expectEqual(.sun, spec.mwd.day); } }
0
repos/zeit
repos/zeit/src/location.zig
//!This file is generated. Do not edit directly! Run `zig build generate` to update after obtaining //!the latest dataset. const builtin = @import("builtin"); pub const Location = enum { @"Africa/Abidjan", @"Africa/Accra", @"Africa/Addis_Ababa", @"Africa/Algiers", @"Africa/Asmera", @"Africa/Bamako", @"Africa/Bangui", @"Africa/Banjul", @"Africa/Bissau", @"Africa/Blantyre", @"Africa/Brazzaville", @"Africa/Bujumbura", @"Africa/Cairo", @"Africa/Casablanca", @"Africa/Ceuta", @"Africa/Conakry", @"Africa/Dakar", @"Africa/Dar_es_Salaam", @"Africa/Djibouti", @"Africa/Douala", @"Africa/El_Aaiun", @"Africa/Freetown", @"Africa/Gaborone", @"Africa/Harare", @"Africa/Johannesburg", @"Africa/Juba", @"Africa/Kampala", @"Africa/Khartoum", @"Africa/Kigali", @"Africa/Kinshasa", @"Africa/Lagos", @"Africa/Libreville", @"Africa/Lome", @"Africa/Luanda", @"Africa/Lubumbashi", @"Africa/Lusaka", @"Africa/Malabo", @"Africa/Maputo", @"Africa/Maseru", @"Africa/Mbabane", @"Africa/Mogadishu", @"Africa/Monrovia", @"Africa/Nairobi", @"Africa/Ndjamena", @"Africa/Niamey", @"Africa/Nouakchott", @"Africa/Ouagadougou", @"Africa/Porto-Novo", @"Africa/Sao_Tome", @"Africa/Tripoli", @"Africa/Tunis", @"Africa/Windhoek", @"America/Adak", @"America/Anchorage", @"America/Anguilla", @"America/Antigua", @"America/Araguaina", @"America/Argentina/La_Rioja", @"America/Argentina/Rio_Gallegos", @"America/Argentina/Salta", @"America/Argentina/San_Juan", @"America/Argentina/San_Luis", @"America/Argentina/Tucuman", @"America/Argentina/Ushuaia", @"America/Aruba", @"America/Asuncion", @"America/Bahia", @"America/Bahia_Banderas", @"America/Barbados", @"America/Belem", @"America/Belize", @"America/Blanc-Sablon", @"America/Boa_Vista", @"America/Bogota", @"America/Boise", @"America/Buenos_Aires", @"America/Cambridge_Bay", @"America/Campo_Grande", @"America/Cancun", @"America/Caracas", @"America/Catamarca", @"America/Cayenne", @"America/Cayman", @"America/Chicago", @"America/Chihuahua", @"America/Ciudad_Juarez", @"America/Coral_Harbour", @"America/Cordoba", @"America/Costa_Rica", @"America/Creston", @"America/Cuiaba", @"America/Curacao", @"America/Danmarkshavn", @"America/Dawson", @"America/Dawson_Creek", @"America/Denver", @"America/Detroit", @"America/Dominica", @"America/Edmonton", @"America/Eirunepe", @"America/El_Salvador", @"America/Fort_Nelson", @"America/Fortaleza", @"America/Glace_Bay", @"America/Godthab", @"America/Goose_Bay", @"America/Grand_Turk", @"America/Grenada", @"America/Guadeloupe", @"America/Guatemala", @"America/Guayaquil", @"America/Guyana", @"America/Halifax", @"America/Havana", @"America/Hermosillo", @"America/Indiana/Knox", @"America/Indiana/Marengo", @"America/Indiana/Petersburg", @"America/Indiana/Tell_City", @"America/Indiana/Vevay", @"America/Indiana/Vincennes", @"America/Indiana/Winamac", @"America/Indianapolis", @"America/Inuvik", @"America/Iqaluit", @"America/Jamaica", @"America/Jujuy", @"America/Juneau", @"America/Kentucky/Monticello", @"America/Kralendijk", @"America/La_Paz", @"America/Lima", @"America/Los_Angeles", @"America/Louisville", @"America/Lower_Princes", @"America/Maceio", @"America/Managua", @"America/Manaus", @"America/Marigot", @"America/Martinique", @"America/Matamoros", @"America/Mazatlan", @"America/Mendoza", @"America/Menominee", @"America/Merida", @"America/Metlakatla", @"America/Mexico_City", @"America/Miquelon", @"America/Moncton", @"America/Monterrey", @"America/Montevideo", @"America/Montserrat", @"America/Nassau", @"America/New_York", @"America/Nome", @"America/Noronha", @"America/North_Dakota/Beulah", @"America/North_Dakota/Center", @"America/North_Dakota/New_Salem", @"America/Ojinaga", @"America/Panama", @"America/Paramaribo", @"America/Phoenix", @"America/Port-au-Prince", @"America/Port_of_Spain", @"America/Porto_Velho", @"America/Puerto_Rico", @"America/Punta_Arenas", @"America/Rankin_Inlet", @"America/Recife", @"America/Regina", @"America/Resolute", @"America/Rio_Branco", @"America/Santarem", @"America/Santiago", @"America/Santo_Domingo", @"America/Sao_Paulo", @"America/Scoresbysund", @"America/Sitka", @"America/St_Barthelemy", @"America/St_Johns", @"America/St_Kitts", @"America/St_Lucia", @"America/St_Thomas", @"America/St_Vincent", @"America/Swift_Current", @"America/Tegucigalpa", @"America/Thule", @"America/Tijuana", @"America/Toronto", @"America/Tortola", @"America/Vancouver", @"America/Whitehorse", @"America/Winnipeg", @"America/Yakutat", @"Antarctica/Casey", @"Antarctica/Davis", @"Antarctica/DumontDUrville", @"Antarctica/Macquarie", @"Antarctica/Mawson", @"Antarctica/McMurdo", @"Antarctica/Palmer", @"Antarctica/Rothera", @"Antarctica/Syowa", @"Antarctica/Vostok", @"Arctic/Longyearbyen", @"Asia/Aden", @"Asia/Almaty", @"Asia/Amman", @"Asia/Anadyr", @"Asia/Aqtau", @"Asia/Aqtobe", @"Asia/Ashgabat", @"Asia/Atyrau", @"Asia/Baghdad", @"Asia/Bahrain", @"Asia/Baku", @"Asia/Bangkok", @"Asia/Barnaul", @"Asia/Beirut", @"Asia/Bishkek", @"Asia/Brunei", @"Asia/Calcutta", @"Asia/Chita", @"Asia/Choibalsan", @"Asia/Colombo", @"Asia/Damascus", @"Asia/Dhaka", @"Asia/Dili", @"Asia/Dubai", @"Asia/Dushanbe", @"Asia/Famagusta", @"Asia/Gaza", @"Asia/Hebron", @"Asia/Hong_Kong", @"Asia/Hovd", @"Asia/Irkutsk", @"Asia/Jakarta", @"Asia/Jayapura", @"Asia/Jerusalem", @"Asia/Kabul", @"Asia/Kamchatka", @"Asia/Karachi", @"Asia/Katmandu", @"Asia/Khandyga", @"Asia/Krasnoyarsk", @"Asia/Kuala_Lumpur", @"Asia/Kuching", @"Asia/Kuwait", @"Asia/Macau", @"Asia/Magadan", @"Asia/Makassar", @"Asia/Manila", @"Asia/Muscat", @"Asia/Nicosia", @"Asia/Novokuznetsk", @"Asia/Novosibirsk", @"Asia/Omsk", @"Asia/Oral", @"Asia/Phnom_Penh", @"Asia/Pontianak", @"Asia/Pyongyang", @"Asia/Qatar", @"Asia/Qostanay", @"Asia/Qyzylorda", @"Asia/Rangoon", @"Asia/Riyadh", @"Asia/Saigon", @"Asia/Sakhalin", @"Asia/Samarkand", @"Asia/Seoul", @"Asia/Shanghai", @"Asia/Singapore", @"Asia/Srednekolymsk", @"Asia/Taipei", @"Asia/Tashkent", @"Asia/Tbilisi", @"Asia/Tehran", @"Asia/Thimphu", @"Asia/Tokyo", @"Asia/Tomsk", @"Asia/Ulaanbaatar", @"Asia/Urumqi", @"Asia/Ust-Nera", @"Asia/Vientiane", @"Asia/Vladivostok", @"Asia/Yakutsk", @"Asia/Yekaterinburg", @"Asia/Yerevan", @"Atlantic/Azores", @"Atlantic/Bermuda", @"Atlantic/Canary", @"Atlantic/Cape_Verde", @"Atlantic/Faeroe", @"Atlantic/Madeira", @"Atlantic/Reykjavik", @"Atlantic/South_Georgia", @"Atlantic/St_Helena", @"Atlantic/Stanley", @"Australia/Adelaide", @"Australia/Brisbane", @"Australia/Broken_Hill", @"Australia/Darwin", @"Australia/Eucla", @"Australia/Hobart", @"Australia/Lindeman", @"Australia/Lord_Howe", @"Australia/Melbourne", @"Australia/Perth", @"Australia/Sydney", CST6CDT, EST5EDT, @"Etc/GMT", @"Etc/GMT+1", @"Etc/GMT+10", @"Etc/GMT+11", @"Etc/GMT+12", @"Etc/GMT+2", @"Etc/GMT+3", @"Etc/GMT+4", @"Etc/GMT+5", @"Etc/GMT+6", @"Etc/GMT+7", @"Etc/GMT+8", @"Etc/GMT+9", @"Etc/GMT-1", @"Etc/GMT-10", @"Etc/GMT-11", @"Etc/GMT-12", @"Etc/GMT-13", @"Etc/GMT-14", @"Etc/GMT-2", @"Etc/GMT-3", @"Etc/GMT-4", @"Etc/GMT-5", @"Etc/GMT-6", @"Etc/GMT-7", @"Etc/GMT-8", @"Etc/GMT-9", @"Etc/UTC", @"Europe/Amsterdam", @"Europe/Andorra", @"Europe/Astrakhan", @"Europe/Athens", @"Europe/Belgrade", @"Europe/Berlin", @"Europe/Bratislava", @"Europe/Brussels", @"Europe/Bucharest", @"Europe/Budapest", @"Europe/Busingen", @"Europe/Chisinau", @"Europe/Copenhagen", @"Europe/Dublin", @"Europe/Gibraltar", @"Europe/Guernsey", @"Europe/Helsinki", @"Europe/Isle_of_Man", @"Europe/Istanbul", @"Europe/Jersey", @"Europe/Kaliningrad", @"Europe/Kiev", @"Europe/Kirov", @"Europe/Lisbon", @"Europe/Ljubljana", @"Europe/London", @"Europe/Luxembourg", @"Europe/Madrid", @"Europe/Malta", @"Europe/Mariehamn", @"Europe/Minsk", @"Europe/Monaco", @"Europe/Moscow", @"Europe/Oslo", @"Europe/Paris", @"Europe/Podgorica", @"Europe/Prague", @"Europe/Riga", @"Europe/Rome", @"Europe/Samara", @"Europe/San_Marino", @"Europe/Sarajevo", @"Europe/Saratov", @"Europe/Simferopol", @"Europe/Skopje", @"Europe/Sofia", @"Europe/Stockholm", @"Europe/Tallinn", @"Europe/Tirane", @"Europe/Ulyanovsk", @"Europe/Vaduz", @"Europe/Vatican", @"Europe/Vienna", @"Europe/Vilnius", @"Europe/Volgograd", @"Europe/Warsaw", @"Europe/Zagreb", @"Europe/Zurich", @"Indian/Antananarivo", @"Indian/Chagos", @"Indian/Christmas", @"Indian/Cocos", @"Indian/Comoro", @"Indian/Kerguelen", @"Indian/Mahe", @"Indian/Maldives", @"Indian/Mauritius", @"Indian/Mayotte", @"Indian/Reunion", MST7MDT, PST8PDT, @"Pacific/Apia", @"Pacific/Auckland", @"Pacific/Bougainville", @"Pacific/Chatham", @"Pacific/Easter", @"Pacific/Efate", @"Pacific/Enderbury", @"Pacific/Fakaofo", @"Pacific/Fiji", @"Pacific/Funafuti", @"Pacific/Galapagos", @"Pacific/Gambier", @"Pacific/Guadalcanal", @"Pacific/Guam", @"Pacific/Honolulu", @"Pacific/Kiritimati", @"Pacific/Kosrae", @"Pacific/Kwajalein", @"Pacific/Majuro", @"Pacific/Marquesas", @"Pacific/Midway", @"Pacific/Nauru", @"Pacific/Niue", @"Pacific/Norfolk", @"Pacific/Noumea", @"Pacific/Pago_Pago", @"Pacific/Palau", @"Pacific/Pitcairn", @"Pacific/Ponape", @"Pacific/Port_Moresby", @"Pacific/Rarotonga", @"Pacific/Saipan", @"Pacific/Tahiti", @"Pacific/Tarawa", @"Pacific/Tongatapu", @"Pacific/Truk", @"Pacific/Wake", @"Pacific/Wallis", pub fn asText(self: Location) []const u8 { switch (builtin.os.tag) { .windows => {}, else => return @tagName(self), } return switch (self) { .@"Africa/Abidjan" => "Greenwich Standard Time", .@"Africa/Accra" => "Greenwich Standard Time", .@"Africa/Addis_Ababa" => "E. Africa Standard Time", .@"Africa/Algiers" => "W. Central Africa Standard Time", .@"Africa/Asmera" => "E. Africa Standard Time", .@"Africa/Bamako" => "Greenwich Standard Time", .@"Africa/Bangui" => "W. Central Africa Standard Time", .@"Africa/Banjul" => "Greenwich Standard Time", .@"Africa/Bissau" => "Greenwich Standard Time", .@"Africa/Blantyre" => "South Africa Standard Time", .@"Africa/Brazzaville" => "W. Central Africa Standard Time", .@"Africa/Bujumbura" => "South Africa Standard Time", .@"Africa/Cairo" => "Egypt Standard Time", .@"Africa/Casablanca" => "Morocco Standard Time", .@"Africa/Ceuta" => "Romance Standard Time", .@"Africa/Conakry" => "Greenwich Standard Time", .@"Africa/Dakar" => "Greenwich Standard Time", .@"Africa/Dar_es_Salaam" => "E. Africa Standard Time", .@"Africa/Djibouti" => "E. Africa Standard Time", .@"Africa/Douala" => "W. Central Africa Standard Time", .@"Africa/El_Aaiun" => "Morocco Standard Time", .@"Africa/Freetown" => "Greenwich Standard Time", .@"Africa/Gaborone" => "South Africa Standard Time", .@"Africa/Harare" => "South Africa Standard Time", .@"Africa/Johannesburg" => "South Africa Standard Time", .@"Africa/Juba" => "South Sudan Standard Time", .@"Africa/Kampala" => "E. Africa Standard Time", .@"Africa/Khartoum" => "Sudan Standard Time", .@"Africa/Kigali" => "South Africa Standard Time", .@"Africa/Kinshasa" => "W. Central Africa Standard Time", .@"Africa/Lagos" => "W. Central Africa Standard Time", .@"Africa/Libreville" => "W. Central Africa Standard Time", .@"Africa/Lome" => "Greenwich Standard Time", .@"Africa/Luanda" => "W. Central Africa Standard Time", .@"Africa/Lubumbashi" => "South Africa Standard Time", .@"Africa/Lusaka" => "South Africa Standard Time", .@"Africa/Malabo" => "W. Central Africa Standard Time", .@"Africa/Maputo" => "South Africa Standard Time", .@"Africa/Maseru" => "South Africa Standard Time", .@"Africa/Mbabane" => "South Africa Standard Time", .@"Africa/Mogadishu" => "E. Africa Standard Time", .@"Africa/Monrovia" => "Greenwich Standard Time", .@"Africa/Nairobi" => "E. Africa Standard Time", .@"Africa/Ndjamena" => "W. Central Africa Standard Time", .@"Africa/Niamey" => "W. Central Africa Standard Time", .@"Africa/Nouakchott" => "Greenwich Standard Time", .@"Africa/Ouagadougou" => "Greenwich Standard Time", .@"Africa/Porto-Novo" => "W. Central Africa Standard Time", .@"Africa/Sao_Tome" => "Sao Tome Standard Time", .@"Africa/Tripoli" => "Libya Standard Time", .@"Africa/Tunis" => "W. Central Africa Standard Time", .@"Africa/Windhoek" => "Namibia Standard Time", .@"America/Adak" => "Aleutian Standard Time", .@"America/Anchorage" => "Alaskan Standard Time", .@"America/Anguilla" => "SA Western Standard Time", .@"America/Antigua" => "SA Western Standard Time", .@"America/Araguaina" => "Tocantins Standard Time", .@"America/Argentina/La_Rioja" => "Argentina Standard Time", .@"America/Argentina/Rio_Gallegos" => "Argentina Standard Time", .@"America/Argentina/Salta" => "Argentina Standard Time", .@"America/Argentina/San_Juan" => "Argentina Standard Time", .@"America/Argentina/San_Luis" => "Argentina Standard Time", .@"America/Argentina/Tucuman" => "Argentina Standard Time", .@"America/Argentina/Ushuaia" => "Argentina Standard Time", .@"America/Aruba" => "SA Western Standard Time", .@"America/Asuncion" => "Paraguay Standard Time", .@"America/Bahia" => "Bahia Standard Time", .@"America/Bahia_Banderas" => "Central Standard Time (Mexico)", .@"America/Barbados" => "SA Western Standard Time", .@"America/Belem" => "SA Eastern Standard Time", .@"America/Belize" => "Central America Standard Time", .@"America/Blanc-Sablon" => "SA Western Standard Time", .@"America/Boa_Vista" => "SA Western Standard Time", .@"America/Bogota" => "SA Pacific Standard Time", .@"America/Boise" => "Mountain Standard Time", .@"America/Buenos_Aires" => "Argentina Standard Time", .@"America/Cambridge_Bay" => "Mountain Standard Time", .@"America/Campo_Grande" => "Central Brazilian Standard Time", .@"America/Cancun" => "Eastern Standard Time (Mexico)", .@"America/Caracas" => "Venezuela Standard Time", .@"America/Catamarca" => "Argentina Standard Time", .@"America/Cayenne" => "SA Eastern Standard Time", .@"America/Cayman" => "SA Pacific Standard Time", .@"America/Chicago" => "Central Standard Time", .@"America/Chihuahua" => "Central Standard Time (Mexico)", .@"America/Ciudad_Juarez" => "Mountain Standard Time", .@"America/Coral_Harbour" => "SA Pacific Standard Time", .@"America/Cordoba" => "Argentina Standard Time", .@"America/Costa_Rica" => "Central America Standard Time", .@"America/Creston" => "US Mountain Standard Time", .@"America/Cuiaba" => "Central Brazilian Standard Time", .@"America/Curacao" => "SA Western Standard Time", .@"America/Danmarkshavn" => "Greenwich Standard Time", .@"America/Dawson" => "Yukon Standard Time", .@"America/Dawson_Creek" => "US Mountain Standard Time", .@"America/Denver" => "Mountain Standard Time", .@"America/Detroit" => "Eastern Standard Time", .@"America/Dominica" => "SA Western Standard Time", .@"America/Edmonton" => "Mountain Standard Time", .@"America/Eirunepe" => "SA Pacific Standard Time", .@"America/El_Salvador" => "Central America Standard Time", .@"America/Fort_Nelson" => "US Mountain Standard Time", .@"America/Fortaleza" => "SA Eastern Standard Time", .@"America/Glace_Bay" => "Atlantic Standard Time", .@"America/Godthab" => "Greenland Standard Time", .@"America/Goose_Bay" => "Atlantic Standard Time", .@"America/Grand_Turk" => "Turks And Caicos Standard Time", .@"America/Grenada" => "SA Western Standard Time", .@"America/Guadeloupe" => "SA Western Standard Time", .@"America/Guatemala" => "Central America Standard Time", .@"America/Guayaquil" => "SA Pacific Standard Time", .@"America/Guyana" => "SA Western Standard Time", .@"America/Halifax" => "Atlantic Standard Time", .@"America/Havana" => "Cuba Standard Time", .@"America/Hermosillo" => "US Mountain Standard Time", .@"America/Indiana/Knox" => "Central Standard Time", .@"America/Indiana/Marengo" => "US Eastern Standard Time", .@"America/Indiana/Petersburg" => "Eastern Standard Time", .@"America/Indiana/Tell_City" => "Central Standard Time", .@"America/Indiana/Vevay" => "US Eastern Standard Time", .@"America/Indiana/Vincennes" => "Eastern Standard Time", .@"America/Indiana/Winamac" => "Eastern Standard Time", .@"America/Indianapolis" => "US Eastern Standard Time", .@"America/Inuvik" => "Mountain Standard Time", .@"America/Iqaluit" => "Eastern Standard Time", .@"America/Jamaica" => "SA Pacific Standard Time", .@"America/Jujuy" => "Argentina Standard Time", .@"America/Juneau" => "Alaskan Standard Time", .@"America/Kentucky/Monticello" => "Eastern Standard Time", .@"America/Kralendijk" => "SA Western Standard Time", .@"America/La_Paz" => "SA Western Standard Time", .@"America/Lima" => "SA Pacific Standard Time", .@"America/Los_Angeles" => "Pacific Standard Time", .@"America/Louisville" => "Eastern Standard Time", .@"America/Lower_Princes" => "SA Western Standard Time", .@"America/Maceio" => "SA Eastern Standard Time", .@"America/Managua" => "Central America Standard Time", .@"America/Manaus" => "SA Western Standard Time", .@"America/Marigot" => "SA Western Standard Time", .@"America/Martinique" => "SA Western Standard Time", .@"America/Matamoros" => "Central Standard Time", .@"America/Mazatlan" => "Mountain Standard Time (Mexico)", .@"America/Mendoza" => "Argentina Standard Time", .@"America/Menominee" => "Central Standard Time", .@"America/Merida" => "Central Standard Time (Mexico)", .@"America/Metlakatla" => "Alaskan Standard Time", .@"America/Mexico_City" => "Central Standard Time (Mexico)", .@"America/Miquelon" => "Saint Pierre Standard Time", .@"America/Moncton" => "Atlantic Standard Time", .@"America/Monterrey" => "Central Standard Time (Mexico)", .@"America/Montevideo" => "Montevideo Standard Time", .@"America/Montserrat" => "SA Western Standard Time", .@"America/Nassau" => "Eastern Standard Time", .@"America/New_York" => "Eastern Standard Time", .@"America/Nome" => "Alaskan Standard Time", .@"America/Noronha" => "UTC-02", .@"America/North_Dakota/Beulah" => "Central Standard Time", .@"America/North_Dakota/Center" => "Central Standard Time", .@"America/North_Dakota/New_Salem" => "Central Standard Time", .@"America/Ojinaga" => "Central Standard Time", .@"America/Panama" => "SA Pacific Standard Time", .@"America/Paramaribo" => "SA Eastern Standard Time", .@"America/Phoenix" => "US Mountain Standard Time", .@"America/Port-au-Prince" => "Haiti Standard Time", .@"America/Port_of_Spain" => "SA Western Standard Time", .@"America/Porto_Velho" => "SA Western Standard Time", .@"America/Puerto_Rico" => "SA Western Standard Time", .@"America/Punta_Arenas" => "Magallanes Standard Time", .@"America/Rankin_Inlet" => "Central Standard Time", .@"America/Recife" => "SA Eastern Standard Time", .@"America/Regina" => "Canada Central Standard Time", .@"America/Resolute" => "Central Standard Time", .@"America/Rio_Branco" => "SA Pacific Standard Time", .@"America/Santarem" => "SA Eastern Standard Time", .@"America/Santiago" => "Pacific SA Standard Time", .@"America/Santo_Domingo" => "SA Western Standard Time", .@"America/Sao_Paulo" => "E. South America Standard Time", .@"America/Scoresbysund" => "Azores Standard Time", .@"America/Sitka" => "Alaskan Standard Time", .@"America/St_Barthelemy" => "SA Western Standard Time", .@"America/St_Johns" => "Newfoundland Standard Time", .@"America/St_Kitts" => "SA Western Standard Time", .@"America/St_Lucia" => "SA Western Standard Time", .@"America/St_Thomas" => "SA Western Standard Time", .@"America/St_Vincent" => "SA Western Standard Time", .@"America/Swift_Current" => "Canada Central Standard Time", .@"America/Tegucigalpa" => "Central America Standard Time", .@"America/Thule" => "Atlantic Standard Time", .@"America/Tijuana" => "Pacific Standard Time (Mexico)", .@"America/Toronto" => "Eastern Standard Time", .@"America/Tortola" => "SA Western Standard Time", .@"America/Vancouver" => "Pacific Standard Time", .@"America/Whitehorse" => "Yukon Standard Time", .@"America/Winnipeg" => "Central Standard Time", .@"America/Yakutat" => "Alaskan Standard Time", .@"Antarctica/Casey" => "Central Pacific Standard Time", .@"Antarctica/Davis" => "SE Asia Standard Time", .@"Antarctica/DumontDUrville" => "West Pacific Standard Time", .@"Antarctica/Macquarie" => "Tasmania Standard Time", .@"Antarctica/Mawson" => "West Asia Standard Time", .@"Antarctica/McMurdo" => "New Zealand Standard Time", .@"Antarctica/Palmer" => "SA Eastern Standard Time", .@"Antarctica/Rothera" => "SA Eastern Standard Time", .@"Antarctica/Syowa" => "E. Africa Standard Time", .@"Antarctica/Vostok" => "Central Asia Standard Time", .@"Arctic/Longyearbyen" => "W. Europe Standard Time", .@"Asia/Aden" => "Arab Standard Time", .@"Asia/Almaty" => "West Asia Standard Time", .@"Asia/Amman" => "Jordan Standard Time", .@"Asia/Anadyr" => "Russia Time Zone 11", .@"Asia/Aqtau" => "West Asia Standard Time", .@"Asia/Aqtobe" => "West Asia Standard Time", .@"Asia/Ashgabat" => "West Asia Standard Time", .@"Asia/Atyrau" => "West Asia Standard Time", .@"Asia/Baghdad" => "Arabic Standard Time", .@"Asia/Bahrain" => "Arab Standard Time", .@"Asia/Baku" => "Azerbaijan Standard Time", .@"Asia/Bangkok" => "SE Asia Standard Time", .@"Asia/Barnaul" => "Altai Standard Time", .@"Asia/Beirut" => "Middle East Standard Time", .@"Asia/Bishkek" => "Central Asia Standard Time", .@"Asia/Brunei" => "Singapore Standard Time", .@"Asia/Calcutta" => "India Standard Time", .@"Asia/Chita" => "Transbaikal Standard Time", .@"Asia/Choibalsan" => "Ulaanbaatar Standard Time", .@"Asia/Colombo" => "Sri Lanka Standard Time", .@"Asia/Damascus" => "Syria Standard Time", .@"Asia/Dhaka" => "Bangladesh Standard Time", .@"Asia/Dili" => "Tokyo Standard Time", .@"Asia/Dubai" => "Arabian Standard Time", .@"Asia/Dushanbe" => "West Asia Standard Time", .@"Asia/Famagusta" => "GTB Standard Time", .@"Asia/Gaza" => "West Bank Standard Time", .@"Asia/Hebron" => "West Bank Standard Time", .@"Asia/Hong_Kong" => "China Standard Time", .@"Asia/Hovd" => "W. Mongolia Standard Time", .@"Asia/Irkutsk" => "North Asia East Standard Time", .@"Asia/Jakarta" => "SE Asia Standard Time", .@"Asia/Jayapura" => "Tokyo Standard Time", .@"Asia/Jerusalem" => "Israel Standard Time", .@"Asia/Kabul" => "Afghanistan Standard Time", .@"Asia/Kamchatka" => "Russia Time Zone 11", .@"Asia/Karachi" => "Pakistan Standard Time", .@"Asia/Katmandu" => "Nepal Standard Time", .@"Asia/Khandyga" => "Yakutsk Standard Time", .@"Asia/Krasnoyarsk" => "North Asia Standard Time", .@"Asia/Kuala_Lumpur" => "Singapore Standard Time", .@"Asia/Kuching" => "Singapore Standard Time", .@"Asia/Kuwait" => "Arab Standard Time", .@"Asia/Macau" => "China Standard Time", .@"Asia/Magadan" => "Magadan Standard Time", .@"Asia/Makassar" => "Singapore Standard Time", .@"Asia/Manila" => "Singapore Standard Time", .@"Asia/Muscat" => "Arabian Standard Time", .@"Asia/Nicosia" => "GTB Standard Time", .@"Asia/Novokuznetsk" => "North Asia Standard Time", .@"Asia/Novosibirsk" => "N. Central Asia Standard Time", .@"Asia/Omsk" => "Omsk Standard Time", .@"Asia/Oral" => "West Asia Standard Time", .@"Asia/Phnom_Penh" => "SE Asia Standard Time", .@"Asia/Pontianak" => "SE Asia Standard Time", .@"Asia/Pyongyang" => "North Korea Standard Time", .@"Asia/Qatar" => "Arab Standard Time", .@"Asia/Qostanay" => "West Asia Standard Time", .@"Asia/Qyzylorda" => "Qyzylorda Standard Time", .@"Asia/Rangoon" => "Myanmar Standard Time", .@"Asia/Riyadh" => "Arab Standard Time", .@"Asia/Saigon" => "SE Asia Standard Time", .@"Asia/Sakhalin" => "Sakhalin Standard Time", .@"Asia/Samarkand" => "West Asia Standard Time", .@"Asia/Seoul" => "Korea Standard Time", .@"Asia/Shanghai" => "China Standard Time", .@"Asia/Singapore" => "Singapore Standard Time", .@"Asia/Srednekolymsk" => "Russia Time Zone 10", .@"Asia/Taipei" => "Taipei Standard Time", .@"Asia/Tashkent" => "West Asia Standard Time", .@"Asia/Tbilisi" => "Georgian Standard Time", .@"Asia/Tehran" => "Iran Standard Time", .@"Asia/Thimphu" => "Bangladesh Standard Time", .@"Asia/Tokyo" => "Tokyo Standard Time", .@"Asia/Tomsk" => "Tomsk Standard Time", .@"Asia/Ulaanbaatar" => "Ulaanbaatar Standard Time", .@"Asia/Urumqi" => "Central Asia Standard Time", .@"Asia/Ust-Nera" => "Vladivostok Standard Time", .@"Asia/Vientiane" => "SE Asia Standard Time", .@"Asia/Vladivostok" => "Vladivostok Standard Time", .@"Asia/Yakutsk" => "Yakutsk Standard Time", .@"Asia/Yekaterinburg" => "Ekaterinburg Standard Time", .@"Asia/Yerevan" => "Caucasus Standard Time", .@"Atlantic/Azores" => "Azores Standard Time", .@"Atlantic/Bermuda" => "Atlantic Standard Time", .@"Atlantic/Canary" => "GMT Standard Time", .@"Atlantic/Cape_Verde" => "Cape Verde Standard Time", .@"Atlantic/Faeroe" => "GMT Standard Time", .@"Atlantic/Madeira" => "GMT Standard Time", .@"Atlantic/Reykjavik" => "Greenwich Standard Time", .@"Atlantic/South_Georgia" => "UTC-02", .@"Atlantic/St_Helena" => "Greenwich Standard Time", .@"Atlantic/Stanley" => "SA Eastern Standard Time", .@"Australia/Adelaide" => "Cen. Australia Standard Time", .@"Australia/Brisbane" => "E. Australia Standard Time", .@"Australia/Broken_Hill" => "Cen. Australia Standard Time", .@"Australia/Darwin" => "AUS Central Standard Time", .@"Australia/Eucla" => "Aus Central W. Standard Time", .@"Australia/Hobart" => "Tasmania Standard Time", .@"Australia/Lindeman" => "E. Australia Standard Time", .@"Australia/Lord_Howe" => "Lord Howe Standard Time", .@"Australia/Melbourne" => "AUS Eastern Standard Time", .@"Australia/Perth" => "W. Australia Standard Time", .@"Australia/Sydney" => "AUS Eastern Standard Time", .CST6CDT => "Central Standard Time", .EST5EDT => "Eastern Standard Time", .@"Etc/GMT" => "UTC", .@"Etc/GMT+1" => "Cape Verde Standard Time", .@"Etc/GMT+10" => "Hawaiian Standard Time", .@"Etc/GMT+11" => "UTC-11", .@"Etc/GMT+12" => "Dateline Standard Time", .@"Etc/GMT+2" => "UTC-02", .@"Etc/GMT+3" => "SA Eastern Standard Time", .@"Etc/GMT+4" => "SA Western Standard Time", .@"Etc/GMT+5" => "SA Pacific Standard Time", .@"Etc/GMT+6" => "Central America Standard Time", .@"Etc/GMT+7" => "US Mountain Standard Time", .@"Etc/GMT+8" => "UTC-08", .@"Etc/GMT+9" => "UTC-09", .@"Etc/GMT-1" => "W. Central Africa Standard Time", .@"Etc/GMT-10" => "West Pacific Standard Time", .@"Etc/GMT-11" => "Central Pacific Standard Time", .@"Etc/GMT-12" => "UTC+12", .@"Etc/GMT-13" => "UTC+13", .@"Etc/GMT-14" => "Line Islands Standard Time", .@"Etc/GMT-2" => "South Africa Standard Time", .@"Etc/GMT-3" => "E. Africa Standard Time", .@"Etc/GMT-4" => "Arabian Standard Time", .@"Etc/GMT-5" => "West Asia Standard Time", .@"Etc/GMT-6" => "Central Asia Standard Time", .@"Etc/GMT-7" => "SE Asia Standard Time", .@"Etc/GMT-8" => "Singapore Standard Time", .@"Etc/GMT-9" => "Tokyo Standard Time", .@"Etc/UTC" => "UTC", .@"Europe/Amsterdam" => "W. Europe Standard Time", .@"Europe/Andorra" => "W. Europe Standard Time", .@"Europe/Astrakhan" => "Astrakhan Standard Time", .@"Europe/Athens" => "GTB Standard Time", .@"Europe/Belgrade" => "Central Europe Standard Time", .@"Europe/Berlin" => "W. Europe Standard Time", .@"Europe/Bratislava" => "Central Europe Standard Time", .@"Europe/Brussels" => "Romance Standard Time", .@"Europe/Bucharest" => "GTB Standard Time", .@"Europe/Budapest" => "Central Europe Standard Time", .@"Europe/Busingen" => "W. Europe Standard Time", .@"Europe/Chisinau" => "E. Europe Standard Time", .@"Europe/Copenhagen" => "Romance Standard Time", .@"Europe/Dublin" => "GMT Standard Time", .@"Europe/Gibraltar" => "W. Europe Standard Time", .@"Europe/Guernsey" => "GMT Standard Time", .@"Europe/Helsinki" => "FLE Standard Time", .@"Europe/Isle_of_Man" => "GMT Standard Time", .@"Europe/Istanbul" => "Turkey Standard Time", .@"Europe/Jersey" => "GMT Standard Time", .@"Europe/Kaliningrad" => "Kaliningrad Standard Time", .@"Europe/Kiev" => "FLE Standard Time", .@"Europe/Kirov" => "Russian Standard Time", .@"Europe/Lisbon" => "GMT Standard Time", .@"Europe/Ljubljana" => "Central Europe Standard Time", .@"Europe/London" => "GMT Standard Time", .@"Europe/Luxembourg" => "W. Europe Standard Time", .@"Europe/Madrid" => "Romance Standard Time", .@"Europe/Malta" => "W. Europe Standard Time", .@"Europe/Mariehamn" => "FLE Standard Time", .@"Europe/Minsk" => "Belarus Standard Time", .@"Europe/Monaco" => "W. Europe Standard Time", .@"Europe/Moscow" => "Russian Standard Time", .@"Europe/Oslo" => "W. Europe Standard Time", .@"Europe/Paris" => "Romance Standard Time", .@"Europe/Podgorica" => "Central Europe Standard Time", .@"Europe/Prague" => "Central Europe Standard Time", .@"Europe/Riga" => "FLE Standard Time", .@"Europe/Rome" => "W. Europe Standard Time", .@"Europe/Samara" => "Russia Time Zone 3", .@"Europe/San_Marino" => "W. Europe Standard Time", .@"Europe/Sarajevo" => "Central European Standard Time", .@"Europe/Saratov" => "Saratov Standard Time", .@"Europe/Simferopol" => "Russian Standard Time", .@"Europe/Skopje" => "Central European Standard Time", .@"Europe/Sofia" => "FLE Standard Time", .@"Europe/Stockholm" => "W. Europe Standard Time", .@"Europe/Tallinn" => "FLE Standard Time", .@"Europe/Tirane" => "Central Europe Standard Time", .@"Europe/Ulyanovsk" => "Astrakhan Standard Time", .@"Europe/Vaduz" => "W. Europe Standard Time", .@"Europe/Vatican" => "W. Europe Standard Time", .@"Europe/Vienna" => "W. Europe Standard Time", .@"Europe/Vilnius" => "FLE Standard Time", .@"Europe/Volgograd" => "Volgograd Standard Time", .@"Europe/Warsaw" => "Central European Standard Time", .@"Europe/Zagreb" => "Central European Standard Time", .@"Europe/Zurich" => "W. Europe Standard Time", .@"Indian/Antananarivo" => "E. Africa Standard Time", .@"Indian/Chagos" => "Central Asia Standard Time", .@"Indian/Christmas" => "SE Asia Standard Time", .@"Indian/Cocos" => "Myanmar Standard Time", .@"Indian/Comoro" => "E. Africa Standard Time", .@"Indian/Kerguelen" => "West Asia Standard Time", .@"Indian/Mahe" => "Mauritius Standard Time", .@"Indian/Maldives" => "West Asia Standard Time", .@"Indian/Mauritius" => "Mauritius Standard Time", .@"Indian/Mayotte" => "E. Africa Standard Time", .@"Indian/Reunion" => "Mauritius Standard Time", .MST7MDT => "Mountain Standard Time", .PST8PDT => "Pacific Standard Time", .@"Pacific/Apia" => "Samoa Standard Time", .@"Pacific/Auckland" => "New Zealand Standard Time", .@"Pacific/Bougainville" => "Bougainville Standard Time", .@"Pacific/Chatham" => "Chatham Islands Standard Time", .@"Pacific/Easter" => "Easter Island Standard Time", .@"Pacific/Efate" => "Central Pacific Standard Time", .@"Pacific/Enderbury" => "UTC+13", .@"Pacific/Fakaofo" => "UTC+13", .@"Pacific/Fiji" => "Fiji Standard Time", .@"Pacific/Funafuti" => "UTC+12", .@"Pacific/Galapagos" => "Central America Standard Time", .@"Pacific/Gambier" => "UTC-09", .@"Pacific/Guadalcanal" => "Central Pacific Standard Time", .@"Pacific/Guam" => "West Pacific Standard Time", .@"Pacific/Honolulu" => "Hawaiian Standard Time", .@"Pacific/Kiritimati" => "Line Islands Standard Time", .@"Pacific/Kosrae" => "Central Pacific Standard Time", .@"Pacific/Kwajalein" => "UTC+12", .@"Pacific/Majuro" => "UTC+12", .@"Pacific/Marquesas" => "Marquesas Standard Time", .@"Pacific/Midway" => "UTC-11", .@"Pacific/Nauru" => "UTC+12", .@"Pacific/Niue" => "UTC-11", .@"Pacific/Norfolk" => "Norfolk Standard Time", .@"Pacific/Noumea" => "Central Pacific Standard Time", .@"Pacific/Pago_Pago" => "UTC-11", .@"Pacific/Palau" => "Tokyo Standard Time", .@"Pacific/Pitcairn" => "UTC-08", .@"Pacific/Ponape" => "Central Pacific Standard Time", .@"Pacific/Port_Moresby" => "West Pacific Standard Time", .@"Pacific/Rarotonga" => "Hawaiian Standard Time", .@"Pacific/Saipan" => "West Pacific Standard Time", .@"Pacific/Tahiti" => "Hawaiian Standard Time", .@"Pacific/Tarawa" => "UTC+12", .@"Pacific/Tongatapu" => "Tonga Standard Time", .@"Pacific/Truk" => "West Pacific Standard Time", .@"Pacific/Wake" => "UTC+12", .@"Pacific/Wallis" => "UTC+12", }; } };
0
repos
repos/snow/server.zig
const std = @import("std"); const pike = @import("pike"); const sync = @import("sync.zig"); const os = std.os; const net = std.net; const mem = std.mem; const meta = std.meta; const atomic = std.atomic; usingnamespace @import("socket.zig"); pub fn Server(comptime opts: Options) type { return struct { const Self = @This(); const Node = struct { ptr: *Connection, next: ?*Node = null, }; const ServerSocket = Socket(.server, opts); const Protocol = opts.protocol_type; pub const Connection = struct { node: Node, socket: ServerSocket, frame: @Frame(Self.runConnection), }; protocol: Protocol, allocator: *mem.Allocator, notifier: *const pike.Notifier, socket: pike.Socket, lock: sync.Mutex = .{}, done: atomic.Bool = atomic.Bool.init(false), pool: [opts.max_connections_per_server]*Connection = undefined, pool_len: usize = 0, cleanup_counter: sync.Counter = .{}, cleanup_queue: ?*Node = null, frame: @Frame(Self.run) = undefined, pub fn init(protocol: Protocol, allocator: *mem.Allocator, notifier: *const pike.Notifier, address: net.Address) !Self { var self = Self{ .protocol = protocol, .allocator = allocator, .notifier = notifier, .socket = try pike.Socket.init(os.AF_INET, os.SOCK_STREAM, os.IPPROTO_TCP, 0), }; errdefer self.socket.deinit(); try self.socket.set(.reuse_address, true); try self.socket.bind(address); try self.socket.listen(128); return self; } pub fn deinit(self: *Self) void { if (self.done.xchg(true, .SeqCst)) return; self.socket.deinit(); await self.frame catch {}; self.close(); self.cleanup_counter.wait(); self.purge(); } pub fn close(self: *Self) void { var pool: [opts.max_connections_per_server]*Connection = undefined; var pool_len: usize = 0; { const held = self.lock.acquire(); defer held.release(); pool = self.pool; pool_len = self.pool_len; self.pool = undefined; self.pool_len = 0; } for (pool[0..pool_len]) |conn| { conn.socket.deinit(); if (comptime meta.trait.hasFn("close")(meta.Child(Protocol))) { self.protocol.close(.server, &conn.socket); } } } pub fn purge(self: *Self) void { const held = self.lock.acquire(); defer held.release(); while (self.cleanup_queue) |head| { await head.ptr.frame catch {}; self.cleanup_queue = head.next; if (comptime meta.trait.hasFn("purge")(meta.Child(Protocol))) { var items: [opts.write_queue_size]opts.message_type = undefined; const queue = &head.ptr.socket.write_queue; const remaining = queue.tail -% queue.head; var i: usize = 0; while (i < remaining) : (i += 1) { items[i] = queue.items[(queue.head + i) % queue.items.len]; } queue.head = queue.tail; self.protocol.purge(.server, &head.ptr.socket, items[0..remaining]); } self.allocator.destroy(head.ptr); } } fn cleanup(self: *Self, node: *Node) void { const held = self.lock.acquire(); defer held.release(); node.next = self.cleanup_queue; self.cleanup_queue = node; } pub fn serve(self: *Self) !void { try self.socket.registerTo(self.notifier); self.frame = async self.run(); } fn run(self: *Self) !void { yield(); defer if (!self.done.xchg(true, .SeqCst)) { self.socket.deinit(); self.close(); }; while (true) { self.accept() catch |err| switch (err) { error.SocketNotListening, error.OperationCancelled, => return, else => { continue; }, }; self.purge(); } } fn accept(self: *Self) !void { self.cleanup_counter.add(1); errdefer self.cleanup_counter.add(-1); const conn = try self.allocator.create(Connection); errdefer self.allocator.destroy(conn); conn.node = .{ .ptr = conn }; const peer = try self.socket.accept(); conn.socket = ServerSocket.init(peer.socket, peer.address); errdefer conn.socket.deinit(); try conn.socket.unwrap().registerTo(self.notifier); { const held = self.lock.acquire(); defer held.release(); if (self.pool_len + 1 == opts.max_connections_per_server) { return error.MaxConnectionLimitExceeded; } self.pool[self.pool_len] = conn; self.pool_len += 1; } conn.frame = async self.runConnection(conn); } fn deleteConnection(self: *Self, conn: *Connection) bool { const held = self.lock.acquire(); defer held.release(); var pool = self.pool[0..self.pool_len]; if (mem.indexOfScalar(*Connection, pool, conn)) |i| { mem.copy(*Connection, pool[i..], pool[i + 1 ..]); self.pool_len -= 1; return true; } return false; } fn runConnection(self: *Self, conn: *Connection) !void { defer { if (self.deleteConnection(conn)) { conn.socket.deinit(); if (comptime meta.trait.hasFn("close")(meta.Child(Protocol))) { self.protocol.close(.server, &conn.socket); } } self.cleanup(&conn.node); self.cleanup_counter.add(-1); } yield(); if (comptime meta.trait.hasFn("handshake")(meta.Child(Protocol))) { conn.socket.context = try self.protocol.handshake(.server, &conn.socket.inner); } try conn.socket.run(self.protocol); } }; }
0
repos
repos/snow/zig.mod
name: snow main: snow.zig dependencies: - type: git path: https://github.com/lithdew/pike.git
0
repos
repos/snow/io.zig
const std = @import("std"); const mem = std.mem; pub fn Reader(comptime Socket: type, comptime buffer_size: usize) type { return struct { const Self = @This(); socket: *Socket, buf: [buffer_size]u8 = undefined, pos: usize = 0, pub inline fn init(socket: *Socket) Self { return Self{ .socket = socket }; } pub inline fn reset(self: *Self) void { self.pos = 0; } pub inline fn readUntil(self: *Self, delimiter: []const u8) ![]const u8 { while (true) { if (self.pos >= buffer_size) return error.BufferOverflow; const num_bytes = try self.socket.read(self.buf[self.pos..]); if (num_bytes == 0) return error.EndOfStream; self.pos += num_bytes; if (mem.indexOf(u8, self.buf[0..self.pos], delimiter)) |i| { return self.buf[0 .. i + 1]; } } } pub inline fn readLine(self: *Self) ![]const u8 { return self.readUntil("\n"); } pub inline fn peek(self: *Self, amount: usize) !void { if (self.pos >= amount) return; while (self.pos < amount) { const num_bytes = try self.socket.read(self.buf[self.pos..]); if (num_bytes == 0) return error.EndOfStream; self.pos += num_bytes; } } pub inline fn shift(self: *Self, amount: usize) void { mem.copy(u8, self.buf[0 .. self.pos - amount], self.buf[amount..self.pos]); self.pos -= amount; } }; } pub fn Writer(comptime Socket: type, comptime buffer_size: usize) type { return struct { const Self = @This(); socket: *Socket, buf: [buffer_size]u8 = undefined, pos: usize = 0, pub inline fn init(socket: *Socket) Self { return Self{ .socket = socket }; } pub inline fn write(self: *Self, buf: []const u8) !void { mem.copy(u8, try self.peek(buf.len), buf); } pub inline fn peek(self: *Self, size: usize) ![]u8 { if (size > buffer_size) return error.RequestedSizeToolarge; if (self.pos + size > buffer_size) try self.shift(buffer_size - size); defer self.pos += size; return self.buf[self.pos..][0..size]; } pub inline fn flush(self: *Self) !void { return self.shift(null); } pub inline fn shift(self: *Self, amount: ?usize) !void { const required_leftover_space = amount orelse 0; while (self.pos > required_leftover_space) { const num_bytes = try self.socket.write(self.buf[0..self.pos]); if (num_bytes == 0) return error.EndOfStream; self.pos -= num_bytes; } } }; }
0
repos
repos/snow/test.zig
const std = @import("std"); const snow = @import("snow.zig"); const sync = @import("sync.zig"); const pike = @import("pike"); const net = std.net; const mem = std.mem; const testing = std.testing; test "client / server" { const Protocol = struct { const Self = @This(); event: sync.Event = .{}, pub fn handshake(self: *Self, comptime side: snow.Side, socket: anytype) !void { return {}; } pub fn close(self: *Self, comptime side: snow.Side, socket: anytype) void { return {}; } pub fn purge(self: *Self, comptime side: snow.Side, socket: anytype, items: []const []const u8) void { return {}; } pub fn read(self: *Self, comptime side: snow.Side, socket: anytype, reader: anytype) !void { while (true) { const line = try reader.readLine(); defer reader.shift(line.len); self.event.notify(); } } pub fn write(self: *Self, comptime side: snow.Side, socket: anytype, writer: anytype, items: [][]const u8) !void { for (items) |message| { if (mem.indexOfScalar(u8, message, '\n') != null) { return error.UnexpectedDelimiter; } const frame = try writer.peek(message.len + 1); mem.copy(u8, frame[0..message.len], message); frame[message.len..][0] = '\n'; } try writer.flush(); } }; const opts: snow.Options = .{ .protocol_type = *Protocol }; const Test = struct { fn run(notifier: *const pike.Notifier, protocol: *Protocol, stopped: *bool) !void { defer stopped.* = true; var server = try snow.Server(opts).init( protocol, testing.allocator, notifier, net.Address.initIp4(.{ 0, 0, 0, 0 }, 0), ); defer server.deinit(); try server.serve(); var client = snow.Client(opts).init( protocol, testing.allocator, notifier, try server.socket.getBindAddress(), ); defer client.deinit(); inline for (.{ "A", "B", "C", "D" }) |message| { try client.write(message); protocol.event.wait(); } } }; const notifier = try pike.Notifier.init(); defer notifier.deinit(); var protocol: Protocol = .{}; var stopped = false; var frame = async Test.run(&notifier, &protocol, &stopped); while (!stopped) { try notifier.poll(10_000); } try nosuspend await frame; }
0
repos
repos/snow/sync.zig
const std = @import("std"); const pike = @import("pike"); const mem = std.mem; pub const Counter = struct { const Self = @This(); state: isize = 0, event: Event = .{}, pub fn add(self: *Self, delta: isize) void { var state = @atomicLoad(isize, &self.state, .Monotonic); var new_state: isize = undefined; while (true) { new_state = state + delta; state = @cmpxchgWeak( isize, &self.state, state, new_state, .Monotonic, .Monotonic, ) orelse break; } if (new_state == 0) { self.event.notify(); } } pub fn wait(self: *Self) void { while (@atomicLoad(isize, &self.state, .Monotonic) != 0) { self.event.wait(); } } }; pub fn Queue(comptime T: type, comptime capacity: comptime_int) type { return struct { const Self = @This(); const Reader = struct { task: pike.Task, dead: bool = false, }; const Writer = struct { next: ?*Writer = null, tail: ?*Writer = null, task: pike.Task, dead: bool = false, }; lock: std.Mutex = .{}, items: [capacity]T = undefined, dead: bool = false, head: usize = 0, tail: usize = 0, reader: ?*Reader = null, writers: ?*Writer = null, pub fn close(self: *Self) void { const held = self.lock.acquire(); if (self.dead) { held.release(); return; } self.dead = true; const maybe_reader = blk: { if (self.reader) |reader| { self.reader = null; break :blk reader; } break :blk null; }; var maybe_writers = blk: { if (self.writers) |writers| { self.writers = null; break :blk writers; } break :blk null; }; held.release(); if (maybe_reader) |reader| { reader.dead = true; pike.dispatch(&reader.task, .{}); } while (maybe_writers) |writer| { writer.dead = true; maybe_writers = writer.next; pike.dispatch(&writer.task, .{}); } } pub fn pending(self: *Self) usize { const held = self.lock.acquire(); defer held.release(); return self.tail -% self.head; } pub fn push(self: *Self, item: T) !void { while (true) { const held = self.lock.acquire(); if (self.dead) { held.release(); return error.AlreadyShutdown; } if (self.tail -% self.head < capacity) { self.items[self.tail % capacity] = item; self.tail +%= 1; const maybe_reader = blk: { if (self.reader) |reader| { self.reader = null; break :blk reader; } break :blk null; }; held.release(); if (maybe_reader) |reader| { pike.dispatch(&reader.task, .{}); } return; } var writer = Writer{ .task = pike.Task.init(@frame()) }; suspend { if (self.writers) |writers| { writers.tail.?.next = &writer; } else { self.writers = &writer; } self.writers.?.tail = &writer; held.release(); } if (writer.dead) return error.OperationCancelled; } } pub fn pop(self: *Self, dst: []T) !usize { while (true) { const held = self.lock.acquire(); const count = self.tail -% self.head; if (count != 0) { var i: usize = 0; while (i < count) : (i += 1) { dst[i] = self.items[(self.head +% i) % capacity]; } self.head = self.tail; var maybe_writers = blk: { if (self.writers) |writers| { self.writers = null; break :blk writers; } break :blk null; }; held.release(); while (maybe_writers) |writer| { maybe_writers = writer.next; pike.dispatch(&writer.task, .{}); } return count; } if (self.dead) { held.release(); return error.AlreadyShutdown; } var reader = Reader{ .task = pike.Task.init(@frame()) }; suspend { self.reader = &reader; held.release(); } if (reader.dead) return error.OperationCancelled; } } }; } // pub fn Queue(comptime T: type, comptime capacity: comptime_int) type { // return struct { // items: [capacity]T = undefined, // reader: Event = .{}, // writer: Event = .{}, // dead: bool = false, // head: usize = 0, // tail: usize = 0, // const Self = @This(); // pub fn pending(self: *const Self) usize { // const head = @atomicLoad(usize, &self.head, .Acquire); // return self.tail -% head; // } // pub fn push(self: *Self, item: T) !void { // while (true) { // if (@atomicLoad(bool, &self.dead, .Monotonic)) { // return error.OperationCancelled; // } // const head = @atomicLoad(usize, &self.head, .Acquire); // if (self.tail -% head < capacity) { // self.items[self.tail % capacity] = item; // @atomicStore(usize, &self.tail, self.tail +% 1, .Release); // self.reader.notify(); // return; // } // self.writer.wait(); // } // } // pub fn pop(self: *Self, dst: []T) !usize { // while (true) { // const tail = @atomicLoad(usize, &self.tail, .Acquire); // const popped = tail -% self.head; // if (popped != 0) { // var i: usize = 0; // while (i < popped) : (i += 1) { // dst[i] = self.items[(self.head +% i) % capacity]; // } // @atomicStore(usize, &self.head, tail, .Release); // self.writer.notify(); // return popped; // } // if (@atomicLoad(bool, &self.dead, .Monotonic)) { // return error.OperationCancelled; // } // self.reader.wait(); // } // } // pub fn close(self: *Self) void { // if (@atomicRmw(bool, &self.dead, .Xchg, true, .Monotonic)) { // return; // } // self.reader.notify(); // self.writer.notify(); // } // }; // } pub const Event = struct { state: ?*pike.Task = null, var notified: pike.Task = undefined; pub fn wait(self: *Event) void { var task = pike.Task.init(@frame()); suspend { var state = @atomicLoad(?*pike.Task, &self.state, .Monotonic); while (true) { const new_state = if (state == &notified) null else if (state == null) &task else unreachable; state = @cmpxchgWeak( ?*pike.Task, &self.state, state, new_state, .Release, .Monotonic, ) orelse { if (new_state == null) pike.dispatch(&task, .{}); break; }; } } } pub fn notify(self: *Event) void { var state = @atomicLoad(?*pike.Task, &self.state, .Monotonic); while (true) { if (state == &notified) return; const new_state = if (state == null) &notified else null; state = @cmpxchgWeak( ?*pike.Task, &self.state, state, new_state, .Acquire, .Monotonic, ) orelse { if (state) |task| pike.dispatch(task, .{}); break; }; } } }; /// Async-friendly Mutex ported from Zig's standard library to be compatible /// with scheduling methods exposed by pike. pub const Mutex = struct { mutex: std.Mutex = .{}, head: usize = UNLOCKED, const UNLOCKED = 0; const LOCKED = 1; const Waiter = struct { // forced Waiter alignment to ensure it doesn't clash with LOCKED next: ?*Waiter align(2), tail: *Waiter, task: pike.Task, }; pub fn initLocked() Mutex { return Mutex{ .head = LOCKED }; } pub fn acquire(self: *Mutex) Held { const held = self.mutex.acquire(); // self.head transitions from multiple stages depending on the value: // UNLOCKED -> LOCKED: // acquire Mutex ownership when theres no waiters // LOCKED -> <Waiter head ptr>: // Mutex is already owned, enqueue first Waiter // <head ptr> -> <head ptr>: // Mutex is owned with pending waiters. Push our waiter to the queue. if (self.head == UNLOCKED) { self.head = LOCKED; held.release(); return Held{ .lock = self }; } var waiter: Waiter = undefined; waiter.next = null; waiter.tail = &waiter; const head = switch (self.head) { UNLOCKED => unreachable, LOCKED => null, else => @intToPtr(*Waiter, self.head), }; if (head) |h| { h.tail.next = &waiter; h.tail = &waiter; } else { self.head = @ptrToInt(&waiter); } suspend { waiter.task = pike.Task.init(@frame()); held.release(); } return Held{ .lock = self }; } pub const Held = struct { lock: *Mutex, pub fn release(self: Held) void { const waiter = blk: { const held = self.lock.mutex.acquire(); defer held.release(); // self.head goes through the reverse transition from acquire(): // <head ptr> -> <new head ptr>: // pop a waiter from the queue to give Mutex ownership when theres still others pending // <head ptr> -> LOCKED: // pop the laster waiter from the queue, while also giving it lock ownership when awaken // LOCKED -> UNLOCKED: // last lock owner releases lock while no one else is waiting for it switch (self.lock.head) { UNLOCKED => unreachable, // Mutex unlocked while unlocking LOCKED => { self.lock.head = UNLOCKED; break :blk null; }, else => { const waiter = @intToPtr(*Waiter, self.lock.head); self.lock.head = if (waiter.next == null) LOCKED else @ptrToInt(waiter.next); if (waiter.next) |next| next.tail = waiter.tail; break :blk waiter; }, } }; if (waiter) |w| { pike.dispatch(&w.task, .{}); } } }; };
0
repos
repos/snow/README.md
# snow A small, fast, cross-platform, async Zig networking framework built on top of [lithdew/pike](https://github.com/lithdew/pike). It automatically handles: 1. buffering/framing data coming in and out of a socket, 2. managing the lifecycle of incoming / outgoing connections, and 3. representing a singular `Client` / `Server` as a bounded adaptive pool of outgoing / incoming connections. It also allows you to specify: 1. how messages are framed (`\n` suffixed to each message, message length prefixed to each message, etc.), 2. a sequence of steps to be performed before successfully establishing a connection (a handshake protocol), and 3. an upper bound to the maximum number of connections a `Client` / `Server` may pool in total. ## Usage In your `build.zig`: ```zig const std = @import("std"); const Builder = std.build.Builder; const pkgs = struct { const pike = std.build.Pkg{ .name = "pike", .path = "pike/pike.zig", }; const snow = std.build.Pkg{ .name = "snow", .path = "snow/snow.zig", .dependencies = &[_]std.build.Pkg{ pike, } }; }; pub fn build(b: *Builder) void { // Given a build step... step.addPackage(pkgs.pike); step.addPackage(pkgs.snow); } ``` ## Protocol Applications written with _snow_ provide a `Protocol` implementation which specifies how message are encoded / decoded into frames. Helpers (`io.Reader` / `io.Writer`) are provided to assist developers in specifying how frame encoding / decoding is to be performed. Given a `Protocol` implementation, a `Client` / `Server` may be instantiated. Here is an example of a `Protocol` that frames messages based on an End-of-Line character ('\n') suffixed at the end of each message: ```zig const std = @import("std"); const snow = @import("snow"); const mem = std.mem; const Protocol = struct { const Self = @This(); // This gets called right before a connection is marked to be successfully established! // // Unlike the rest of the callbacks below, 'socket' is a raw 'pike.Socket'. Feel free to // read / write as much data as you wish, or to return an error to prevent a connection // from being marked as being successfully established. // // Rather than 'void', snow.Options.context_type may be set and returned from 'handshake' // to bootstrap a connection with additional fields and methods under 'socket.context'. pub fn handshake(self: *Self, comptime side: snow.Side, socket: anytype) !void { return {}; } // This gets called before a connection is closed! pub fn close(self: *Self, comptime side: snow.Side, socket: anytype) void { return {}; } // This gets called when a connection's resources is ready to be de-allocated! // // A slice of remaining items in the socket's write queue is passed to purge() to be // optionally deallocated. pub fn purge(self: *Self, comptime side: snow.Side, socket: anytype, items: []const []const u8) void { return {}; } // This gets called when data is ready to be read from a connection! pub fn read(self: *Self, comptime side: snow.Side, socket: anytype, reader: anytype) !void { while (true) { const line = try reader.readLine(); defer reader.shift(line.len); // Do something with the frame here! } } // This gets called when data is queued and ready to be encoded and written to // a connection! // // Rather than '[]const u8', custom message types may be set to be queuable to the // connections write queue by setting snow.Options.message_type. pub fn write(self: *Self, comptime side: snow.Side, socket: anytype, writer: anytype, items: [][]const u8) !void { for (items) |message| { if (mem.indexOfScalar(u8, message, '\n') != null) { return error.UnexpectedDelimiter; } const frame = try writer.peek(message.len + 1); mem.copy(u8, frame[0..message.len], message); frame[message.len..][0] = '\n'; } try writer.flush(); } }; ``` ## Client A `Client` comprises of a bounded adaptive pool of outgoing connections that are to be connected to a single IPv4/IPv6 endpoint. When writing a message to an endpoint with a `Client`, a connection is initially grabbed from the pool. The message is then queued to be written to the connection's underlying socket. A policy is specified for selecting which connection to grab from a `Client`'s pool. The policy goes as follows: There exists a configurable maximum number of connections that may belong to a `Client`'s pool (defaulting to 16). If all existing connections in a `Client`'s pool contain queued messages that have yet to be flushed and written, a new connection is created and registered to the pool up to a maximum number of connections. If the pool's maximum number of connections limit is reached, the connection in the pool with the smallest number of queued messages is returned. Otherwise, a new connection is created and registered to the pool and returned. ## Server A `Server` comprises of a bounded adaptive pool of incoming connections accepted from a single bounded IPv4/IPv6 endpoint. There exists a configurable maximum number of connections that may belong to a `Server`'s pool (defaulting to 128). Should an incoming connection be established and the pool underlying a `Server` appears to be full, the connection will be declined and de-initialized. ## Socket All sockets comprise of two coroutines: a reader coroutine, and a writer coroutine. The reader and writer coroutine are responsible for framing and buffering messages received from / written to a single socket instance, and for executing logic specified under a `Protocol` implementation. An interesting detail to note is that the writer coroutine is entirely lock-free. ## Performance _snow_ was written with performance in mind: zero heap allocations occur in all hot paths. Heap allocations only ever occur when establishing a new incoming / outgoing connection. All other underlying components are stack-allocated and recycled as much as possible.
0
repos
repos/snow/socket.zig
const std = @import("std"); const pike = @import("pike"); const io = @import("io.zig"); const sync = @import("sync.zig"); const net = std.net; const meta = std.meta; pub const Side = packed enum(u1) { client, server, }; pub const Options = struct { max_connections_per_client: usize = 16, max_connections_per_server: usize = 128, protocol_type: type = void, message_type: type = []const u8, context_type: type = void, write_queue_size: usize = 128, read_buffer_size: usize = 4 * 1024 * 1024, write_buffer_size: usize = 4 * 1024 * 1024, }; pub fn yield() void { suspend { var task = pike.Task.init(@frame()); pike.dispatch(&task, .{ .use_lifo = true }); } } pub fn Socket(comptime side: Side, comptime opts: Options) type { return struct { const Self = @This(); pub const Reader = io.Reader(pike.Socket, opts.read_buffer_size); pub const Writer = io.Writer(pike.Socket, opts.write_buffer_size); const WriteQueue = sync.Queue(opts.message_type, opts.write_queue_size); const Protocol = opts.protocol_type; const Context = opts.context_type; inner: pike.Socket, address: net.Address, context: Context = undefined, write_queue: WriteQueue = .{}, pub fn init(inner: pike.Socket, address: net.Address) Self { return Self{ .inner = inner, .address = address }; } pub fn deinit(self: *Self) void { self.inner.deinit(); } pub inline fn unwrap(self: *Self) *pike.Socket { return &self.inner; } pub fn write(self: *Self, message: opts.message_type) !void { try self.write_queue.push(message); } pub fn run(self: *Self, protocol: Protocol) !void { var reader = Reader.init(self.unwrap()); var writer = async self.runWriter(protocol); defer { self.write_queue.close(); await writer catch {}; } yield(); try protocol.read(side, self, &reader); } fn runWriter(self: *Self, protocol: Protocol) !void { var writer = Writer.init(self.unwrap()); var queue: @TypeOf(self.write_queue.items) = undefined; while (true) { const num_items = try self.write_queue.pop(queue[0..]); try protocol.write(side, self, &writer, queue[0..num_items]); } } }; }
0
repos
repos/snow/build.zig
const std = @import("std"); const deps = @import("deps.zig"); pub fn build(b: *std.build.Builder) void { const mode = b.standardReleaseOptions(); const target = b.standardTargetOptions(.{}); const test_runner = b.addTest("test.zig"); test_runner.setBuildMode(mode); test_runner.setTarget(target); deps.addAllTo(test_runner); const test_step = b.step("test", "Runs the test suite."); test_step.dependOn(&test_runner.step); }
0
repos
repos/snow/client.zig
const std = @import("std"); const pike = @import("pike"); const sync = @import("sync.zig"); const os = std.os; const net = std.net; const mem = std.mem; const meta = std.meta; const testing = std.testing; usingnamespace @import("socket.zig"); pub fn Client(comptime opts: Options) type { return struct { const Self = @This(); const Node = struct { ptr: *Connection, next: ?*Node = null, }; const ClientSocket = Socket(.client, opts); const Protocol = opts.protocol_type; pub const Connection = struct { node: Node, socket: ClientSocket, frame: @Frame(Self.runConnection), }; protocol: Protocol, notifier: *const pike.Notifier, allocator: *mem.Allocator, address: net.Address, lock: sync.Mutex = .{}, done: bool = false, pool: [opts.max_connections_per_client]*Connection = undefined, pool_len: usize = 0, cleanup_counter: sync.Counter = .{}, cleanup_queue: ?*Node = null, pub fn init(protocol: Protocol, allocator: *mem.Allocator, notifier: *const pike.Notifier, address: net.Address) Self { return Self{ .protocol = protocol, .allocator = allocator, .notifier = notifier, .address = address }; } pub fn deinit(self: *Self) void { var pool: [opts.max_connections_per_client]*Connection = undefined; var pool_len: usize = 0; { const held = self.lock.acquire(); defer held.release(); if (self.done) { return; } else { self.done = true; } pool = self.pool; pool_len = self.pool_len; self.pool = undefined; self.pool_len = 0; } for (pool[0..pool_len]) |conn| { conn.socket.deinit(); if (comptime meta.trait.hasFn("close")(meta.Child(Protocol))) { self.protocol.close(.client, &conn.socket); } } self.cleanup_counter.wait(); self.purge(); } pub fn purge(self: *Self) void { const held = self.lock.acquire(); defer held.release(); while (self.cleanup_queue) |head| { await head.ptr.frame catch {}; self.cleanup_queue = head.next; if (comptime meta.trait.hasFn("purge")(meta.Child(Protocol))) { var items: [opts.write_queue_size]opts.message_type = undefined; const queue = &head.ptr.socket.write_queue; const remaining = queue.tail -% queue.head; var i: usize = 0; while (i < remaining) : (i += 1) { items[i] = queue.items[(queue.head + i) % queue.items.len]; } queue.head = queue.tail; self.protocol.purge(.client, &head.ptr.socket, items[0..remaining]); } self.allocator.destroy(head.ptr); } } fn cleanup(self: *Self, node: *Node) void { const held = self.lock.acquire(); defer held.release(); node.next = self.cleanup_queue; self.cleanup_queue = node; } pub fn bootstrap(self: *Self) !void { _ = try self.getConnection(); } pub fn write(self: *Self, message: opts.message_type) !void { const conn = try self.getConnection(); try conn.socket.write(message); } pub fn getConnection(self: *Self) !*Connection { defer self.purge(); const held = self.lock.acquire(); defer held.release(); if (self.done) return error.OperationCancelled; var pool = self.pool[0..self.pool_len]; if (pool.len == 0) return self.initConnection(); var min_conn = pool[0]; var min_pending = min_conn.socket.write_queue.pending(); if (min_pending == 0) return min_conn; for (pool[1..]) |conn| { const pending = conn.socket.write_queue.pending(); if (pending == 0) return conn; if (pending < min_pending) { min_conn = conn; min_pending = pending; } } if (pool.len < opts.max_connections_per_client) { return self.initConnection(); } return min_conn; } fn initConnection(self: *Self) !*Connection { const conn = try self.allocator.create(Connection); errdefer self.allocator.destroy(conn); conn.node = .{ .ptr = conn }; conn.socket = ClientSocket.init( try pike.Socket.init(os.AF_INET, os.SOCK_STREAM, os.IPPROTO_TCP, 0), self.address, ); errdefer conn.socket.deinit(); try conn.socket.unwrap().registerTo(self.notifier); try conn.socket.unwrap().connect(conn.socket.address); if (comptime meta.trait.hasFn("handshake")(meta.Child(Protocol))) { conn.socket.context = try self.protocol.handshake(.client, &conn.socket.inner); } self.pool[self.pool_len] = conn; self.pool_len += 1; conn.frame = async self.runConnection(conn); return conn; } fn deleteConnection(self: *Self, conn: *Connection) bool { const held = self.lock.acquire(); defer held.release(); var pool = self.pool[0..self.pool_len]; if (mem.indexOfScalar(*Connection, pool, conn)) |i| { mem.copy(*Connection, pool[i..], pool[i + 1 ..]); self.pool_len -= 1; return true; } return false; } fn runConnection(self: *Self, conn: *Connection) !void { self.cleanup_counter.add(1); defer { if (self.deleteConnection(conn)) { conn.socket.deinit(); if (comptime meta.trait.hasFn("close")(meta.Child(Protocol))) { self.protocol.close(.client, &conn.socket); } } self.cleanup(&conn.node); self.cleanup_counter.add(-1); } yield(); try conn.socket.run(self.protocol); } }; }
0
repos
repos/snow/snow.zig
pub const io = @import("io.zig"); pub const sync = @import("sync.zig"); pub usingnamespace @import("client.zig"); pub usingnamespace @import("server.zig"); pub usingnamespace @import("socket.zig");
0
repos
repos/clipboard/README.md
# clipboard [![reference Zig](https://img.shields.io/badge/zig%20-0.13.0-orange)](https://github.com/dgv/clipboard/blob/main/build.zig.zon) [![reference Zig](https://img.shields.io/badge/zigdoc%20-pages-orange)](https://github.com/dgv/clipboard/blob/main/docs/) [![reference Zig](https://img.shields.io/badge/deps%20-0-green)](https://github.com/dgv/clipboard/blob/main/build.zig.zon) [![build](https://github.com/dgv/clipboard/actions/workflows/build.yml/badge.svg)](https://github.com/dgv/clipboard/actions/workflows/build.yml) [![License: MIT](https://img.shields.io/badge/license-MIT-yellow.svg)](https://opensource.org/licenses/MIT) Provide copying and pasting text (UTF-8) to the clipboard for Zig. ### platform support - MacOS - Linux, Unix (requires 'xclip' or 'xsel' command to be installed) - Windows ### usage #### install ``` zig fetch --save https://github.com/dgv/clipboard/archive/refs/heads/main.zip ``` #### import (build.zig) ```zig ... exe.root_module.addImport("clipboard", b.dependency("clipboard", .{}).module("clipboard")); b.installArtifact(exe); ``` #### sample ```zig const clipboard = @import("clipboard"); const std = @import("std"); pub fn main() !void { try clipboard.write("Zig ⚡"); std.debug.print("{s}\n", .{clipboard.read() catch ""}); } ```
0
repos
repos/clipboard/build.zig.zon
.{ .name = "clipboard", .version = "0.0.0", .minimum_zig_version = "0.13.0", .paths = .{ "build.zig", "build.zig.zon", "src", }, }
0
repos
repos/clipboard/build.zig
const std = @import("std"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); _ = b.addModule("clipboard", .{ .root_source_file = b.path("src/clipboard.zig"), }); // const lib = b.addStaticLibrary(.{ // .name = "clipboard", // .root_source_file = b.path("src/clipboard.zig"), // .target = target, // .optimize = optimize, // }); // const docs = b.addInstallDirectory(.{ // .source_dir = lib.getEmittedDocs(), // .install_dir = .prefix, // .install_subdir = "../docs", // }); // b.getInstallStep().dependOn(&docs.step); // b.installArtifact(lib); const lib_unit_tests = b.addTest(.{ .root_source_file = b.path("src/clipboard.zig"), .target = target, .optimize = optimize, }); const test_step = b.step("test", "Run unit tests"); test_step.dependOn(&b.addRunArtifact(lib_unit_tests).step); }
0
repos/clipboard
repos/clipboard/src/clipboard.zig
/// Library clipboard read/write on clipboard const std = @import("std"); const builtin = @import("builtin"); const win = @import("clipboard_windows.zig"); const macos = @import("clipboard_macos.zig"); const unix = @import("clipboard_unix.zig"); const testing = std.testing; /// read string from clipboard pub fn read() ![]const u8 { switch (builtin.os.tag) { .windows => return try win.read(), .macos => return try macos.read(), .linux, .freebsd, .openbsd, .netbsd, .dragonfly => return try unix.read(), else => @compileError("platform not currently supported"), } } /// write string to clipboard pub fn write(text: []const u8) !void { switch (builtin.os.tag) { .windows => try win.write(text), .macos => try macos.write(text), .linux, .freebsd, .openbsd, .netbsd, .dragonfly => try unix.write(text), else => @compileError("platform not currently supported"), } } test "utf8 copy/paste" { const text = "zig zag ⚡"; try write(text); const r = try read(); try std.testing.expect(std.mem.eql(u8, r, text)); }
0
repos/clipboard
repos/clipboard/src/clipboard_windows.zig
const std = @import("std"); const windows = std.os.windows; const cf_unicode_text: windows.UINT = 13; const gmem_moveable: windows.UINT = 0x0002; pub extern "user32" fn OpenClipboard(hwnd: ?windows.HWND) callconv(windows.WINAPI) windows.BOOL; pub extern "user32" fn CloseClipboard() callconv(windows.WINAPI) windows.BOOL; pub extern "user32" fn EmptyClipboard() callconv(windows.WINAPI) windows.BOOL; pub extern "user32" fn IsClipboardFormatAvailable(format: windows.UINT) callconv(windows.WINAPI) windows.BOOL; pub extern "user32" fn GetClipboardData(format: windows.UINT) callconv(windows.WINAPI) ?windows.HANDLE; pub extern "user32" fn SetClipboardData(format: windows.UINT, handle: windows.HANDLE) callconv(windows.WINAPI) ?windows.HANDLE; pub extern "kernel32" fn GlobalLock(handle: windows.HANDLE) callconv(windows.WINAPI) ?*anyopaque; pub extern "kernel32" fn GlobalUnlock(handle: windows.HANDLE) callconv(windows.WINAPI) windows.BOOL; pub extern "kernel32" fn GlobalAlloc(flags: windows.UINT, size: windows.SIZE_T) callconv(windows.WINAPI) ?*anyopaque; pub extern "kernel32" fn GlobalFree(handle: windows.HANDLE) callconv(windows.WINAPI) windows.BOOL; pub extern "kernel32" fn RtlMoveMemory(out: *anyopaque, in: *anyopaque, size: windows.SIZE_T) callconv(windows.WINAPI) void; fn open_clipboard() !void { const success = OpenClipboard(null); if (success == 0) { return error.OpenClipboard; } } pub fn read() ![]u8 { if (IsClipboardFormatAvailable(cf_unicode_text) == 0) { return error.UnicodeFormatUnavailable; } try open_clipboard(); defer _ = CloseClipboard(); const h_data = GetClipboardData(cf_unicode_text) orelse return error.GetClipboardData; const raw_data = GlobalLock(h_data) orelse return error.GlobalLock; defer _ = GlobalUnlock(h_data); const w_data: [*c]const u16 = @alignCast(@ptrCast(raw_data)); const data = std.mem.span(w_data); const text = try std.unicode.utf16leToUtf8Alloc(std.heap.page_allocator, data); return std.mem.replaceOwned(u8, std.heap.page_allocator, text, "\r", "") catch ""; } pub fn write(text: []const u8) !void { try open_clipboard(); defer _ = CloseClipboard(); const success = EmptyClipboard(); if (success == 0) { return error.EmptyClipboard; } const text_utf16 = try std.unicode.utf8ToUtf16LeAllocZ(std.heap.page_allocator, text); const h_data = GlobalAlloc(gmem_moveable, text_utf16[0] * text_utf16.len) orelse return error.GlobalAlloc; const raw_data = GlobalLock(h_data) orelse return error.GlobalLock; defer _ = GlobalUnlock(h_data); const w_data: [*:0]u16 = @alignCast(@ptrCast(raw_data)); const s_data = std.mem.span(w_data); RtlMoveMemory(s_data.ptr, text_utf16.ptr, text_utf16[0] * text_utf16.len); _ = SetClipboardData(cf_unicode_text, h_data) orelse return error.SetClipboardData; }
0
repos/clipboard
repos/clipboard/src/clipboard_macos.zig
const std = @import("std"); const read_cmd = "pbpaste"; const write_cmd = "pbcopy"; pub fn read() ![]u8 { const result = try std.process.Child.run(.{ .allocator = std.heap.page_allocator, .argv = &[_][]const u8{ read_cmd, }, }); return result.stdout; } pub fn write(text: []const u8) !void { var proc = std.process.Child.init( &[_][]const u8{write_cmd}, std.heap.page_allocator, ); proc.stdin_behavior = .Pipe; proc.stdout_behavior = .Ignore; proc.stderr_behavior = .Ignore; try proc.spawn(); try proc.stdin.?.writeAll(text); proc.stdin.?.close(); proc.stdin = null; const term = proc.wait() catch unreachable; if (term != .Exited or term.Exited != 0) unreachable; }
0
repos/clipboard
repos/clipboard/src/clipboard_unix.zig
const std = @import("std"); const xsel: []const u8 = "xsel"; const xclip: []const u8 = "xclip"; const wlpaste: []const u8 = "wlpaste"; const wlcopy: []const u8 = "wlcopy"; const xsel_write = [_][]const u8{ xsel, "--input", "--clipboard" }; const xsel_read = [_][]const u8{ xsel, "--output", "--clipboard" }; const xclip_write = [_][]const u8{ xclip, "-in", "-selection", "clipboard" }; const xclip_read = [_][]const u8{ xclip, "-out", "-selection", "clipboard" }; const wlpaste_read = [_][]const u8{ wlpaste, "--no-newline" }; const wlcopy_write = [_][]const u8{wlcopy}; const op = enum { read, write, }; fn canExecutePosix(path: []const u8) bool { std.posix.access(path, std.posix.X_OK) catch return false; return true; } fn findProgramByNamePosix(name: []const u8, path: ?[]const u8, buf: []u8) ?[]const u8 { if (std.mem.indexOfScalar(u8, name, '/') != null) { @memcpy(buf[0..name.len], name); return buf[0..name.len]; } const path_env = path orelse return null; var fib = std.heap.FixedBufferAllocator.init(buf); var it = std.mem.tokenizeScalar(u8, path_env, std.fs.path.delimiter_posix); while (it.next()) |path_dir| { defer fib.reset(); const full_path = std.fs.path.join(fib.allocator(), &.{ path_dir, name }) catch continue; if (canExecutePosix(full_path)) return full_path; } return null; } fn getCmd(t: op) ![]const []const u8 { const pathenv = std.process.getEnvVarOwned(std.heap.page_allocator, "PATH") catch ""; const wd = std.process.getEnvVarOwned(std.heap.page_allocator, "WAYLAND_DISPLAY") catch ""; if (!std.mem.eql(u8, wd, "")) { return if (t == op.read) &wlpaste_read else &wlpaste_read; } var buf: [255]u8 = undefined; var p = findProgramByNamePosix(xclip, pathenv, &buf); if (p != null) { return if (t == op.read) &xclip_read else &xclip_write; } p = findProgramByNamePosix(xsel, pathenv, &buf); if (p != null) { return if (t == op.read) &xsel_read else &xsel_write; } return error.ClipboardCmdNotFound; } pub fn read() ![]u8 { const cmd = try getCmd(.read); const result = try std.process.Child.run(.{ .allocator = std.heap.page_allocator, .argv = cmd, }); return result.stdout; } pub fn write(text: []const u8) !void { const cmd = try getCmd(.write); var proc = std.process.Child.init( cmd, std.heap.page_allocator, ); proc.stdin_behavior = .Pipe; proc.stdout_behavior = .Ignore; proc.stderr_behavior = .Ignore; try proc.spawn(); try proc.stdin.?.writeAll(text); proc.stdin.?.close(); proc.stdin = null; const term = proc.wait() catch unreachable; if (term != .Exited or term.Exited != 0) unreachable; }
0
repos/clipboard
repos/clipboard/docs/main.js
(function() { const CAT_namespace = 0; const CAT_global_variable = 1; const CAT_function = 2; const CAT_primitive = 3; const CAT_error_set = 4; const CAT_global_const = 5; const CAT_alias = 6; const CAT_type = 7; const CAT_type_type = 8; const CAT_type_function = 9; const domDocTestsCode = document.getElementById("docTestsCode"); const domFnErrorsAnyError = document.getElementById("fnErrorsAnyError"); const domFnProto = document.getElementById("fnProto"); const domFnProtoCode = document.getElementById("fnProtoCode"); const domHdrName = document.getElementById("hdrName"); const domHelpModal = document.getElementById("helpDialog"); const domListErrSets = document.getElementById("listErrSets"); const domListFields = document.getElementById("listFields"); const domListParams = document.getElementById("listParams"); const domListFnErrors = document.getElementById("listFnErrors"); const domListFns = document.getElementById("listFns"); const domListGlobalVars = document.getElementById("listGlobalVars"); const domListInfo = document.getElementById("listInfo"); const domListNamespaces = document.getElementById("listNamespaces"); const domListNav = document.getElementById("listNav"); const domListSearchResults = document.getElementById("listSearchResults"); const domListTypes = document.getElementById("listTypes"); const domListValues = document.getElementById("listValues"); const domSearch = document.getElementById("search"); const domSectDocTests = document.getElementById("sectDocTests"); const domSectErrSets = document.getElementById("sectErrSets"); const domSectFields = document.getElementById("sectFields"); const domSectParams = document.getElementById("sectParams"); const domSectFnErrors = document.getElementById("sectFnErrors"); const domSectFns = document.getElementById("sectFns"); const domSectGlobalVars = document.getElementById("sectGlobalVars"); const domSectNamespaces = document.getElementById("sectNamespaces"); const domSectNav = document.getElementById("sectNav"); const domSectSearchNoResults = document.getElementById("sectSearchNoResults"); const domSectSearchResults = document.getElementById("sectSearchResults"); const domSectSource = document.getElementById("sectSource"); const domSectTypes = document.getElementById("sectTypes"); const domSectValues = document.getElementById("sectValues"); const domSourceText = document.getElementById("sourceText"); const domStatus = document.getElementById("status"); const domTableFnErrors = document.getElementById("tableFnErrors"); const domTldDocs = document.getElementById("tldDocs"); var searchTimer = null; const curNav = { // 0 = home // 1 = decl (decl) // 2 = source (path) tag: 0, // unsigned int: decl index decl: null, // string file name matching tarball path path: null, // when this is populated, pressing the "view source" command will // navigate to this hash. viewSourceHash: null, }; var curNavSearch = ""; var curSearchIndex = -1; var imFeelingLucky = false; // names of modules in the same order as wasm const moduleList = []; let wasm_promise = fetch("main.wasm"); let sources_promise = fetch("sources.tar").then(function(response) { if (!response.ok) throw new Error("unable to download sources"); return response.arrayBuffer(); }); var wasm_exports = null; const text_decoder = new TextDecoder(); const text_encoder = new TextEncoder(); WebAssembly.instantiateStreaming(wasm_promise, { js: { log: function(ptr, len) { const msg = decodeString(ptr, len); console.log(msg); }, panic: function (ptr, len) { const msg = decodeString(ptr, len); throw new Error("panic: " + msg); }, }, }).then(function(obj) { wasm_exports = obj.instance.exports; window.wasm = obj; // for debugging sources_promise.then(function(buffer) { const js_array = new Uint8Array(buffer); const ptr = wasm_exports.alloc(js_array.length); const wasm_array = new Uint8Array(wasm_exports.memory.buffer, ptr, js_array.length); wasm_array.set(js_array); wasm_exports.unpack(ptr, js_array.length); updateModuleList(); window.addEventListener('popstate', onPopState, false); domSearch.addEventListener('keydown', onSearchKeyDown, false); domSearch.addEventListener('input', onSearchChange, false); window.addEventListener('keydown', onWindowKeyDown, false); onHashChange(null); }); }); function renderTitle() { const suffix = " - Zig Documentation"; if (curNavSearch.length > 0) { document.title = curNavSearch + " - Search" + suffix; } else if (curNav.decl != null) { document.title = fullyQualifiedName(curNav.decl) + suffix; } else if (curNav.path != null) { document.title = curNav.path + suffix; } else { document.title = moduleList[0] + suffix; // Home } } function render() { domFnErrorsAnyError.classList.add("hidden"); domFnProto.classList.add("hidden"); domHdrName.classList.add("hidden"); domHelpModal.classList.add("hidden"); domSectErrSets.classList.add("hidden"); domSectDocTests.classList.add("hidden"); domSectFields.classList.add("hidden"); domSectParams.classList.add("hidden"); domSectFnErrors.classList.add("hidden"); domSectFns.classList.add("hidden"); domSectGlobalVars.classList.add("hidden"); domSectNamespaces.classList.add("hidden"); domSectNav.classList.add("hidden"); domSectSearchNoResults.classList.add("hidden"); domSectSearchResults.classList.add("hidden"); domSectSource.classList.add("hidden"); domSectTypes.classList.add("hidden"); domSectValues.classList.add("hidden"); domStatus.classList.add("hidden"); domTableFnErrors.classList.add("hidden"); domTldDocs.classList.add("hidden"); renderTitle(); if (curNavSearch !== "") return renderSearch(); switch (curNav.tag) { case 0: return renderHome(); case 1: if (curNav.decl == null) { return renderNotFound(); } else { return renderDecl(curNav.decl); } case 2: return renderSource(curNav.path); default: throw new Error("invalid navigation state"); } } function renderHome() { if (moduleList.length == 0) { domStatus.textContent = "sources.tar contains no modules"; domStatus.classList.remove("hidden"); return; } return renderModule(0); } function renderModule(pkg_index) { const root_decl = wasm_exports.find_module_root(pkg_index); return renderDecl(root_decl); } function renderDecl(decl_index) { const category = wasm_exports.categorize_decl(decl_index, 0); switch (category) { case CAT_namespace: return renderNamespacePage(decl_index); case CAT_global_variable: case CAT_primitive: case CAT_global_const: case CAT_type: case CAT_type_type: return renderGlobal(decl_index); case CAT_function: return renderFunction(decl_index); case CAT_type_function: return renderTypeFunction(decl_index); case CAT_error_set: return renderErrorSetPage(decl_index); case CAT_alias: return renderDecl(wasm_exports.get_aliasee()); default: throw new Error("unrecognized category " + category); } } function renderSource(path) { const decl_index = findFileRoot(path); if (decl_index == null) return renderNotFound(); renderNavFancy(decl_index, [{ name: "[src]", href: location.hash, }]); domSourceText.innerHTML = declSourceHtml(decl_index); domSectSource.classList.remove("hidden"); } function renderDeclHeading(decl_index) { curNav.viewSourceHash = "#src/" + unwrapString(wasm_exports.decl_file_path(decl_index)); const hdrNameSpan = domHdrName.children[0]; const srcLink = domHdrName.children[1]; hdrNameSpan.innerText = unwrapString(wasm_exports.decl_category_name(decl_index)); srcLink.setAttribute('href', curNav.viewSourceHash); domHdrName.classList.remove("hidden"); renderTopLevelDocs(decl_index); } function renderTopLevelDocs(decl_index) { const tld_docs_html = unwrapString(wasm_exports.decl_docs_html(decl_index, false)); if (tld_docs_html.length > 0) { domTldDocs.innerHTML = tld_docs_html; domTldDocs.classList.remove("hidden"); } } function renderNav(cur_nav_decl, list) { return renderNavFancy(cur_nav_decl, []); } function renderNavFancy(cur_nav_decl, list) { { // First, walk backwards the decl parents within a file. let decl_it = cur_nav_decl; let prev_decl_it = null; while (decl_it != null) { list.push({ name: declIndexName(decl_it), href: navLinkDeclIndex(decl_it), }); prev_decl_it = decl_it; decl_it = declParent(decl_it); } // Next, walk backwards the file path segments. if (prev_decl_it != null) { const file_path = fullyQualifiedName(prev_decl_it); const parts = file_path.split("."); parts.pop(); // skip last for (;;) { const href = navLinkFqn(parts.join(".")); const part = parts.pop(); if (!part) break; list.push({ name: part, href: href, }); } } list.reverse(); } resizeDomList(domListNav, list.length, '<li><a href="#"></a></li>'); for (let i = 0; i < list.length; i += 1) { const liDom = domListNav.children[i]; const aDom = liDom.children[0]; aDom.textContent = list[i].name; aDom.setAttribute('href', list[i].href); if (i + 1 == list.length) { aDom.classList.add("active"); } else { aDom.classList.remove("active"); } } domSectNav.classList.remove("hidden"); } function renderNotFound() { domStatus.textContent = "Declaration not found."; domStatus.classList.remove("hidden"); } function navLinkFqn(full_name) { return '#' + full_name; } function navLinkDeclIndex(decl_index) { return navLinkFqn(fullyQualifiedName(decl_index)); } function resizeDomList(listDom, desiredLen, templateHtml) { // add the missing dom entries var i, ev; for (i = listDom.childElementCount; i < desiredLen; i += 1) { listDom.insertAdjacentHTML('beforeend', templateHtml); } // remove extra dom entries while (desiredLen < listDom.childElementCount) { listDom.removeChild(listDom.lastChild); } } function renderErrorSetPage(decl_index) { renderNav(decl_index); renderDeclHeading(decl_index); const errorSetList = declErrorSet(decl_index).slice(); renderErrorSet(decl_index, errorSetList); } function renderErrorSet(base_decl, errorSetList) { if (errorSetList == null) { domFnErrorsAnyError.classList.remove("hidden"); } else { resizeDomList(domListFnErrors, errorSetList.length, '<div></div>'); for (let i = 0; i < errorSetList.length; i += 1) { const divDom = domListFnErrors.children[i]; const html = unwrapString(wasm_exports.error_html(base_decl, errorSetList[i])); divDom.innerHTML = html; } domTableFnErrors.classList.remove("hidden"); } domSectFnErrors.classList.remove("hidden"); } function renderParams(decl_index) { // Prevent params from being emptied next time wasm calls memory.grow. const params = declParams(decl_index).slice(); if (params.length !== 0) { resizeDomList(domListParams, params.length, '<div></div>'); for (let i = 0; i < params.length; i += 1) { const divDom = domListParams.children[i]; divDom.innerHTML = unwrapString(wasm_exports.decl_param_html(decl_index, params[i])); } domSectParams.classList.remove("hidden"); } } function renderTypeFunction(decl_index) { renderNav(decl_index); renderDeclHeading(decl_index); renderTopLevelDocs(decl_index); renderParams(decl_index); renderDocTests(decl_index); const members = unwrapSlice32(wasm_exports.type_fn_members(decl_index, false)).slice(); const fields = unwrapSlice32(wasm_exports.type_fn_fields(decl_index)).slice(); if (members.length !== 0 || fields.length !== 0) { renderNamespace(decl_index, members, fields); } else { domSourceText.innerHTML = declSourceHtml(decl_index); domSectSource.classList.remove("hidden"); } } function renderDocTests(decl_index) { const doctest_html = declDoctestHtml(decl_index); if (doctest_html.length > 0) { domDocTestsCode.innerHTML = doctest_html; domSectDocTests.classList.remove("hidden"); } } function renderFunction(decl_index) { renderNav(decl_index); renderDeclHeading(decl_index); renderTopLevelDocs(decl_index); renderParams(decl_index); renderDocTests(decl_index); domFnProtoCode.innerHTML = fnProtoHtml(decl_index, false); domFnProto.classList.remove("hidden"); const errorSetNode = fnErrorSet(decl_index); if (errorSetNode != null) { const base_decl = wasm_exports.fn_error_set_decl(decl_index, errorSetNode); renderErrorSet(base_decl, errorSetNodeList(decl_index, errorSetNode)); } domSourceText.innerHTML = declSourceHtml(decl_index); domSectSource.classList.remove("hidden"); } function renderGlobal(decl_index) { renderNav(decl_index); renderDeclHeading(decl_index); const docs_html = declDocsHtmlShort(decl_index); if (docs_html.length > 0) { domTldDocs.innerHTML = docs_html; domTldDocs.classList.remove("hidden"); } domSourceText.innerHTML = declSourceHtml(decl_index); domSectSource.classList.remove("hidden"); } function renderNamespace(base_decl, members, fields) { const typesList = []; const namespacesList = []; const errSetsList = []; const fnsList = []; const varsList = []; const valsList = []; member_loop: for (let i = 0; i < members.length; i += 1) { let member = members[i]; const original = member; while (true) { const member_category = wasm_exports.categorize_decl(member, 0); switch (member_category) { case CAT_namespace: if (wasm_exports.decl_field_count(member) > 0) { typesList.push({original: original, member: member}); } else { namespacesList.push({original: original, member: member}); } continue member_loop; case CAT_namespace: namespacesList.push({original: original, member: member}); continue member_loop; case CAT_global_variable: varsList.push(member); continue member_loop; case CAT_function: fnsList.push(member); continue member_loop; case CAT_type: case CAT_type_type: case CAT_type_function: typesList.push({original: original, member: member}); continue member_loop; case CAT_error_set: errSetsList.push({original: original, member: member}); continue member_loop; case CAT_global_const: case CAT_primitive: valsList.push({original: original, member: member}); continue member_loop; case CAT_alias: member = wasm_exports.get_aliasee(); continue; default: throw new Error("uknown category: " + member_category); } } } typesList.sort(byDeclIndexName2); namespacesList.sort(byDeclIndexName2); errSetsList.sort(byDeclIndexName2); fnsList.sort(byDeclIndexName); varsList.sort(byDeclIndexName); valsList.sort(byDeclIndexName2); if (typesList.length !== 0) { resizeDomList(domListTypes, typesList.length, '<li><a href="#"></a></li>'); for (let i = 0; i < typesList.length; i += 1) { const liDom = domListTypes.children[i]; const aDom = liDom.children[0]; const original_decl = typesList[i].original; const decl = typesList[i].member; aDom.textContent = declIndexName(original_decl); aDom.setAttribute('href', navLinkDeclIndex(decl)); } domSectTypes.classList.remove("hidden"); } if (namespacesList.length !== 0) { resizeDomList(domListNamespaces, namespacesList.length, '<li><a href="#"></a></li>'); for (let i = 0; i < namespacesList.length; i += 1) { const liDom = domListNamespaces.children[i]; const aDom = liDom.children[0]; const original_decl = namespacesList[i].original; const decl = namespacesList[i].member; aDom.textContent = declIndexName(original_decl); aDom.setAttribute('href', navLinkDeclIndex(decl)); } domSectNamespaces.classList.remove("hidden"); } if (errSetsList.length !== 0) { resizeDomList(domListErrSets, errSetsList.length, '<li><a href="#"></a></li>'); for (let i = 0; i < errSetsList.length; i += 1) { const liDom = domListErrSets.children[i]; const aDom = liDom.children[0]; const original_decl = errSetsList[i].original; const decl = errSetsList[i].member; aDom.textContent = declIndexName(original_decl); aDom.setAttribute('href', navLinkDeclIndex(decl)); } domSectErrSets.classList.remove("hidden"); } if (fnsList.length !== 0) { resizeDomList(domListFns, fnsList.length, '<div><dt><code></code></dt><dd></dd></div>'); for (let i = 0; i < fnsList.length; i += 1) { const decl = fnsList[i]; const divDom = domListFns.children[i]; const dtDom = divDom.children[0]; const ddDocs = divDom.children[1]; const protoCodeDom = dtDom.children[0]; protoCodeDom.innerHTML = fnProtoHtml(decl, true); ddDocs.innerHTML = declDocsHtmlShort(decl); } domSectFns.classList.remove("hidden"); } if (fields.length !== 0) { resizeDomList(domListFields, fields.length, '<div></div>'); for (let i = 0; i < fields.length; i += 1) { const divDom = domListFields.children[i]; divDom.innerHTML = unwrapString(wasm_exports.decl_field_html(base_decl, fields[i])); } domSectFields.classList.remove("hidden"); } if (varsList.length !== 0) { resizeDomList(domListGlobalVars, varsList.length, '<tr><td><a href="#"></a></td><td></td><td></td></tr>'); for (let i = 0; i < varsList.length; i += 1) { const decl = varsList[i]; const trDom = domListGlobalVars.children[i]; const tdName = trDom.children[0]; const tdNameA = tdName.children[0]; const tdType = trDom.children[1]; const tdDesc = trDom.children[2]; tdNameA.setAttribute('href', navLinkDeclIndex(decl)); tdNameA.textContent = declIndexName(decl); tdType.innerHTML = declTypeHtml(decl); tdDesc.innerHTML = declDocsHtmlShort(decl); } domSectGlobalVars.classList.remove("hidden"); } if (valsList.length !== 0) { resizeDomList(domListValues, valsList.length, '<tr><td><a href="#"></a></td><td></td><td></td></tr>'); for (let i = 0; i < valsList.length; i += 1) { const trDom = domListValues.children[i]; const tdName = trDom.children[0]; const tdNameA = tdName.children[0]; const tdType = trDom.children[1]; const tdDesc = trDom.children[2]; const original_decl = valsList[i].original; const decl = valsList[i].member; tdNameA.setAttribute('href', navLinkDeclIndex(decl)); tdNameA.textContent = declIndexName(original_decl); tdType.innerHTML = declTypeHtml(decl); tdDesc.innerHTML = declDocsHtmlShort(decl); } domSectValues.classList.remove("hidden"); } } function renderNamespacePage(decl_index) { renderNav(decl_index); renderDeclHeading(decl_index); const members = namespaceMembers(decl_index, false).slice(); const fields = declFields(decl_index).slice(); renderNamespace(decl_index, members, fields); } function operatorCompare(a, b) { if (a === b) { return 0; } else if (a < b) { return -1; } else { return 1; } } function updateCurNav(location_hash) { curNav.tag = 0; curNav.decl = null; curNav.path = null; curNav.viewSourceHash = null; curNavSearch = ""; if (location_hash.length > 1 && location_hash[0] === '#') { const query = location_hash.substring(1); const qpos = query.indexOf("?"); let nonSearchPart; if (qpos === -1) { nonSearchPart = query; } else { nonSearchPart = query.substring(0, qpos); curNavSearch = decodeURIComponent(query.substring(qpos + 1)); } if (nonSearchPart.length > 0) { const source_mode = nonSearchPart.startsWith("src/"); if (source_mode) { curNav.tag = 2; curNav.path = nonSearchPart.substring(4); } else { curNav.tag = 1; curNav.decl = findDecl(nonSearchPart); } } } } function onHashChange(state) { history.replaceState({}, ""); navigate(location.hash); if (state == null) window.scrollTo({top: 0}); } function onPopState(ev) { onHashChange(ev.state); } function navigate(location_hash) { updateCurNav(location_hash); if (domSearch.value !== curNavSearch) { domSearch.value = curNavSearch; } render(); if (imFeelingLucky) { imFeelingLucky = false; activateSelectedResult(); } } function activateSelectedResult() { if (domSectSearchResults.classList.contains("hidden")) { return; } var liDom = domListSearchResults.children[curSearchIndex]; if (liDom == null && domListSearchResults.children.length !== 0) { liDom = domListSearchResults.children[0]; } if (liDom != null) { var aDom = liDom.children[0]; location.href = aDom.getAttribute("href"); curSearchIndex = -1; } domSearch.blur(); } function onSearchKeyDown(ev) { switch (ev.code) { case "Enter": if (ev.shiftKey || ev.ctrlKey || ev.altKey) return; clearAsyncSearch(); imFeelingLucky = true; location.hash = computeSearchHash(); ev.preventDefault(); ev.stopPropagation(); return; case "Escape": if (ev.shiftKey || ev.ctrlKey || ev.altKey) return; domSearch.value = ""; domSearch.blur(); curSearchIndex = -1; ev.preventDefault(); ev.stopPropagation(); startSearch(); return; case "ArrowUp": if (ev.shiftKey || ev.ctrlKey || ev.altKey) return; moveSearchCursor(-1); ev.preventDefault(); ev.stopPropagation(); return; case "ArrowDown": if (ev.shiftKey || ev.ctrlKey || ev.altKey) return; moveSearchCursor(1); ev.preventDefault(); ev.stopPropagation(); return; default: ev.stopPropagation(); // prevent keyboard shortcuts return; } } function onSearchChange(ev) { curSearchIndex = -1; startAsyncSearch(); } function moveSearchCursor(dir) { if (curSearchIndex < 0 || curSearchIndex >= domListSearchResults.children.length) { if (dir > 0) { curSearchIndex = -1 + dir; } else if (dir < 0) { curSearchIndex = domListSearchResults.children.length + dir; } } else { curSearchIndex += dir; } if (curSearchIndex < 0) { curSearchIndex = 0; } if (curSearchIndex >= domListSearchResults.children.length) { curSearchIndex = domListSearchResults.children.length - 1; } renderSearchCursor(); } function onWindowKeyDown(ev) { switch (ev.code) { case "Escape": if (ev.shiftKey || ev.ctrlKey || ev.altKey) return; if (!domHelpModal.classList.contains("hidden")) { domHelpModal.classList.add("hidden"); ev.preventDefault(); ev.stopPropagation(); } break; case "KeyS": if (ev.shiftKey || ev.ctrlKey || ev.altKey) return; domSearch.focus(); domSearch.select(); ev.preventDefault(); ev.stopPropagation(); startAsyncSearch(); break; case "KeyU": if (ev.shiftKey || ev.ctrlKey || ev.altKey) return; ev.preventDefault(); ev.stopPropagation(); navigateToSource(); break; case "Slash": if (!ev.shiftKey || ev.ctrlKey || ev.altKey) return; ev.preventDefault(); ev.stopPropagation(); showHelpModal(); break; } } function showHelpModal() { domHelpModal.classList.remove("hidden"); domHelpModal.style.left = (window.innerWidth / 2 - domHelpModal.clientWidth / 2) + "px"; domHelpModal.style.top = (window.innerHeight / 2 - domHelpModal.clientHeight / 2) + "px"; domHelpModal.focus(); } function navigateToSource() { if (curNav.viewSourceHash != null) { location.hash = curNav.viewSourceHash; } } function clearAsyncSearch() { if (searchTimer != null) { clearTimeout(searchTimer); searchTimer = null; } } function startAsyncSearch() { clearAsyncSearch(); searchTimer = setTimeout(startSearch, 10); } function computeSearchHash() { // How location.hash works: // 1. http://example.com/ => "" // 2. http://example.com/# => "" // 3. http://example.com/#foo => "#foo" // wat const oldWatHash = location.hash; const oldHash = oldWatHash.startsWith("#") ? oldWatHash : "#" + oldWatHash; const parts = oldHash.split("?"); const newPart2 = (domSearch.value === "") ? "" : ("?" + domSearch.value); return parts[0] + newPart2; } function startSearch() { clearAsyncSearch(); navigate(computeSearchHash()); } function renderSearch() { renderNav(curNav.decl); const ignoreCase = (curNavSearch.toLowerCase() === curNavSearch); const results = executeQuery(curNavSearch, ignoreCase); if (results.length !== 0) { resizeDomList(domListSearchResults, results.length, '<li><a href="#"></a></li>'); for (let i = 0; i < results.length; i += 1) { const liDom = domListSearchResults.children[i]; const aDom = liDom.children[0]; const match = results[i]; const full_name = fullyQualifiedName(match); aDom.textContent = full_name; aDom.setAttribute('href', navLinkFqn(full_name)); } renderSearchCursor(); domSectSearchResults.classList.remove("hidden"); } else { domSectSearchNoResults.classList.remove("hidden"); } } function renderSearchCursor() { for (let i = 0; i < domListSearchResults.children.length; i += 1) { var liDom = domListSearchResults.children[i]; if (curSearchIndex === i) { liDom.classList.add("selected"); } else { liDom.classList.remove("selected"); } } } function updateModuleList() { moduleList.length = 0; for (let i = 0;; i += 1) { const name = unwrapString(wasm_exports.module_name(i)); if (name.length == 0) break; moduleList.push(name); } } function byDeclIndexName(a, b) { const a_name = declIndexName(a); const b_name = declIndexName(b); return operatorCompare(a_name, b_name); } function byDeclIndexName2(a, b) { const a_name = declIndexName(a.original); const b_name = declIndexName(b.original); return operatorCompare(a_name, b_name); } function decodeString(ptr, len) { if (len === 0) return ""; return text_decoder.decode(new Uint8Array(wasm_exports.memory.buffer, ptr, len)); } function unwrapString(bigint) { const ptr = Number(bigint & 0xffffffffn); const len = Number(bigint >> 32n); return decodeString(ptr, len); } function declTypeHtml(decl_index) { return unwrapString(wasm_exports.decl_type_html(decl_index)); } function declDocsHtmlShort(decl_index) { return unwrapString(wasm_exports.decl_docs_html(decl_index, true)); } function fullyQualifiedName(decl_index) { return unwrapString(wasm_exports.decl_fqn(decl_index)); } function declIndexName(decl_index) { return unwrapString(wasm_exports.decl_name(decl_index)); } function declSourceHtml(decl_index) { return unwrapString(wasm_exports.decl_source_html(decl_index)); } function declDoctestHtml(decl_index) { return unwrapString(wasm_exports.decl_doctest_html(decl_index)); } function fnProtoHtml(decl_index, linkify_fn_name) { return unwrapString(wasm_exports.decl_fn_proto_html(decl_index, linkify_fn_name)); } function setQueryString(s) { const jsArray = text_encoder.encode(s); const len = jsArray.length; const ptr = wasm_exports.query_begin(len); const wasmArray = new Uint8Array(wasm_exports.memory.buffer, ptr, len); wasmArray.set(jsArray); } function executeQuery(query_string, ignore_case) { setQueryString(query_string); const ptr = wasm_exports.query_exec(ignore_case); const head = new Uint32Array(wasm_exports.memory.buffer, ptr, 1); const len = head[0]; return new Uint32Array(wasm_exports.memory.buffer, ptr + 4, len); } function namespaceMembers(decl_index, include_private) { return unwrapSlice32(wasm_exports.namespace_members(decl_index, include_private)); } function declFields(decl_index) { return unwrapSlice32(wasm_exports.decl_fields(decl_index)); } function declParams(decl_index) { return unwrapSlice32(wasm_exports.decl_params(decl_index)); } function declErrorSet(decl_index) { return unwrapSlice64(wasm_exports.decl_error_set(decl_index)); } function errorSetNodeList(base_decl, err_set_node) { return unwrapSlice64(wasm_exports.error_set_node_list(base_decl, err_set_node)); } function unwrapSlice32(bigint) { const ptr = Number(bigint & 0xffffffffn); const len = Number(bigint >> 32n); if (len === 0) return []; return new Uint32Array(wasm_exports.memory.buffer, ptr, len); } function unwrapSlice64(bigint) { const ptr = Number(bigint & 0xffffffffn); const len = Number(bigint >> 32n); if (len === 0) return []; return new BigUint64Array(wasm_exports.memory.buffer, ptr, len); } function findDecl(fqn) { setInputString(fqn); const result = wasm_exports.find_decl(); if (result === -1) return null; return result; } function findFileRoot(path) { setInputString(path); const result = wasm_exports.find_file_root(); if (result === -1) return null; return result; } function declParent(decl_index) { const result = wasm_exports.decl_parent(decl_index); if (result === -1) return null; return result; } function fnErrorSet(decl_index) { const result = wasm_exports.fn_error_set(decl_index); if (result === 0) return null; return result; } function setInputString(s) { const jsArray = text_encoder.encode(s); const len = jsArray.length; const ptr = wasm_exports.set_input_string(len); const wasmArray = new Uint8Array(wasm_exports.memory.buffer, ptr, len); wasmArray.set(jsArray); } })();
0
repos/clipboard
repos/clipboard/docs/index.html
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Zig Documentation</title> <link rel="icon" href="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxNTMgMTQwIj48ZyBmaWxsPSIjRjdBNDFEIj48Zz48cG9seWdvbiBwb2ludHM9IjQ2LDIyIDI4LDQ0IDE5LDMwIi8+PHBvbHlnb24gcG9pbnRzPSI0NiwyMiAzMywzMyAyOCw0NCAyMiw0NCAyMiw5NSAzMSw5NSAyMCwxMDAgMTIsMTE3IDAsMTE3IDAsMjIiIHNoYXBlLXJlbmRlcmluZz0iY3Jpc3BFZGdlcyIvPjxwb2x5Z29uIHBvaW50cz0iMzEsOTUgMTIsMTE3IDQsMTA2Ii8+PC9nPjxnPjxwb2x5Z29uIHBvaW50cz0iNTYsMjIgNjIsMzYgMzcsNDQiLz48cG9seWdvbiBwb2ludHM9IjU2LDIyIDExMSwyMiAxMTEsNDQgMzcsNDQgNTYsMzIiIHNoYXBlLXJlbmRlcmluZz0iY3Jpc3BFZGdlcyIvPjxwb2x5Z29uIHBvaW50cz0iMTE2LDk1IDk3LDExNyA5MCwxMDQiLz48cG9seWdvbiBwb2ludHM9IjExNiw5NSAxMDAsMTA0IDk3LDExNyA0MiwxMTcgNDIsOTUiIHNoYXBlLXJlbmRlcmluZz0iY3Jpc3BFZGdlcyIvPjxwb2x5Z29uIHBvaW50cz0iMTUwLDAgNTIsMTE3IDMsMTQwIDEwMSwyMiIvPjwvZz48Zz48cG9seWdvbiBwb2ludHM9IjE0MSwyMiAxNDAsNDAgMTIyLDQ1Ii8+PHBvbHlnb24gcG9pbnRzPSIxNTMsMjIgMTUzLDExNyAxMDYsMTE3IDEyMCwxMDUgMTI1LDk1IDEzMSw5NSAxMzEsNDUgMTIyLDQ1IDEzMiwzNiAxNDEsMjIiIHNoYXBlLXJlbmRlcmluZz0iY3Jpc3BFZGdlcyIvPjxwb2x5Z29uIHBvaW50cz0iMTI1LDk1IDEzMCwxMTAgMTA2LDExNyIvPjwvZz48L2c+PC9zdmc+"> <style type="text/css"> body { font-family: system-ui, -apple-system, Roboto, "Segoe UI", sans-serif; color: #000000; } .hidden { display: none; } table { width: 100%; } a { color: #2A6286; } pre{ font-family:"Source Code Pro",monospace; font-size:1em; background-color:#F5F5F5; padding: 1em; margin: 0; overflow-x: auto; } code { font-family:"Source Code Pro",monospace; font-size: 0.9em; } code a { color: #000000; } #listFields > div, #listParams > div { margin-bottom: 1em; } #hdrName a { font-size: 0.7em; padding-left: 1em; } .fieldDocs { border: 1px solid #F5F5F5; border-top: 0px; padding: 1px 1em; } #logo { width: 8em; padding: 0.5em 1em; } #navWrap { width: -moz-available; width: -webkit-fill-available; width: stretch; margin-left: 11em; } #search { width: 100%; } nav { width: 10em; float: left; } nav h2 { font-size: 1.2em; text-decoration: underline; margin: 0; padding: 0.5em 0; text-align: center; } nav p { margin: 0; padding: 0; text-align: center; } section { clear: both; padding-top: 1em; } section h1 { border-bottom: 1px dashed; margin: 0 0; } section h2 { font-size: 1.3em; margin: 0.5em 0; padding: 0; border-bottom: 1px solid; } #listNav { list-style-type: none; margin: 0.5em 0 0 0; padding: 0; overflow: hidden; background-color: #f1f1f1; } #listNav li { float:left; } #listNav li a { display: block; color: #000; text-align: center; padding: .5em .8em; text-decoration: none; } #listNav li a:hover { background-color: #555; color: #fff; } #listNav li a.active { background-color: #FFBB4D; color: #000; } #helpDialog { width: 21em; height: 21em; position: fixed; top: 0; left: 0; background-color: #333; color: #fff; border: 1px solid #fff; } #helpDialog h1 { text-align: center; font-size: 1.5em; } #helpDialog dt, #helpDialog dd { display: inline; margin: 0 0.2em; } kbd { color: #000; background-color: #fafbfc; border-color: #d1d5da; border-bottom-color: #c6cbd1; box-shadow-color: #c6cbd1; display: inline-block; padding: 0.3em 0.2em; font: 1.2em monospace; line-height: 0.8em; vertical-align: middle; border: solid 1px; border-radius: 3px; box-shadow: inset 0 -1px 0; cursor: default; } #listSearchResults li.selected { background-color: #93e196; } #tableFnErrors dt { font-weight: bold; } dl > div { padding: 0.5em; border: 1px solid #c0c0c0; margin-top: 0.5em; } td { vertical-align: top; margin: 0; padding: 0.5em; max-width: 20em; text-overflow: ellipsis; overflow-x: hidden; } ul.columns { column-width: 20em; } .tok-kw { color: #333; font-weight: bold; } .tok-str { color: #d14; } .tok-builtin { color: #0086b3; } .tok-comment { color: #777; font-style: italic; } .tok-fn { color: #900; font-weight: bold; } .tok-null { color: #008080; } .tok-number { color: #008080; } .tok-type { color: #458; font-weight: bold; } @media (prefers-color-scheme: dark) { body { background-color: #111; color: #bbb; } pre { background-color: #222; color: #ccc; } a { color: #88f; } code a { color: #ccc; } .fieldDocs { border-color:#2A2A2A; } #listNav { background-color: #333; } #listNav li a { color: #fff; } #listNav li a:hover { background-color: #555; color: #fff; } #listNav li a.active { background-color: #FFBB4D; color: #000; } #listSearchResults li.selected { background-color: #000; } #listSearchResults li.selected a { color: #fff; } dl > div { border-color: #373737; } .tok-kw { color: #eee; } .tok-str { color: #2e5; } .tok-builtin { color: #ff894c; } .tok-comment { color: #aa7; } .tok-fn { color: #B1A0F8; } .tok-null { color: #ff8080; } .tok-number { color: #ff8080; } .tok-type { color: #68f; } } </style> </head> <body> <nav> <a class="logo" href="#"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 140"> <g fill="#F7A41D"> <g> <polygon points="46,22 28,44 19,30"/> <polygon points="46,22 33,33 28,44 22,44 22,95 31,95 20,100 12,117 0,117 0,22" shape-rendering="crispEdges"/> <polygon points="31,95 12,117 4,106"/> </g> <g> <polygon points="56,22 62,36 37,44"/> <polygon points="56,22 111,22 111,44 37,44 56,32" shape-rendering="crispEdges"/> <polygon points="116,95 97,117 90,104"/> <polygon points="116,95 100,104 97,117 42,117 42,95" shape-rendering="crispEdges"/> <polygon points="150,0 52,117 3,140 101,22"/> </g> <g> <polygon points="141,22 140,40 122,45"/> <polygon points="153,22 153,117 106,117 120,105 125,95 131,95 131,45 122,45 132,36 141,22" shape-rendering="crispEdges"/> <polygon points="125,95 130,110 106,117"/> </g> </g> <style> #text { fill: #121212 } @media (prefers-color-scheme: dark) { #text { fill: #f2f2f2 } } </style> <g id="text"> <g> <polygon points="260,22 260,37 229,40 177,40 177,22" shape-rendering="crispEdges"/> <polygon points="260,37 207,99 207,103 176,103 229,40 229,37"/> <polygon points="261,99 261,117 176,117 176,103 206,99" shape-rendering="crispEdges"/> </g> <rect x="272" y="22" shape-rendering="crispEdges" width="22" height="95"/> <g> <polygon points="394,67 394,106 376,106 376,81 360,70 346,67" shape-rendering="crispEdges"/> <polygon points="360,68 376,81 346,67"/> <path d="M394,106c-10.2,7.3-24,12-37.7,12c-29,0-51.1-20.8-51.1-48.3c0-27.3,22.5-48.1,52-48.1 c14.3,0,29.2,5.5,38.9,14l-13,15c-7.1-6.3-16.8-10-25.9-10c-17,0-30.2,12.9-30.2,29.5c0,16.8,13.3,29.6,30.3,29.6 c5.7,0,12.8-2.3,19-5.5L394,106z"/> </g> </g> </svg> </a> </nav> <div id="navWrap"> <input type="search" id="search" autocomplete="off" spellcheck="false" placeholder="`s` to search, `?` to see more options"> <div id="sectNav" class="hidden"><ul id="listNav"></ul></div> </div> <section> <p id="status">Loading...</p> <h1 id="hdrName" class="hidden"><span></span><a href="#">[src]</a></h1> <div id="fnProto" class="hidden"> <pre><code id="fnProtoCode"></code></pre> </div> <div id="tldDocs" class="hidden"></div> <div id="sectParams" class="hidden"> <h2>Parameters</h2> <div id="listParams"> </div> </div> <div id="sectFnErrors" class="hidden"> <h2>Errors</h2> <div id="fnErrorsAnyError"> <p><span class="tok-type">anyerror</span> means the error set is known only at runtime.</p> </div> <div id="tableFnErrors"><dl id="listFnErrors"></dl></div> </div> <div id="sectSearchResults" class="hidden"> <h2>Search Results</h2> <ul id="listSearchResults"></ul> </div> <div id="sectSearchNoResults" class="hidden"> <h2>No Results Found</h2> <p>Press escape to exit search and then '?' to see more options.</p> </div> <div id="sectFields" class="hidden"> <h2>Fields</h2> <div id="listFields"> </div> </div> <div id="sectTypes" class="hidden"> <h2>Types</h2> <ul id="listTypes" class="columns"> </ul> </div> <div id="sectNamespaces" class="hidden"> <h2>Namespaces</h2> <ul id="listNamespaces" class="columns"> </ul> </div> <div id="sectGlobalVars" class="hidden"> <h2>Global Variables</h2> <table> <tbody id="listGlobalVars"> </tbody> </table> </div> <div id="sectValues" class="hidden"> <h2>Values</h2> <table> <tbody id="listValues"> </tbody> </table> </div> <div id="sectFns" class="hidden"> <h2>Functions</h2> <dl id="listFns"> </dl> </div> <div id="sectErrSets" class="hidden"> <h2>Error Sets</h2> <ul id="listErrSets" class="columns"> </ul> </div> <div id="sectDocTests" class="hidden"> <h2>Example Usage</h2> <pre><code id="docTestsCode"></code></pre> </div> <div id="sectSource" class="hidden"> <h2>Source Code</h2> <pre><code id="sourceText"></code></pre> </div> </section> <div id="helpDialog" class="hidden"> <h1>Keyboard Shortcuts</h1> <dl><dt><kbd>?</kbd></dt><dd>Show this help dialog</dd></dl> <dl><dt><kbd>Esc</kbd></dt><dd>Clear focus; close this dialog</dd></dl> <dl><dt><kbd>s</kbd></dt><dd>Focus the search field</dd></dl> <dl><dt><kbd>u</kbd></dt><dd>Go to source code</dd></dl> <dl><dt><kbd>↑</kbd></dt><dd>Move up in search results</dd></dl> <dl><dt><kbd>↓</kbd></dt><dd>Move down in search results</dd></dl> <dl><dt><kbd>⏎</kbd></dt><dd>Go to active search result</dd></dl> </div> <script src="main.js"></script> </body> </html>
0
repos
repos/maybe-zig/README.md
# maybe-zig [![](https://img.shields.io/github/v/tag/thechampagne/maybe-zig?label=version)](https://github.com/thechampagne/maybe-zig/releases/latest) [![](https://img.shields.io/github/license/thechampagne/maybe-zig)](https://github.com/thechampagne/maybe-zig/blob/main/LICENSE) A Rust compatible Result<T, E> and Option< T > types for Zig. ### References - [Result<T, E>](https://doc.rust-lang.org/std/result/index.html) - [Option< T >](https://doc.rust-lang.org/std/option/index.html) ### License This repo is released under the [MIT License](https://github.com/thechampagne/maybe-zig/blob/main/LICENSE).
0
repos
repos/maybe-zig/build.zig
const std = @import("std"); pub fn build(b: *std.Build) void { _ = b.addModule("maybe", .{ .source_file = .{ .path = "src/maybe.zig" }, .dependencies = &[_]std.Build.ModuleDependency{}, }); }
0
repos/maybe-zig
repos/maybe-zig/src/tests.zig
const Option = @import("maybe.zig").Option; test "isSome" { const a: Option(u32) = .{ .some = 2}; try @import("std").testing.expectEqual(a.isSome(), true); const b: Option(u32) = .{ .none = {}}; try @import("std").testing.expectEqual(b.isSome(), false); } test "isSomeAnd" { const function = struct { fn predicate(x: u32) bool { return x > 1; } }; const a: Option(u32) = .{ .some = 2}; try @import("std").testing.expectEqual(a.isSomeAnd(function.predicate), true); const b: Option(u32) = .{ .some = 0}; try @import("std").testing.expectEqual(b.isSomeAnd(function.predicate), false); const c: Option(u32) = .{ .none = {}}; try @import("std").testing.expectEqual(c.isSomeAnd(function.predicate), false); } test "isNone" { const a: Option(u32) = .{ .some = 2}; try @import("std").testing.expectEqual(a.isNone(), false); const b: Option(u32) = .{ .none = {}}; try @import("std").testing.expectEqual(b.isNone(), true); } test "expect" { const a: Option([]const u8) = .{ .some = "value"}; try @import("std").testing.expectEqual(a.expect("fruits are healthy"), "value"); } test "unwrap" { const a: Option([]const u8) = .{ .some = "air"}; try @import("std").testing.expectEqual(a.unwrap(), "air"); } test "unwrapOr" { try @import("std").testing.expectEqual(Option([]const u8).Some("car").unwrapOr("bike"), "car"); try @import("std").testing.expectEqual(Option([]const u8).None().unwrapOr("bike"), "bike"); } test "unwrapOrElse" { const function = struct { fn orElse() u32 { return 2 * 10; } }; try @import("std").testing.expectEqual(Option(u32).Some(4).unwrapOrElse(function.orElse), 4); try @import("std").testing.expectEqual(Option(u32).None().unwrapOrElse(function.orElse), 20); } test "unwrapUnchecked" { const a: Option([]const u8) = .{ .some = "air"}; try @import("std").testing.expectEqual(a.unwrapUnchecked(), "air"); } test "map" { const function = struct { fn map(x: []const u8) usize { return x.len; } }; const a: Option([]const u8) = .{ .some = "Hello, World!"}; try @import("std").testing.expectEqual(a.map(usize, function.map), Option(usize).Some(13)); const b: Option([]const u8) = .{ .none = {}}; try @import("std").testing.expectEqual(b.map(usize, function.map), Option(usize).None()); } test "inspect" { const function = struct { fn inspect(x: *const u32) void { @import("std").debug.print("got: {}\n", .{x.*}); } }; _ = Option(u32).Some(4).inspect(function.inspect); _ = Option(u32).None().inspect(function.inspect); } test "mapOr" { const function = struct { fn map(x: []const u8) usize { return x.len; } }; const a = Option([]const u8).Some("foo"); try @import("std").testing.expectEqual(a.mapOr(usize, 42, function.map), 3); const b = Option([]const u8).None(); try @import("std").testing.expectEqual(b.mapOr(usize, 42, function.map), 42); } test "mapOrElse" { const function = struct { fn map(x: []const u8) usize { return x.len; } fn @"else"() usize { return 2 * 21; } }; const a = Option([]const u8).Some("foo"); try @import("std").testing.expectEqual(a.mapOrElse(usize, function.@"else", function.map), 3); const b = Option([]const u8).None(); try @import("std").testing.expectEqual(b.mapOrElse(usize, function.@"else", function.map), 42); } test "and" { { const a = Option(u32).Some(2); const b = Option([]const u8).None(); try @import("std").testing.expectEqual(a.@"and"([]const u8, b), Option([]const u8).None()); } { const a = Option(u32).None(); const b = Option([]const u8).Some("foo"); try @import("std").testing.expectEqual(a.@"and"([]const u8, b), Option([]const u8).None()); } { const a = Option(u32).Some(2); const b = Option([]const u8).Some("foo"); try @import("std").testing.expectEqual(a.@"and"([]const u8, b), Option([]const u8).Some("foo")); } { const a = Option(u32).None(); const b = Option([]const u8).None(); try @import("std").testing.expectEqual(a.@"and"([]const u8, b), Option([]const u8).None()); } } test "andThen" { const function = struct { fn andThen(x: u32) Option([]const u8) { if (x > 2) { return Option([]const u8).None(); } else { return Option([]const u8).Some("ok"); } } }; try @import("std").testing.expectEqual(Option(u32).Some(2).andThen([]const u8, function.andThen), Option([]const u8).Some("ok")); try @import("std").testing.expectEqual(Option(u32).Some(1_000_000).andThen([]const u8, function.andThen), Option([]const u8).None()); try @import("std").testing.expectEqual(Option(u32).None().andThen([]const u8, function.andThen), Option([]const u8).None()); } test "filter" { const function = struct { fn isEven(x: *const u32) bool { return x.* % 2 == 0; } }; try @import("std").testing.expectEqual(Option(u32).None().filter(function.isEven), Option(u32).None()); try @import("std").testing.expectEqual(Option(u32).Some(3).filter(function.isEven), Option(u32).None()); try @import("std").testing.expectEqual(Option(u32).Some(4).filter(function.isEven), Option(u32).Some(4)); } test "or" { { const a = Option(u32).Some(2); const b = Option(u32).None(); try @import("std").testing.expectEqual(a.@"or"(b), Option(u32).Some(2)); } { const a = Option(u32).None(); const b = Option(u32).Some(100); try @import("std").testing.expectEqual(a.@"or"(b), Option(u32).Some(100)); } { const a = Option(u32).Some(2); const b = Option(u32).Some(100); try @import("std").testing.expectEqual(a.@"or"(b), Option(u32).Some(2)); } { const a = Option(u32).None(); const b = Option(u32).None(); try @import("std").testing.expectEqual(a.@"or"(b), Option(u32).None()); } } test "orElse" { const function = struct { fn vikings() Option([]const u8) { return Option([]const u8).Some("vikings"); } fn nobody() Option([]const u8) { return Option([]const u8).None(); } }; try @import("std").testing.expectEqual(Option([]const u8).Some("barbarians").orElse(function.vikings), Option([]const u8).Some("barbarians")); try @import("std").testing.expectEqual(Option([]const u8).None().orElse(function.vikings), Option([]const u8).Some("vikings")); try @import("std").testing.expectEqual(Option([]const u8).None().orElse(function.nobody), Option([]const u8).None()); } test "xor" { { const a = Option(u32).Some(2); const b = Option(u32).None(); try @import("std").testing.expectEqual(a.xor(b), Option(u32).Some(2)); } { const a = Option(u32).None(); const b = Option(u32).Some(2); try @import("std").testing.expectEqual(a.xor(b), Option(u32).Some(2)); } { const a = Option(u32).Some(2); const b = Option(u32).Some(2); try @import("std").testing.expectEqual(a.xor(b), Option(u32).None()); } { const a = Option(u32).None(); const b = Option(u32).None(); try @import("std").testing.expectEqual(a.xor(b), Option(u32).None()); } }
0
repos/maybe-zig
repos/maybe-zig/src/maybe.zig
pub fn Option(comptime T: type) type { return union(enum) { some: T, none, const Self = @This(); pub inline fn None() Self { return .{ .none = {}}; } pub inline fn Some(value: T) Self { return .{ .some = value}; } pub fn isSome(self: Self) bool { switch(self) { .some => return true, else => return false } } pub fn isSomeAnd(self: Self, f: *const fn(T) bool) bool { switch(self) { .some => |v| return f(v), else => return false } } pub fn isNone(self: Self) bool { switch(self) { .none => return true, else => return false } } pub fn expect(self: Self, msg: []const u8) T { switch(self) { .some => |v| return v, else => @panic(msg) } } pub fn unwrap(self: Self) T { switch(self) { .some => |v| return v, else => @panic("called `Option.unwrap()` on a `none` value") } } pub fn unwrapOr(self: Self, default: T) T { switch(self) { .some => |v| return v, else => return default } } pub fn unwrapOrElse(self: Self, f: *const fn() T) T { switch(self) { .some => |v| return v, else => return f() } } pub fn unwrapUnchecked(self: Self) T { return self.some; } pub fn map(self: Self, U: anytype, f: *const fn(T) U) Option(U) { switch(self) { .some => |v| return Option(U).Some(f(v)), else => return Option(U).None() } } pub fn inspect(self: *const Self, f: *const fn(*const T) void) Self { switch(self.*) { .some => |*v| f(v), else => {} } return self.*; } pub fn mapOr(self: Self, U: anytype, default: U, f: *const fn(T) U) U { switch(self) { .some => |v| return f(v), else => return default } } pub fn mapOrElse(self: Self, U: anytype, default: *const fn() U, f: *const fn(T) U) U { switch(self) { .some => |v| return f(v), else => return default() } } pub fn @"and"(self: Self, U: anytype, optb: Option(U)) Option(U) { switch(self) { .some => return optb, else => return Option(U).None() } } pub fn andThen(self: Self, U: anytype, f: *const fn(T) Option(U)) Option(U) { switch(self) { .some => |v| return f(v), else => return Option(U).None() } } pub fn filter(self: *const Self, f: *const fn(*const T) bool) Self { switch(self.*) { .some => |*v| if (f(v)) return self.* else return Self.None(), else => return self.* } } pub fn @"or"(self: Self, optb: Option(T)) Option(T) { switch(self) { .some => return self, else => return optb } } pub fn orElse(self: Self, f: *const fn() Option(T)) Option(T) { switch(self) { .some => return self, else => return f() } } pub fn xor(self: Self, optb: Option(T)) Option(T) { if (self.isSome() and optb.isNone()) { return self; } else if (self.isNone() and optb.isSome()) { return optb; } else return Self.None(); } }; }
0
repos
repos/zig_demoJson/README.md
# zig_demoJson **ZIG-LANG essai JSON ** <BR /> Good morning,<BR /> I needed to make a program and work with JSON.<BR /> <BR /> I was inspired by this code, it was good.<BR /> <BR /> [ziggit.dev](https://ziggit.dev/t/here-is-my-mostly-complete-json-parsing-utility/1334/10) <BR /> thank you [logger](https://github.com/kissy24/zig-logger)<BR /> <BR /> <BR /> Since there aren't many examples, that does the job from start to finish.<BR /> <BR /> This demonstration applies to the possibility of saving and reading JSON.<BR /> To put in a structure and see how to make a JSON<BR /> <BR /> I kept it simple, it's not a work of abstraction, but something that can be incorporated into a module incorporating into a model.<BR /> <BR /> Thanks to everyone who helped me.<BR /> # UPDATE ZIG V 0.13.0<BR />
0
repos/zig_demoJson
repos/zig_demoJson/library/library.zig
///----------------------- /// export library /// zig 0.12.0 dev ///----------------------- pub const cursed = @import("cursed"); pub const utils = @import("utils"); pub const match = @import("match"); pub const forms = @import("forms"); pub const grid = @import("grid"); pub const menu = @import("menu"); pub const callpgm = @import("callpgm"); pub const zmmap = @import("zmmap"); pub const crypto = @import("crypto"); pub const dcml = @import("decimal"); pub const logger = @import("logger");
0
repos/zig_demoJson
repos/zig_demoJson/library/build.zig.zon
.{ .name = "library", .version = "0.0.0", .dependencies = .{}, .paths = .{ "", }, }
0
repos/zig_demoJson
repos/zig_demoJson/library/build.zig
///----------------------- /// build (library) /// zig 0.12.0 dev ///----------------------- const std = @import("std"); pub fn build(b: *std.Build) void { const logger_mod = b.addModule("logger", .{ .root_source_file = b.path( "./curse/logger.zig" ), }); const cursed_mod = b.addModule("cursed", .{ .root_source_file = b.path( "./curse/cursed.zig" ), }); const utils_mod = b.addModule("utils", .{ .root_source_file = b.path( "./curse/utils.zig" ), }); const match_mod = b.addModule("match", .{ .root_source_file = b.path( "./curse/match.zig" ), }); const forms_mod = b.addModule("forms", .{ .root_source_file = b.path( "./curse/forms.zig" ), .imports= &.{ .{ .name = "cursed", .module = cursed_mod }, .{ .name = "utils", .module = utils_mod}, .{ .name = "match", .module = match_mod }, }, }); const grid_mod = b.addModule("grid", .{ .root_source_file = b.path( "./curse/grid.zig" ), .imports = &.{ .{ .name = "cursed", .module = cursed_mod}, .{ .name = "utils", .module = utils_mod}, }, }); const menu_mod= b.addModule("menu", .{ .root_source_file = b.path( "./curse/menu.zig" ), .imports= &.{ .{ .name = "cursed", .module = cursed_mod}, .{ .name = "utils", .module = utils_mod}, }, }); const callpgm_mod = b.addModule("callpgm", .{ .root_source_file = b.path( "./calling/callpgm.zig" ), }); const crypto_mod= b.addModule("crypto", .{ .root_source_file = b.path( "./crypt/crypto.zig" ), }); const zmmap_mod= b.addModule("zmmap", .{ .root_source_file = b.path( "./mmap/zmmap.zig" ), .imports= &.{ .{ .name = "crypto", .module = crypto_mod}, .{ .name = "logger", .module = logger_mod}, }, }); const decimal_mod = b.addModule("decimal", .{ .root_source_file = b.path( "./decimal/decimal.zig" ), }); match_mod.addIncludePath( b.path( "./lib/")); match_mod.link_libc = true; match_mod.addObjectFile(.{.cwd_relative = "/usr/lib/libpcre2-posix.so"}); decimal_mod.addIncludePath( b.path( "./lib/")); decimal_mod.link_libc = true; decimal_mod.addObjectFile(.{.cwd_relative = "/usr/lib/libmpdec.so"}); const library_mod = b.addModule("library", .{ .root_source_file = b.path( "library.zig" ), .imports = &.{ .{ .name = "cursed", .module = cursed_mod }, .{ .name = "utils", .module = utils_mod }, .{ .name = "match", .module = match_mod }, .{ .name = "forms", .module = forms_mod }, .{ .name = "grid", .module = grid_mod }, .{ .name = "menu", .module = menu_mod }, .{ .name = "decimal", .module = decimal_mod }, .{ .name = "callpgm", .module = callpgm_mod }, .{ .name = "zmmap", .module = zmmap_mod }, .{ .name = "crypto", .module = crypto_mod }, .{ .name = "logger", .module = logger_mod }, }, }); _ = library_mod; }
0
repos/zig_demoJson/library
repos/zig_demoJson/library/decimal/decimal.zig
const std = @import("std"); const utf = @import("std").unicode; const c = @cImport( { @cInclude("mpdecimal.h"); } ); //--------------------------------------------------------------------------------- // begin decimal // /// https://www.bytereef.org/mpdecimal/index.html /// const c = @cImport( { @cInclude("mpdecimal.h"); } ); /// installation with your package manager or download /// /// validated: by https://speleotrove.com/decimal/ /// official site thank you for making this standardization available /// /// CTX_ADDR Communication structure for default common control decimal128 -> MPD_ROUND_05UP /// openContex() /// /// DCMLFX includes 3 values /// number: mpdecimal structure [*c] /// integer: number of integers in front of the point /// scale: number of integers behind the point /// associated function: /// def: checks the relevance of bounding with mpdecimal and determines the fixed decimal /// Test if the context is active otherwise it calls openContext() /// /// free: frees the associated memory storage ".number" (not the definition) /// debugPrint: small followed by ".number" /// isNumber: check value is compliant '0-9 + - .' compliant SQL postgres DB2... /// isValide: uses isNumber, and checks if the external value complies with the boundary /// isOverflow: check if the internal value is out of bounds /// assign: give a value (text format) to ".number" /// setZeros: forces the value 0 to ".number" /// isZeros: checks if the value 0 /// round: two-function round and truncate (0.5 = +1) see finance... /// trunc: to a function, truncate without rounding /// string: if the scale part is larger than its definition, /// it rounds then adds zeros if necessary (respects the SQL display alignment standard on the left ex: 1.00) /// add: a = a + b /// sub: a = a - b /// mul: a = a * b /// div: a = a / b if b = zeros raises an error /// addTo: r = a + b /// subTo: r = a - b /// mulTo: r = a * b /// divto: r = a / b if b = zeros raises an error /// floor: r = a /// ceil : r = a /// rem : r = a / b if b = zeros raises an error /// rate: raises a value with the percentage ex ( n = (val*nbr) , val = (n * %1.25) /// /// function off DCMLF /// cmp: compare a , b returns EQ LT GT /// mdrate module: returns ex: ttc , htx (base val, article nrb, rate = 25 ) practice in 5 operations /// forceAssign: forces the value /// dsperr: practical @panic product in test /// debugContext: print context pub var CTX_ADDR: c.mpd_context_t = undefined; var startContext : bool = false ; const dcmlError = error { Failed_Init_iEntier_iScale, Failed_set_precision_cMaxDigit, Failed_isNumber_string, Failed_valid_entier, Failed_valid_scale, Failed_valid_dot, isOverflow_entier, isOverflow_scale, isOverflow_entier_htx, isOverflow_entier_ttc, div_impossible_zeros, cmp_impossible }; pub const dcml = struct{ pub const DCMLFX = struct { number : [*c]c.mpd_t , // number entier : u8 , // Left part of the number scale : u8 , // Right part of the number //-------------------------------------------------------------- // Definition ex: for management -> accounting, stock, order... //-------------------------------------------------------------- // MPD_DECIMAL32 = 32 MPD_ROUND_HALF_EVEN // MPD_DECIMAL64 = 64 MPD_ROUND_HALF_EVEN // MPD_DECIMAL128 = 128 MPD_ROUND_HALF_EVEN 34 digit IEE754 // MPD_DECIMAL256 = 256 MPD_ROUND_HALF_EVEN 70 // MPD_DECIMAL512 = 512 MPD_ROUND_HALF_EVEN 142 fn openContext() void { c.mpd_maxcontext(&CTX_ADDR) ; _= c.mpd_ieee_context(&CTX_ADDR, 512); _= c.mpd_qsetround(&CTX_ADDR, 6); // default MPD_ROUND_HALF_EVEN startContext = true ; } pub fn def( iEntier: u8 , iScale : u8 ) ! DCMLFX { if (!startContext) openContext(); if ((iEntier + iScale > c.mpd_getprec(&CTX_ADDR)) or ( iEntier == 0 and iScale == 0 ) ) return dcmlError.Failed_Init_iEntier_iScale; const snum = DCMLFX { .number = c.mpd_qnew() , .entier = iEntier , .scale = iScale }; c.mpd_set_string(@ptrCast(snum.number), @ptrCast("0"), &CTX_ADDR ); c.mpd_set_flags(snum.number,128); return snum; } // Frees the storage memory of DCMLFX.number fn free(cnbr: DCMLFX) void { c.mpd_del(cnbr.number); } // debug dcml number, entier,scale pub fn debugPrint(cnbr: DCMLFX, txt : []const u8) void { std.debug.print("debug: {s} --> dcml:{s} entier:{d} scale:{d} \r\n", .{ txt, c.mpd_to_eng(cnbr.number, 0), cnbr.entier, cnbr.scale }); } // Numerical value control pub fn isNumber ( str :[] const u8) bool { if (std.mem.eql(u8, str, "") ) return false; var iter = iteratStr.iterator(str); var b: bool = true; var p: bool = false; var i: usize =0; while (iter.next()) |ch| :( i += 1) { const x = utf.utf8Decode(ch) catch unreachable; switch (x) { '0'...'9' => continue , '.' => { if ( p ) b = false else { p = true ; continue ; } // control is . unique }, '-' => { if ( i == 0 ) continue else b = false ; } , '+' => { if ( i == 0 ) continue else b = false ; } , else => b = false , } } return b; } // Validity check pub fn isValid (cnbr: DCMLFX, str :[] const u8) ! void { if (!isNumber(str)) return dcmlError.Failed_isNumber_string; var iter = iteratStr.iterator(str); var e: usize = 0 ; // nbr carctère entier var s: usize = 0 ; // nbr carctère scale var p: bool =false; // '.' while (iter.next()) |ch| { const x = utf.utf8Decode(ch) catch unreachable; switch (x) { '0'...'9' => { if (!p ) e += 1 else s += 1; }, '.' => p = true, else => {}, } } if (cnbr.entier < e) return dcmlError.Failed_valid_entier; if (cnbr.scale < s) return dcmlError.Failed_valid_scale; if (p and s == 0) return dcmlError.Failed_valid_dot; return ; } // Validity check Overflow pub fn isOverflow (cnbr: DCMLFX) ! void { const str = std.mem.span(c.mpd_to_eng(cnbr.number, 0)); var iter = iteratStr.iterator(str); var e: usize = 0 ; // nbr carctère entier var s: usize = 0 ; // nbr carctère scale var p: bool =false; // '.' while (iter.next()) |ch| { const x = utf.utf8Decode(ch) catch unreachable; switch (x) { '0'...'9' => { if (!p ) e += 1 else s += 1; }, '.' => p = true, else => {}, } } if (cnbr.entier < e) return dcmlError.isOverflow_entier; if (cnbr.scale < s) return dcmlError.isOverflow_scale; } // value assignment pub fn assign(cnbr: DCMLFX, str: []const u8) ! void { const allocator = std.heap.page_allocator; isValid(cnbr, str) catch | err | {return err ;} ; const sVal = allocator.alloc(u8, str.len ) catch unreachable; @memcpy( sVal, str); c.mpd_set_string(@ptrCast(cnbr.number), @ptrCast(sVal), &CTX_ADDR ); } // set "0" pub fn setZeros(cnbr: DCMLFX) void { c.mpd_set_string(@ptrCast(cnbr.number), @ptrCast("0"), &CTX_ADDR); } // isZeros pub fn isZeros(cnbr: DCMLFX) bool{ if ( 1 == c.mpd_iszero(cnbr.number)) return true else return false; } // ARRONDI comptable / commercial // round and truncate 5 => + 1 pub fn round(cnbr: DCMLFX) void { const r: [*c]c.mpd_t = c.mpd_qnew(); var i : usize = 1; const m: c_int = 10; c.mpd_copy(r , cnbr.number , &CTX_ADDR); if (cnbr.scale > 0){ while( i <= cnbr.scale) : (i += 1) { c.mpd_mul_i32(r , r, m , &CTX_ADDR); } i = 1; c.mpd_round_to_int(r , r, &CTX_ADDR); while( i <= cnbr.scale) : (i += 1) { c.mpd_div_i32(r , r, m , &CTX_ADDR); } } else c.mpd_floor(r , r, &CTX_ADDR); c.mpd_copy(cnbr.number , r, &CTX_ADDR); } // truncate without rounding pub fn trunc(cnbr: DCMLFX) void { const r: [*c]c.mpd_t = c.mpd_qnew(); var i : usize = 1; const m: c_int = 10; c.mpd_copy(r , cnbr.number , &CTX_ADDR); if (cnbr.scale > 0){ while( i <= cnbr.scale) : (i += 1) { c.mpd_mul_i32(r , r, m , &CTX_ADDR); } i = 1; c.mpd_trunc(r , r, &CTX_ADDR); while( i <= cnbr.scale) : (i += 1) { c.mpd_div_i32(r , r, m , &CTX_ADDR); } } else c.mpd_floor(r , r, &CTX_ADDR); c.mpd_copy(cnbr.number , r, &CTX_ADDR); } // Returns a formatted string for gestion, statistique ... pub fn string(cnbr: DCMLFX ) [] const u8 { // attention output [*c] const cstring = c.mpd_to_eng(cnbr.number, 0); // convetion from [*c] to [] const u8 var str = std.mem.span(cstring); var iter = iteratStr.iterator(str); var s: usize = 0 ; // nbr carctère scale var p: bool =false; // '.' while (iter.next()) |ch| { const x = utf.utf8Decode(ch) catch unreachable; switch (x) { '0'...'9' => { if (p ) s += 1 ; }, '.' => p = true, else => {}, } } if ( s > cnbr.scale ) { cnbr.round(); str = std.mem.span(c.mpd_to_eng(cnbr.number, 0)); iter = iteratStr.iterator(str); s = 0 ; p =false; while (iter.next()) |ch| { const x = utf.utf8Decode(ch) catch unreachable; switch (x) { '0'...'9' => { if (p ) s += 1 ; }, '.' => p = true, else => {}, } } } if ( cnbr.scale > 0 ) { var n : usize = cnbr.scale - s; const allocator = std.heap.page_allocator; var buf = std.fmt.allocPrint(allocator,"{s}", .{str}) catch unreachable; if (!p) buf = std.fmt.allocPrint(allocator,"{s}.", .{buf}) catch unreachable; while (true) { if (n == 0) break; buf = std.fmt.allocPrint(allocator,"{s}0", .{buf}) catch unreachable; n -= 1; } return buf; } else return str ; } // function ADD pub fn add(a: DCMLFX ,b: DCMLFX) !void { if( a.isZeros()) {a.setZeros() ; return ;} c.mpd_add(a.number, a.number, b.number, &CTX_ADDR); a.isOverflow() catch | err | { if (err == dcmlError.isOverflow_entier) return err ; } ; } // function ADD pub fn addTo(r: DCMLFX , a: DCMLFX ,b: DCMLFX) !void { if( a.isZeros()) {r.setZeros() ; return ;} c.mpd_add(r.number, a.number, b.number, &CTX_ADDR); r.isOverflow() catch | err | { if (err == dcmlError.isOverflow_entier) return err ; } ; } // function SUB pub fn sub(a: DCMLFX ,b: DCMLFX) !void { if( a.isZeros()) {a.setZeros() ; return ;} c.mpd_sub(a.number, a.number, b.number, &CTX_ADDR); a.isOverflow() catch | err | { if (err == dcmlError.isOverflow_entier) return err ; } ; } // function SUB pub fn subTo(r: DCMLFX ,a: DCMLFX ,b: DCMLFX) !void { if( a.isZeros()) {r.setZeros() ; return ;} c.mpd_sub(r.number, a.number, b.number, &CTX_ADDR); r.isOverflow() catch | err | { if (err == dcmlError.isOverflow_entier) return err ; } ; } // function mult pub fn mult(a: DCMLFX ,b: DCMLFX) !void { if( a.isZeros()) {a.setZeros() ; return ;} c.mpd_mul(a.number, a.number, b.number, &CTX_ADDR); a.isOverflow() catch | err | { if (err == dcmlError.isOverflow_entier) return err ; } ; } // function mult pub fn multTo(r: DCMLFX ,a: DCMLFX ,b: DCMLFX) !void { if( a.isZeros()) {r.setZeros() ; return ;} c.mpd_mul(r.number, a.number, b.number, &CTX_ADDR,); r.isOverflow() catch | err | { if (err == dcmlError.isOverflow_entier) return err ; } ; } // function div pub fn div(a: DCMLFX ,b: DCMLFX) !void { if( b.isZeros()) return dcmlError.div_impossible_zeros; if( a.isZeros()) {a.setZeros() ; return ;} c.mpd_div(a.number, a.number, b.number, &CTX_ADDR); a.isOverflow() catch | err | { if (err == dcmlError.isOverflow_entier) return err ; } ; } // function mult pub fn divTo(r: DCMLFX ,a: DCMLFX ,b: DCMLFX) !void { if( b.isZeros()) return dcmlError.div_impossible_zeros; if( a.isZeros()) {r.setZeros() ; return ;} c.mpd_mul(r.number, a.number, b.number, &CTX_ADDR,); r.isOverflow() catch | err | { if (err == dcmlError.isOverflow_entier) return err ; } ; } // function Floor pub fn floor(r: DCMLFX ,a: DCMLFX) !void { if( a.isZeros()) {r.setZeros() ; return ;} c.mpd_floor(r.number, a.number, &CTX_ADDR); r.isOverflow() catch | err | { if (err == dcmlError.isOverflow_entier) return err ; } ; } // function ceiling pub fn ceil(r: DCMLFX ,a: DCMLFX) !void { if( a.isZeros()) {r.setZeros() ; return ;} c.mpd_ceil(r.number, a.number, &CTX_ADDR); r.isOverflow() catch | err | { if (err == dcmlError.isOverflow_entier) return err ; } ; } // function remainder pub fn rem(r: DCMLFX ,a: DCMLFX ,b: DCMLFX) !void { if( b.isZeros()) return dcmlError.div_impossible_zeros; if( a.isZeros()) {r.setZeros() ; return ;} c.mpd_rem(r.number, a.number, b.number, &CTX_ADDR); r.isOverflow() catch | err | { if (err == dcmlError.isOverflow_entier) return err ; } ; } // function val * nbr * coef 1*x * 1.25 pub fn rate(res: DCMLFX ,val: DCMLFX , nbr: DCMLFX, coef:DCMLFX) !void { if( val.isZeros()) {res.setZeros() ; return ;} // total htx c.mpd_mul(res.number,val.number, nbr.number, &CTX_ADDR); // total ttc c.mpd_mul(res.number,res.number, coef.number, &CTX_ADDR); } // compare a , b returns EQ LT GT pub fn cmp(a: DCMLFX ,b: DCMLFX) ! CMP { const rep : c_int = c.mpd_cmp(a.number ,b.number, &CTX_ADDR); switch (rep) { -1 => return CMP.LT , 0 => return CMP.EQ , 1 => return CMP.GT , else => return dcmlError.cmp_impossible, } } }; pub const CMP = enum (i8) { LT = -1 , EQ = 0 , GT = 1 , }; // compare a , b returns EQ LT GT pub fn cmp(a: DCMLFX ,b: DCMLFX) ! CMP { const rep : c_int = c.mpd_cmp(a.number ,b.number, &CTX_ADDR); switch (rep) { -1 => return CMP.LT , 0 => return CMP.EQ , 1 => return CMP.GT , else => return dcmlError.cmp_impossible, } } // module rate htx= (val * nbr) ttc = (htx/∕100) * 25 ) + htx pub fn mdrate(resttc: DCMLFX ,reshtx: DCMLFX ,val: DCMLFX ,nbr: DCMLFX, coef:DCMLFX) !void { if( val.isZeros() or val.isZeros() or coef.isZeros()) {resttc.setZeros() ; reshtx.setZeros() ;return ;} const cent: [*c]c.mpd_t = c.mpd_qnew(); c.mpd_set_string(@ptrCast(cent), @ptrCast("100"),&CTX_ADDR) ; c.mpd_mul(reshtx.number,val.number, nbr.number, &CTX_ADDR); c.mpd_div(resttc.number,reshtx.number, cent, &CTX_ADDR); c.mpd_mul(resttc.number,resttc.number, coef.number, &CTX_ADDR); c.mpd_add(resttc.number,resttc.number, reshtx.number, &CTX_ADDR); reshtx.isOverflow() catch | err | { if (err == dcmlError.isOverflow_entier_htx) return err ; } ; resttc.isOverflow() catch | err | { if (err == dcmlError.isOverflow_entier_ttc) return err ; } ; } // force value assignment pub fn forceAssign(cnbr: DCMLFX, str: []const u8) ! void { if (!dcml.DCMLFX.isNumber(str)) return dcmlError.Failed_isNumber_string; const allocator = std.heap.page_allocator; const sVal = allocator.alloc(u8, str.len ) catch unreachable; @memcpy(sVal, str); c.mpd_set_string(@ptrCast(cnbr.number), @ptrCast(sVal),&CTX_ADDR ); } // Shows mode debug serious programming errors pub const dsperr = struct { pub fn errorDcml(errpgm :anyerror ) void { const allocator = std.heap.page_allocator; const msgerr:[]const u8 = std.fmt.allocPrint(allocator,"To report: {any} ",.{errpgm }) catch unreachable; @panic(msgerr); } }; // debug context pub fn debugContext() void { std.debug.print("{any}\n", .{CTX_ADDR}); } // end decimal //--------------------------------------------------------------------------------- //================================ // function utilitaire //================================ /// Iterator support iteration string pub const iteratStr = struct { var strbuf:[] const u8 = undefined; var arenastr = std.heap.ArenaAllocator.init(std.heap.page_allocator); //defer arena.deinit(); const allocator = arenastr.allocator(); /// Errors that may occur when using String pub const ErrNbrch = error{ InvalideAllocBuffer, }; fn allocBuffer ( size :usize) ErrNbrch![]u8 { const buf = allocator.alloc(u8, size) catch { return ErrNbrch.InvalideAllocBuffer; }; return buf; } pub const StringIterator = struct { buf: []u8 , index: usize , pub fn next(it: *StringIterator) ?[]const u8 { const optional_buf: ?[]u8 = allocBuffer(strbuf.len) catch return null; it.buf= optional_buf orelse ""; var n : usize = 0; while (true) { if (n >= strbuf.len) break; it.buf[n] = strbuf[n]; n += 1; } if (it.index == it.buf.len) return null; const i = it.index; it.index += getUTF8Size(it.buf[i]); return it.buf[i..it.index]; } pub fn preview(it: *StringIterator) ?[]const u8 { const optional_buf: ?[]u8 = allocBuffer(strbuf.len) catch return null; it.buf= optional_buf orelse ""; var n : usize = 0; while (true) { if (n >= strbuf.len) break; it.buf[n] = strbuf[n]; n += 1; } if (it.index == 0) return null; const i = it.buf.len; it.index -= getUTF8Size(it.buf[i]); return it.buf[i..it.index]; } }; /// iterator String pub fn iterator(str:[] const u8) StringIterator { strbuf = str; return StringIterator{ .buf = undefined, .index = 0, }; } /// Returns the UTF-8 character's size fn getUTF8Size(char: u8) u3 { return std.unicode.utf8ByteSequenceLength(char) catch { return 1; }; } }; };
0
repos/zig_demoJson/library
repos/zig_demoJson/library/calling/callpgm.zig
///----------------------- /// callpgm /// zig 0.12.0 dev ///----------------------- const std = @import("std"); /// Errors that may occur when using String pub const ErrChild = error{ Module_Invalid, }; var allocChild = std.heap.page_allocator; pub fn callPgmPid( pgm: []const u8, module: []const u8, pid: ?[]const u8) !void { if ( ! std.mem.eql(u8, pgm, "SH") and !std.mem.eql(u8, pgm, "APPTERM") ) return ErrChild.Module_Invalid; var CallModule: std.process.Child = undefined; // Retrieval of the working library. var buf: [std.fs.max_path_bytes]u8 = undefined; const cwd = std.posix.getcwd(&buf) catch unreachable; //The set of modules is located in the manager's library, for example: (APPTERM). CallModule.cwd = cwd; var arg2: [2][]const u8 = undefined; var arg3: [3][]const u8 = undefined; var prog: [] const u8 = undefined; var cmd : [] const u8 = undefined; var parm: [] const u8 = undefined; if (pid) |value| { if (std.mem.eql(u8, pgm, "SH")) { cmd = std.fmt.allocPrint(allocChild, "./{s} {s}", .{ module, value}) catch unreachable; arg3 = .{ "/bin/sh", "-c", cmd }; CallModule = std.process.Child.init(arg3[0..], allocChild); } if (std.mem.eql(u8, pgm, "APPTERM")) { prog = std.fmt.allocPrint(allocChild,"./{s}", .{pgm}) catch unreachable; cmd = std.fmt.allocPrint(allocChild,"./{s}", .{module}) catch unreachable; parm = std.fmt.allocPrint(allocChild,"{s}", .{ value }) catch unreachable; arg3 = .{prog,cmd, parm}; CallModule = std.process.Child.init(arg3[0..], allocChild); } } else { if (std.mem.eql(u8, pgm, "SH")) { cmd = std.fmt.allocPrint(allocChild, "./{s}", .{ module}) catch unreachable; arg3 = .{ "/bin/sh", "-c", cmd }; CallModule = std.process.Child.init(arg3[0..], allocChild); } if (std.mem.eql(u8, pgm, "APPTERM")) { prog = std.fmt.allocPrint(allocChild,"./{s}", .{pgm}) catch unreachable; cmd = std.fmt.allocPrint(allocChild,"./{s}", .{module}) catch unreachable; arg2 = .{ prog, cmd }; CallModule = std.process.Child.init(arg2[0..], allocChild); } } // CallModule = std.ChildProcess.init(args[0..], allocChild); // Execution and suspension of the caller. const childTerm = std.process.Child.spawnAndWait(&CallModule) catch |err| { @panic(std.fmt.allocPrint(allocChild, "{}", .{err}) catch unreachable); }; switch (childTerm) { .Exited => |code| { if (code != 0) return ErrChild.Module_Invalid; }, else =>unreachable, } }
0
repos/zig_demoJson/library
repos/zig_demoJson/library/crypt/crypto.zig
///----------------------- /// build crypto /// zi=g 0.12.0 dev ///----------------------- const std = @import("std"); const crypto = std.crypto; const Ghash = std.crypto.onetimeauth.Ghash; const math = std.math; const mem = std.mem; const modes = crypto.core.modes; const AuthenticationError = crypto.errors.AuthenticationError; /// référence https://github.com/ziglang/zig/blob/master/lib/std/crypto/aes_gcm.zig /// thank you zig-lang pub const Aes128Gcm = AesGcm(crypto.core.aes.Aes128); pub const Aes256Gcm = AesGcm(crypto.core.aes.Aes256); const random = std.crypto.random; pub fn AesGcm(comptime Aes: anytype) type { return struct { pub const tag_length = 16; pub const nonce_length = 12; pub const key_length = Aes.key_bits / 8; const zeros = [_]u8{0} ** 16; /// `tag`: Authentication tag /// `ad`: Associated data /// `npub`: Public nonce /// `k`: Private key pub fn encrypt(c: [] u8, tag: *[tag_length]u8, m: []const u8, npub: [nonce_length]u8, key: [key_length]u8) void { const ad :[]u8 =""; const aes = Aes.initEnc(key); var h: [16]u8 = undefined; aes.encrypt(&h, &zeros); var t: [16]u8 = undefined; var j: [16]u8 = undefined; j[0..nonce_length].* = npub; mem.writeInt(u32, j[nonce_length..][0..4], 1, .big); aes.encrypt(&t, &j); const block_count = (math.divCeil(usize, ad.len, Ghash.block_length) catch unreachable) + (math.divCeil(usize, c.len, Ghash.block_length) catch unreachable) + 1; var mac = Ghash.initForBlockCount(&h, block_count); mac.update(ad); mac.pad(); mem.writeInt(u32, j[nonce_length..][0..4], 2, .big); modes.ctr(@TypeOf(aes), aes, c, m, j, .big); mac.update(c[0..m.len][0..]); mac.pad(); var final_block = h; mem.writeInt(u64, final_block[0..8], ad.len * 8, .big); mem.writeInt(u64, final_block[8..16], m.len * 8, .big); mac.update(&final_block); mac.final(tag); for (t, 0..) |x, i| { tag[i] ^= x; } } /// `tag`: Authentication tag /// `ad`: Associated data /// `npub`: Public nonce /// `k`: Private key pub fn decrypt(c: []u8, tag: [tag_length]u8, m: []u8, npub: [nonce_length]u8, key: [key_length]u8) AuthenticationError!void { const ad :[]u8 =""; const aes = Aes.initEnc(key); var h: [16]u8 = undefined; aes.encrypt(&h, &zeros); var t: [16]u8 = undefined; var j: [16]u8 = undefined; j[0..nonce_length].* = npub; mem.writeInt(u32, j[nonce_length..][0..4], 1, .big); aes.encrypt(&t, &j); const block_count = (math.divCeil(usize, ad.len, Ghash.block_length) catch unreachable) + (math.divCeil(usize, c.len, Ghash.block_length) catch unreachable) + 1; var mac = Ghash.initForBlockCount(&h, block_count); mac.update(ad); mac.pad(); mac.update(c); mac.pad(); var final_block = h; mem.writeInt(u64, final_block[0..8], ad.len * 8, .big); mem.writeInt(u64, final_block[8..16], m.len * 8, .big); mac.update(&final_block); var computed_tag: [Ghash.mac_length]u8 = undefined; mac.final(&computed_tag); for (t, 0..) |x, i| { computed_tag[i] ^= x; } const verify = crypto.utils.timingSafeEql([tag_length]u8, computed_tag, tag); if (!verify) { crypto.utils.secureZero(u8, &computed_tag); @memset(m, undefined); return error.AuthenticationFailed; } mem.writeInt(u32, j[nonce_length..][0..4], 2, .big); modes.ctr(@TypeOf(aes), aes, m, c, j, .big); } }; }
0
repos/zig_demoJson/library
repos/zig_demoJson/library/lib/mpdecimal.h
/* * Copyright (c) 2008-2024 Stefan Krah. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef LIBMPDEC_MPDECIMAL_H_ #define LIBMPDEC_MPDECIMAL_H_ #ifdef __cplusplus #include <cinttypes> #include <climits> #include <cstdint> #include <cstdio> #include <cstdlib> #define MPD_UINT8_C(x) (static_cast<uint8_t>(x)) extern "C" { #else #include <inttypes.h> #include <limits.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #define MPD_UINT8_C(x) ((uint8_t)x) #endif #if (defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__)) && \ defined(__GNUC__) && __GNUC__ >= 4 && !defined(__INTEL_COMPILER) #define MPD_PRAGMA(x) _Pragma(x) #define MPD_HIDE_SYMBOLS_START "GCC visibility push(hidden)" #define MPD_HIDE_SYMBOLS_END "GCC visibility pop" #else #define MPD_PRAGMA(x) #define MPD_HIDE_SYMBOLS_START #define MPD_HIDE_SYMBOLS_END #endif /******************************************************************************/ /* Version */ /******************************************************************************/ #define MPD_MAJOR_VERSION 4 #define MPD_MINOR_VERSION 0 #define MPD_MICRO_VERSION 0 #define MPD_VERSION "4.0.0" #define MPD_VERSION_HEX ((MPD_MAJOR_VERSION << 24) | \ (MPD_MINOR_VERSION << 16) | \ (MPD_MICRO_VERSION << 8)) const char *mpd_version(void); /******************************************************************************/ /* Configuration */ /******************************************************************************/ /* ABI: 64-bit */ #define MPD_CONFIG_64 1 #ifdef MPD_CONFIG_32 #error "cannot use MPD_CONFIG_32 with 64-bit header." #endif #ifdef CONFIG_32 #error "cannot use CONFIG_32 with 64-bit header." #endif /* BEGIN MPD_CONFIG_64 */ #if defined(MPD_CONFIG_64) /* types for modular and base arithmetic */ #define MPD_UINT_MAX UINT64_MAX #define MPD_BITS_PER_UINT 64 typedef uint64_t mpd_uint_t; /* unsigned mod type */ #define MPD_SIZE_MAX SIZE_MAX typedef size_t mpd_size_t; /* unsigned size type */ /* type for exp, digits, len, prec */ #define MPD_SSIZE_MAX INT64_MAX #define MPD_SSIZE_MIN INT64_MIN typedef int64_t mpd_ssize_t; #define _mpd_strtossize strtoll /* decimal arithmetic */ #define MPD_RADIX 10000000000000000000ULL /* 10**19 */ #define MPD_RDIGITS 19 #define MPD_MAX_POW10 19 #define MPD_EXPDIGITS 19 /* MPD_EXPDIGITS <= MPD_RDIGITS+1 */ #define MPD_MAXTRANSFORM_2N 4294967296ULL /* 2**32 */ #define MPD_MAX_PREC 999999999999999999LL #define MPD_MAX_PREC_LOG2 64 #define MPD_ELIMIT 1000000000000000000LL #define MPD_MAX_EMAX 999999999999999999LL /* ELIMIT-1 */ #define MPD_MIN_EMIN (-999999999999999999LL) /* -EMAX */ #define MPD_MIN_ETINY (MPD_MIN_EMIN-(MPD_MAX_PREC-1)) #define MPD_EXP_INF 2000000000000000001LL #define MPD_EXP_CLAMP (-4000000000000000001LL) #define MPD_MAXIMPORT 105263157894736842L /* ceil((2*MPD_MAX_PREC)/MPD_RDIGITS) */ #define MPD_IEEE_CONTEXT_MAX_BITS 512 /* 16*(log2(MPD_MAX_EMAX / 3)-3) */ /* conversion specifiers */ #define PRI_mpd_uint_t PRIu64 #define PRI_mpd_ssize_t PRIi64 /* END MPD_CONFIG_64 */ /* BEGIN MPD_CONFIG_32 */ #elif defined(MPD_CONFIG_32) /* types for modular and base arithmetic */ #define MPD_UINT_MAX UINT32_MAX #define MPD_BITS_PER_UINT 32 typedef uint32_t mpd_uint_t; /* unsigned mod type */ #ifndef MPD_LEGACY_COMPILER #define MPD_UUINT_MAX UINT64_MAX typedef uint64_t mpd_uuint_t; /* double width unsigned mod type */ #endif #define MPD_SIZE_MAX SIZE_MAX typedef size_t mpd_size_t; /* unsigned size type */ /* type for dec->len, dec->exp, ctx->prec */ #define MPD_SSIZE_MAX INT32_MAX #define MPD_SSIZE_MIN INT32_MIN typedef int32_t mpd_ssize_t; #define _mpd_strtossize strtol /* decimal arithmetic */ #define MPD_RADIX 1000000000UL /* 10**9 */ #define MPD_RDIGITS 9 #define MPD_MAX_POW10 9 #define MPD_EXPDIGITS 10 /* MPD_EXPDIGITS <= MPD_RDIGITS+1 */ #define MPD_MAXTRANSFORM_2N 33554432UL /* 2**25 */ #define MPD_MAX_PREC 425000000L #define MPD_MAX_PREC_LOG2 32 #define MPD_ELIMIT 425000001L #define MPD_MAX_EMAX 425000000L /* ELIMIT-1 */ #define MPD_MIN_EMIN (-425000000L) /* -EMAX */ #define MPD_MIN_ETINY (MPD_MIN_EMIN-(MPD_MAX_PREC-1)) #define MPD_EXP_INF 1000000001L /* allows for emax=999999999 in the tests */ #define MPD_EXP_CLAMP (-2000000001L) /* allows for emin=-999999999 in the tests */ #define MPD_MAXIMPORT 94444445L /* ceil((2*MPD_MAX_PREC)/MPD_RDIGITS) */ #define MPD_IEEE_CONTEXT_MAX_BITS 256 /* 16*(log2(MPD_MAX_EMAX / 3)-3) */ /* conversion specifiers */ #define PRI_mpd_uint_t PRIu32 #define PRI_mpd_ssize_t PRIi32 /* END MPD_CONFIG_32 */ #else #error "define MPD_CONFIG_64 or MPD_CONFIG_32" #endif /* END CONFIG */ #if MPD_SIZE_MAX != MPD_UINT_MAX #error "unsupported platform: need mpd_size_t == mpd_uint_t" #endif /******************************************************************************/ /* Context */ /******************************************************************************/ enum { MPD_ROUND_UP, /* round away from 0 */ MPD_ROUND_DOWN, /* round toward 0 (truncate) */ MPD_ROUND_CEILING, /* round toward +infinity */ MPD_ROUND_FLOOR, /* round toward -infinity */ MPD_ROUND_HALF_UP, /* 0.5 is rounded up */ MPD_ROUND_HALF_DOWN, /* 0.5 is rounded down */ MPD_ROUND_HALF_EVEN, /* 0.5 is rounded to even */ MPD_ROUND_05UP, /* round zero or five away from 0 */ MPD_ROUND_TRUNC, /* truncate, but set infinity */ MPD_ROUND_GUARD }; enum { MPD_CLAMP_DEFAULT, MPD_CLAMP_IEEE_754, MPD_CLAMP_GUARD }; extern const char * const mpd_round_string[MPD_ROUND_GUARD]; extern const char * const mpd_clamp_string[MPD_CLAMP_GUARD]; typedef struct mpd_context_t { mpd_ssize_t prec; /* precision */ mpd_ssize_t emax; /* max positive exp */ mpd_ssize_t emin; /* min negative exp */ uint32_t traps; /* status events that should be trapped */ uint32_t status; /* status flags */ uint32_t newtrap; /* set by mpd_addstatus_raise() */ int round; /* rounding mode */ int clamp; /* clamp mode */ int allcr; /* all functions correctly rounded */ } mpd_context_t; /* Status flags */ #define MPD_Clamped 0x00000001U #define MPD_Conversion_syntax 0x00000002U #define MPD_Division_by_zero 0x00000004U #define MPD_Division_impossible 0x00000008U #define MPD_Division_undefined 0x00000010U #define MPD_Fpu_error 0x00000020U #define MPD_Inexact 0x00000040U #define MPD_Invalid_context 0x00000080U #define MPD_Invalid_operation 0x00000100U #define MPD_Malloc_error 0x00000200U #define MPD_Not_implemented 0x00000400U #define MPD_Overflow 0x00000800U #define MPD_Rounded 0x00001000U #define MPD_Subnormal 0x00002000U #define MPD_Underflow 0x00004000U #define MPD_Max_status (0x00008000U-1U) /* Conditions that result in an IEEE 754 exception */ #define MPD_IEEE_Invalid_operation (MPD_Conversion_syntax | \ MPD_Division_impossible | \ MPD_Division_undefined | \ MPD_Fpu_error | \ MPD_Invalid_context | \ MPD_Invalid_operation | \ MPD_Malloc_error) \ /* Errors that require the result of an operation to be set to NaN */ #define MPD_Errors (MPD_IEEE_Invalid_operation | \ MPD_Division_by_zero) /* Default traps */ #define MPD_Traps (MPD_IEEE_Invalid_operation | \ MPD_Division_by_zero | \ MPD_Overflow | \ MPD_Underflow) /* Official name */ #define MPD_Insufficient_storage MPD_Malloc_error /* IEEE 754 interchange format contexts */ #define MPD_DECIMAL32 32 #define MPD_DECIMAL64 64 #define MPD_DECIMAL128 128 #define MPD_MINALLOC_MIN 2 #define MPD_MINALLOC_MAX 64 extern mpd_ssize_t MPD_MINALLOC; extern void (* mpd_traphandler)(mpd_context_t *); void mpd_dflt_traphandler(mpd_context_t *); void mpd_setminalloc(mpd_ssize_t n); void mpd_init(mpd_context_t *ctx, mpd_ssize_t prec); void mpd_maxcontext(mpd_context_t *ctx); void mpd_defaultcontext(mpd_context_t *ctx); void mpd_basiccontext(mpd_context_t *ctx); int mpd_ieee_context(mpd_context_t *ctx, int bits); mpd_ssize_t mpd_getprec(const mpd_context_t *ctx); mpd_ssize_t mpd_getemax(const mpd_context_t *ctx); mpd_ssize_t mpd_getemin(const mpd_context_t *ctx); int mpd_getround(const mpd_context_t *ctx); uint32_t mpd_gettraps(const mpd_context_t *ctx); uint32_t mpd_getstatus(const mpd_context_t *ctx); int mpd_getclamp(const mpd_context_t *ctx); int mpd_getcr(const mpd_context_t *ctx); int mpd_qsetprec(mpd_context_t *ctx, mpd_ssize_t prec); int mpd_qsetemax(mpd_context_t *ctx, mpd_ssize_t emax); int mpd_qsetemin(mpd_context_t *ctx, mpd_ssize_t emin); int mpd_qsetround(mpd_context_t *ctx, int newround); int mpd_qsettraps(mpd_context_t *ctx, uint32_t flags); int mpd_qsetstatus(mpd_context_t *ctx, uint32_t flags); int mpd_qsetclamp(mpd_context_t *ctx, int c); int mpd_qsetcr(mpd_context_t *ctx, int c); void mpd_addstatus_raise(mpd_context_t *ctx, uint32_t flags); /******************************************************************************/ /* Decimal Arithmetic */ /******************************************************************************/ /* mpd_t flags */ #define MPD_POS MPD_UINT8_C(0) #define MPD_NEG MPD_UINT8_C(1) #define MPD_INF MPD_UINT8_C(2) #define MPD_NAN MPD_UINT8_C(4) #define MPD_SNAN MPD_UINT8_C(8) #define MPD_SPECIAL (MPD_INF|MPD_NAN|MPD_SNAN) #define MPD_STATIC MPD_UINT8_C(16) #define MPD_STATIC_DATA MPD_UINT8_C(32) #define MPD_SHARED_DATA MPD_UINT8_C(64) #define MPD_CONST_DATA MPD_UINT8_C(128) #define MPD_DATAFLAGS (MPD_STATIC_DATA|MPD_SHARED_DATA|MPD_CONST_DATA) /* mpd_t */ typedef struct mpd_t { uint8_t flags; mpd_ssize_t exp; mpd_ssize_t digits; mpd_ssize_t len; mpd_ssize_t alloc; mpd_uint_t *data; uint8_t entier; /* ---> specifique partie Entière */ uint8_t scale; /* ---> specifique partie non Entière */ uint8_t nullable; /* ---> specifique sql */ } mpd_t; /******************************************************************************/ /* Triple */ /******************************************************************************/ /* status cases for getting a triple */ enum mpd_triple_class { MPD_TRIPLE_NORMAL, MPD_TRIPLE_INF, MPD_TRIPLE_QNAN, MPD_TRIPLE_SNAN, MPD_TRIPLE_ERROR, }; typedef struct { enum mpd_triple_class tag; uint8_t sign; uint64_t hi; uint64_t lo; int64_t exp; } mpd_uint128_triple_t; int mpd_from_uint128_triple(mpd_t *result, const mpd_uint128_triple_t *triple, uint32_t *status); mpd_uint128_triple_t mpd_as_uint128_triple(const mpd_t *a); /******************************************************************************/ /* Quiet, thread-safe functions */ /******************************************************************************/ /* format specification */ typedef struct mpd_spec_t { mpd_ssize_t min_width; /* minimum field width */ mpd_ssize_t prec; /* fraction digits or significant digits */ char type; /* conversion specifier */ char align; /* alignment */ char sign; /* sign printing/alignment */ char sign_coerce; /* coerce to positive zero */ char fill[5]; /* fill character */ const char *dot; /* decimal point */ const char *sep; /* thousands separator */ const char *grouping; /* grouping of digits */ } mpd_spec_t; /* output to a string */ char *mpd_to_sci(const mpd_t *dec, int fmt); char *mpd_to_eng(const mpd_t *dec, int fmt); mpd_ssize_t mpd_to_sci_size(char **res, const mpd_t *dec, int fmt); mpd_ssize_t mpd_to_eng_size(char **res, const mpd_t *dec, int fmt); int mpd_validate_lconv(mpd_spec_t *spec); int mpd_parse_fmt_str(mpd_spec_t *spec, const char *fmt, int caps); char *mpd_qformat_spec(const mpd_t *dec, const mpd_spec_t *spec, const mpd_context_t *ctx, uint32_t *status); char *mpd_qformat(const mpd_t *dec, const char *fmt, const mpd_context_t *ctx, uint32_t *status); #define MPD_NUM_FLAGS 15 #define MPD_MAX_FLAG_STRING 208 #define MPD_MAX_FLAG_LIST (MPD_MAX_FLAG_STRING+18) #define MPD_MAX_SIGNAL_LIST 121 int mpd_snprint_flags(char *dest, int nmemb, uint32_t flags); int mpd_lsnprint_flags(char *dest, int nmemb, uint32_t flags, const char *flag_string[]); int mpd_lsnprint_signals(char *dest, int nmemb, uint32_t flags, const char *signal_string[]); /* output to a file */ void mpd_fprint(FILE *file, const mpd_t *dec); void mpd_print(const mpd_t *dec); /* assignment from a string */ void mpd_qset_string(mpd_t *dec, const char *s, const mpd_context_t *ctx, uint32_t *status); void mpd_qset_string_exact(mpd_t *dec, const char *s, uint32_t *status); /* set to NaN with error flags */ void mpd_seterror(mpd_t *result, uint32_t flags, uint32_t *status); /* set a special with sign and type */ void mpd_setspecial(mpd_t *result, uint8_t sign, uint8_t type); /* set coefficient to zero or all nines */ void mpd_zerocoeff(mpd_t *result); void mpd_qmaxcoeff(mpd_t *result, const mpd_context_t *ctx, uint32_t *status); /* quietly assign a C integer type to an mpd_t */ void mpd_qset_ssize(mpd_t *result, mpd_ssize_t a, const mpd_context_t *ctx, uint32_t *status); void mpd_qset_i32(mpd_t *result, int32_t a, const mpd_context_t *ctx, uint32_t *status); void mpd_qset_uint(mpd_t *result, mpd_uint_t a, const mpd_context_t *ctx, uint32_t *status); void mpd_qset_u32(mpd_t *result, uint32_t a, const mpd_context_t *ctx, uint32_t *status); #ifndef MPD_LEGACY_COMPILER void mpd_qset_i64(mpd_t *result, int64_t a, const mpd_context_t *ctx, uint32_t *status); void mpd_qset_u64(mpd_t *result, uint64_t a, const mpd_context_t *ctx, uint32_t *status); void mpd_qset_i64_exact(mpd_t *result, int64_t a, uint32_t *status); void mpd_qset_u64_exact(mpd_t *result, uint64_t a, uint32_t *status); #endif /* quietly assign a C integer type to an mpd_t with a static coefficient */ void mpd_qsset_ssize(mpd_t *result, mpd_ssize_t a, const mpd_context_t *ctx, uint32_t *status); void mpd_qsset_i32(mpd_t *result, int32_t a, const mpd_context_t *ctx, uint32_t *status); void mpd_qsset_uint(mpd_t *result, mpd_uint_t a, const mpd_context_t *ctx, uint32_t *status); void mpd_qsset_u32(mpd_t *result, uint32_t a, const mpd_context_t *ctx, uint32_t *status); /* quietly get a C integer type from an mpd_t */ mpd_ssize_t mpd_qget_ssize(const mpd_t *dec, uint32_t *status); mpd_uint_t mpd_qget_uint(const mpd_t *dec, uint32_t *status); mpd_uint_t mpd_qabs_uint(const mpd_t *dec, uint32_t *status); int32_t mpd_qget_i32(const mpd_t *dec, uint32_t *status); uint32_t mpd_qget_u32(const mpd_t *dec, uint32_t *status); #ifndef MPD_LEGACY_COMPILER int64_t mpd_qget_i64(const mpd_t *dec, uint32_t *status); uint64_t mpd_qget_u64(const mpd_t *dec, uint32_t *status); #endif /* quiet functions */ int mpd_qcheck_nan(mpd_t *nanresult, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status); int mpd_qcheck_nans(mpd_t *nanresult, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status); void mpd_qfinalize(mpd_t *result, const mpd_context_t *ctx, uint32_t *status); const char *mpd_class(const mpd_t *a, const mpd_context_t *ctx); int mpd_qcopy(mpd_t *result, const mpd_t *a, uint32_t *status); int mpd_qcopy_cxx(mpd_t *result, const mpd_t *a); mpd_t *mpd_qncopy(const mpd_t *a); int mpd_qcopy_abs(mpd_t *result, const mpd_t *a, uint32_t *status); int mpd_qcopy_negate(mpd_t *result, const mpd_t *a, uint32_t *status); int mpd_qcopy_sign(mpd_t *result, const mpd_t *a, const mpd_t *b, uint32_t *status); void mpd_qand(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status); void mpd_qinvert(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status); void mpd_qlogb(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status); void mpd_qor(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status); void mpd_qscaleb(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status); void mpd_qxor(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status); int mpd_same_quantum(const mpd_t *a, const mpd_t *b); void mpd_qrotate(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status); int mpd_qshiftl(mpd_t *result, const mpd_t *a, mpd_ssize_t n, uint32_t *status); mpd_uint_t mpd_qshiftr(mpd_t *result, const mpd_t *a, mpd_ssize_t n, uint32_t *status); mpd_uint_t mpd_qshiftr_inplace(mpd_t *result, mpd_ssize_t n); void mpd_qshift(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status); void mpd_qshiftn(mpd_t *result, const mpd_t *a, mpd_ssize_t n, const mpd_context_t *ctx, uint32_t *status); int mpd_qcmp(const mpd_t *a, const mpd_t *b, uint32_t *status); int mpd_qcompare(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status); int mpd_qcompare_signal(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status); int mpd_cmp_total(const mpd_t *a, const mpd_t *b); int mpd_cmp_total_mag(const mpd_t *a, const mpd_t *b); int mpd_compare_total(mpd_t *result, const mpd_t *a, const mpd_t *b); int mpd_compare_total_mag(mpd_t *result, const mpd_t *a, const mpd_t *b); void mpd_qround_to_intx(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status); void mpd_qround_to_int(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status); void mpd_qtrunc(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status); void mpd_qfloor(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status); void mpd_qceil(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status); void mpd_qabs(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status); void mpd_qmax(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status); void mpd_qmax_mag(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status); void mpd_qmin(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status); void mpd_qmin_mag(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status); void mpd_qminus(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status); void mpd_qplus(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status); void mpd_qnext_minus(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status); void mpd_qnext_plus(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status); void mpd_qnext_toward(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status); void mpd_qquantize(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status); void mpd_qrescale(mpd_t *result, const mpd_t *a, mpd_ssize_t exp, const mpd_context_t *ctx, uint32_t *status); void mpd_qrescale_fmt(mpd_t *result, const mpd_t *a, mpd_ssize_t exp, const mpd_context_t *ctx, uint32_t *status); void mpd_qreduce(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status); void mpd_qadd(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status); void mpd_qadd_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b, const mpd_context_t *ctx, uint32_t *status); void mpd_qadd_i32(mpd_t *result, const mpd_t *a, int32_t b, const mpd_context_t *ctx, uint32_t *status); void mpd_qadd_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b, const mpd_context_t *ctx, uint32_t *status); void mpd_qadd_u32(mpd_t *result, const mpd_t *a, uint32_t b, const mpd_context_t *ctx, uint32_t *status); void mpd_qsub(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status); void mpd_qsub_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b, const mpd_context_t *ctx, uint32_t *status); void mpd_qsub_i32(mpd_t *result, const mpd_t *a, int32_t b, const mpd_context_t *ctx, uint32_t *status); void mpd_qsub_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b, const mpd_context_t *ctx, uint32_t *status); void mpd_qsub_u32(mpd_t *result, const mpd_t *a, uint32_t b, const mpd_context_t *ctx, uint32_t *status); void mpd_qmul(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status); void mpd_qmul_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b, const mpd_context_t *ctx, uint32_t *status); void mpd_qmul_i32(mpd_t *result, const mpd_t *a, int32_t b, const mpd_context_t *ctx, uint32_t *status); void mpd_qmul_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b, const mpd_context_t *ctx, uint32_t *status); void mpd_qmul_u32(mpd_t *result, const mpd_t *a, uint32_t b, const mpd_context_t *ctx, uint32_t *status); void mpd_qfma(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_t *c, const mpd_context_t *ctx, uint32_t *status); void mpd_qdiv(mpd_t *q, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status); void mpd_qdiv_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b, const mpd_context_t *ctx, uint32_t *status); void mpd_qdiv_i32(mpd_t *result, const mpd_t *a, int32_t b, const mpd_context_t *ctx, uint32_t *status); void mpd_qdiv_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b, const mpd_context_t *ctx, uint32_t *status); void mpd_qdiv_u32(mpd_t *result, const mpd_t *a, uint32_t b, const mpd_context_t *ctx, uint32_t *status); void mpd_qdivint(mpd_t *q, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status); void mpd_qrem(mpd_t *r, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status); void mpd_qrem_near(mpd_t *r, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status); void mpd_qdivmod(mpd_t *q, mpd_t *r, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status); void mpd_qpow(mpd_t *result, const mpd_t *base, const mpd_t *exp, const mpd_context_t *ctx, uint32_t *status); void mpd_qpowmod(mpd_t *result, const mpd_t *base, const mpd_t *exp, const mpd_t *mod, const mpd_context_t *ctx, uint32_t *status); void mpd_qexp(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status); void mpd_qln10(mpd_t *result, mpd_ssize_t prec, uint32_t *status); void mpd_qln(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status); void mpd_qlog10(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status); void mpd_qsqrt(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status); void mpd_qinvroot(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status); #ifndef MPD_LEGACY_COMPILER void mpd_qadd_i64(mpd_t *result, const mpd_t *a, int64_t b, const mpd_context_t *ctx, uint32_t *status); void mpd_qadd_u64(mpd_t *result, const mpd_t *a, uint64_t b, const mpd_context_t *ctx, uint32_t *status); void mpd_qsub_i64(mpd_t *result, const mpd_t *a, int64_t b, const mpd_context_t *ctx, uint32_t *status); void mpd_qsub_u64(mpd_t *result, const mpd_t *a, uint64_t b, const mpd_context_t *ctx, uint32_t *status); void mpd_qmul_i64(mpd_t *result, const mpd_t *a, int64_t b, const mpd_context_t *ctx, uint32_t *status); void mpd_qmul_u64(mpd_t *result, const mpd_t *a, uint64_t b, const mpd_context_t *ctx, uint32_t *status); void mpd_qdiv_i64(mpd_t *result, const mpd_t *a, int64_t b, const mpd_context_t *ctx, uint32_t *status); void mpd_qdiv_u64(mpd_t *result, const mpd_t *a, uint64_t b, const mpd_context_t *ctx, uint32_t *status); #endif size_t mpd_sizeinbase(const mpd_t *a, uint32_t base); void mpd_qimport_u16(mpd_t *result, const uint16_t *srcdata, size_t srclen, uint8_t srcsign, uint32_t srcbase, const mpd_context_t *ctx, uint32_t *status); void mpd_qimport_u32(mpd_t *result, const uint32_t *srcdata, size_t srclen, uint8_t srcsign, uint32_t srcbase, const mpd_context_t *ctx, uint32_t *status); size_t mpd_qexport_u16(uint16_t **rdata, size_t rlen, uint32_t base, const mpd_t *src, uint32_t *status); size_t mpd_qexport_u32(uint32_t **rdata, size_t rlen, uint32_t base, const mpd_t *src, uint32_t *status); /******************************************************************************/ /* Signalling functions */ /******************************************************************************/ char *mpd_format(const mpd_t *dec, const char *fmt, mpd_context_t *ctx); void mpd_import_u16(mpd_t *result, const uint16_t *srcdata, size_t srclen, uint8_t srcsign, uint32_t base, mpd_context_t *ctx); void mpd_import_u32(mpd_t *result, const uint32_t *srcdata, size_t srclen, uint8_t srcsign, uint32_t base, mpd_context_t *ctx); size_t mpd_export_u16(uint16_t **rdata, size_t rlen, uint32_t base, const mpd_t *src, mpd_context_t *ctx); size_t mpd_export_u32(uint32_t **rdata, size_t rlen, uint32_t base, const mpd_t *src, mpd_context_t *ctx); void mpd_finalize(mpd_t *result, mpd_context_t *ctx); int mpd_check_nan(mpd_t *result, const mpd_t *a, mpd_context_t *ctx); int mpd_check_nans(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx); void mpd_set_string(mpd_t *result, const char *s, mpd_context_t *ctx); void mpd_maxcoeff(mpd_t *result, mpd_context_t *ctx); void mpd_sset_ssize(mpd_t *result, mpd_ssize_t a, mpd_context_t *ctx); void mpd_sset_i32(mpd_t *result, int32_t a, mpd_context_t *ctx); void mpd_sset_uint(mpd_t *result, mpd_uint_t a, mpd_context_t *ctx); void mpd_sset_u32(mpd_t *result, uint32_t a, mpd_context_t *ctx); void mpd_set_ssize(mpd_t *result, mpd_ssize_t a, mpd_context_t *ctx); void mpd_set_i32(mpd_t *result, int32_t a, mpd_context_t *ctx); void mpd_set_uint(mpd_t *result, mpd_uint_t a, mpd_context_t *ctx); void mpd_set_u32(mpd_t *result, uint32_t a, mpd_context_t *ctx); #ifndef MPD_LEGACY_COMPILER void mpd_set_i64(mpd_t *result, int64_t a, mpd_context_t *ctx); void mpd_set_u64(mpd_t *result, uint64_t a, mpd_context_t *ctx); #endif mpd_ssize_t mpd_get_ssize(const mpd_t *a, mpd_context_t *ctx); mpd_uint_t mpd_get_uint(const mpd_t *a, mpd_context_t *ctx); mpd_uint_t mpd_abs_uint(const mpd_t *a, mpd_context_t *ctx); int32_t mpd_get_i32(const mpd_t *a, mpd_context_t *ctx); uint32_t mpd_get_u32(const mpd_t *a, mpd_context_t *ctx); #ifndef MPD_LEGACY_COMPILER int64_t mpd_get_i64(const mpd_t *a, mpd_context_t *ctx); uint64_t mpd_get_u64(const mpd_t *a, mpd_context_t *ctx); #endif void mpd_and(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx); void mpd_copy(mpd_t *result, const mpd_t *a, mpd_context_t *ctx); void mpd_canonical(mpd_t *result, const mpd_t *a, mpd_context_t *ctx); void mpd_copy_abs(mpd_t *result, const mpd_t *a, mpd_context_t *ctx); void mpd_copy_negate(mpd_t *result, const mpd_t *a, mpd_context_t *ctx); void mpd_copy_sign(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx); void mpd_invert(mpd_t *result, const mpd_t *a, mpd_context_t *ctx); void mpd_logb(mpd_t *result, const mpd_t *a, mpd_context_t *ctx); void mpd_or(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx); void mpd_rotate(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx); void mpd_scaleb(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx); void mpd_shiftl(mpd_t *result, const mpd_t *a, mpd_ssize_t n, mpd_context_t *ctx); mpd_uint_t mpd_shiftr(mpd_t *result, const mpd_t *a, mpd_ssize_t n, mpd_context_t *ctx); void mpd_shiftn(mpd_t *result, const mpd_t *a, mpd_ssize_t n, mpd_context_t *ctx); void mpd_shift(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx); void mpd_xor(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx); void mpd_abs(mpd_t *result, const mpd_t *a, mpd_context_t *ctx); int mpd_cmp(const mpd_t *a, const mpd_t *b, mpd_context_t *ctx); int mpd_compare(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx); int mpd_compare_signal(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx); void mpd_add(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx); void mpd_add_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b, mpd_context_t *ctx); void mpd_add_i32(mpd_t *result, const mpd_t *a, int32_t b, mpd_context_t *ctx); void mpd_add_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b, mpd_context_t *ctx); void mpd_add_u32(mpd_t *result, const mpd_t *a, uint32_t b, mpd_context_t *ctx); void mpd_sub(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx); void mpd_sub_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b, mpd_context_t *ctx); void mpd_sub_i32(mpd_t *result, const mpd_t *a, int32_t b, mpd_context_t *ctx); void mpd_sub_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b, mpd_context_t *ctx); void mpd_sub_u32(mpd_t *result, const mpd_t *a, uint32_t b, mpd_context_t *ctx); void mpd_div(mpd_t *q, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx); void mpd_div_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b, mpd_context_t *ctx); void mpd_div_i32(mpd_t *result, const mpd_t *a, int32_t b, mpd_context_t *ctx); void mpd_div_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b, mpd_context_t *ctx); void mpd_div_u32(mpd_t *result, const mpd_t *a, uint32_t b, mpd_context_t *ctx); void mpd_divmod(mpd_t *q, mpd_t *r, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx); void mpd_divint(mpd_t *q, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx); void mpd_exp(mpd_t *result, const mpd_t *a, mpd_context_t *ctx); void mpd_fma(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_t *c, mpd_context_t *ctx); void mpd_ln(mpd_t *result, const mpd_t *a, mpd_context_t *ctx); void mpd_log10(mpd_t *result, const mpd_t *a, mpd_context_t *ctx); void mpd_max(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx); void mpd_max_mag(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx); void mpd_min(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx); void mpd_min_mag(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx); void mpd_minus(mpd_t *result, const mpd_t *a, mpd_context_t *ctx); void mpd_mul(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx); void mpd_mul_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b, mpd_context_t *ctx); void mpd_mul_i32(mpd_t *result, const mpd_t *a, int32_t b, mpd_context_t *ctx); void mpd_mul_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b, mpd_context_t *ctx); void mpd_mul_u32(mpd_t *result, const mpd_t *a, uint32_t b, mpd_context_t *ctx); void mpd_next_minus(mpd_t *result, const mpd_t *a, mpd_context_t *ctx); void mpd_next_plus(mpd_t *result, const mpd_t *a, mpd_context_t *ctx); void mpd_next_toward(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx); void mpd_plus(mpd_t *result, const mpd_t *a, mpd_context_t *ctx); void mpd_pow(mpd_t *result, const mpd_t *base, const mpd_t *exp, mpd_context_t *ctx); void mpd_powmod(mpd_t *result, const mpd_t *base, const mpd_t *exp, const mpd_t *mod, mpd_context_t *ctx); void mpd_quantize(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx); void mpd_rescale(mpd_t *result, const mpd_t *a, mpd_ssize_t exp, mpd_context_t *ctx); void mpd_reduce(mpd_t *result, const mpd_t *a, mpd_context_t *ctx); void mpd_rem(mpd_t *r, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx); void mpd_rem_near(mpd_t *r, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx); void mpd_round_to_intx(mpd_t *result, const mpd_t *a, mpd_context_t *ctx); void mpd_round_to_int(mpd_t *result, const mpd_t *a, mpd_context_t *ctx); void mpd_trunc(mpd_t *result, const mpd_t *a, mpd_context_t *ctx); void mpd_floor(mpd_t *result, const mpd_t *a, mpd_context_t *ctx); void mpd_ceil(mpd_t *result, const mpd_t *a, mpd_context_t *ctx); void mpd_sqrt(mpd_t *result, const mpd_t *a, mpd_context_t *ctx); void mpd_invroot(mpd_t *result, const mpd_t *a, mpd_context_t *ctx); #ifndef MPD_LEGACY_COMPILER void mpd_add_i64(mpd_t *result, const mpd_t *a, int64_t b, mpd_context_t *ctx); void mpd_add_u64(mpd_t *result, const mpd_t *a, uint64_t b, mpd_context_t *ctx); void mpd_sub_i64(mpd_t *result, const mpd_t *a, int64_t b, mpd_context_t *ctx); void mpd_sub_u64(mpd_t *result, const mpd_t *a, uint64_t b, mpd_context_t *ctx); void mpd_div_i64(mpd_t *result, const mpd_t *a, int64_t b, mpd_context_t *ctx); void mpd_div_u64(mpd_t *result, const mpd_t *a, uint64_t b, mpd_context_t *ctx); void mpd_mul_i64(mpd_t *result, const mpd_t *a, int64_t b, mpd_context_t *ctx); void mpd_mul_u64(mpd_t *result, const mpd_t *a, uint64_t b, mpd_context_t *ctx); #endif /******************************************************************************/ /* Configuration specific */ /******************************************************************************/ #ifdef MPD_CONFIG_64 void mpd_qsset_i64(mpd_t *result, int64_t a, const mpd_context_t *ctx, uint32_t *status); void mpd_qsset_u64(mpd_t *result, uint64_t a, const mpd_context_t *ctx, uint32_t *status); void mpd_sset_i64(mpd_t *result, int64_t a, mpd_context_t *ctx); void mpd_sset_u64(mpd_t *result, uint64_t a, mpd_context_t *ctx); #endif /******************************************************************************/ /* Get attributes of a decimal */ /******************************************************************************/ mpd_ssize_t mpd_adjexp(const mpd_t *dec); mpd_ssize_t mpd_etiny(const mpd_context_t *ctx); mpd_ssize_t mpd_etop(const mpd_context_t *ctx); mpd_uint_t mpd_msword(const mpd_t *dec); int mpd_word_digits(mpd_uint_t word); /* most significant digit of a word */ mpd_uint_t mpd_msd(mpd_uint_t word); /* least significant digit of a word */ mpd_uint_t mpd_lsd(mpd_uint_t word); /* coefficient size needed to store 'digits' */ mpd_ssize_t mpd_digits_to_size(mpd_ssize_t digits); /* number of digits in the exponent, undefined for MPD_SSIZE_MIN */ int mpd_exp_digits(mpd_ssize_t exp); int mpd_iscanonical(const mpd_t *dec); int mpd_isfinite(const mpd_t *dec); int mpd_isinfinite(const mpd_t *dec); int mpd_isinteger(const mpd_t *dec); int mpd_isnan(const mpd_t *dec); int mpd_isnegative(const mpd_t *dec); int mpd_ispositive(const mpd_t *dec); int mpd_isqnan(const mpd_t *dec); int mpd_issigned(const mpd_t *dec); int mpd_issnan(const mpd_t *dec); int mpd_isspecial(const mpd_t *dec); int mpd_iszero(const mpd_t *dec); /* undefined for special numbers */ int mpd_iszerocoeff(const mpd_t *dec); int mpd_isnormal(const mpd_t *dec, const mpd_context_t *ctx); int mpd_issubnormal(const mpd_t *dec, const mpd_context_t *ctx); /* odd word */ int mpd_isoddword(mpd_uint_t word); /* odd coefficient */ int mpd_isoddcoeff(const mpd_t *dec); /* odd decimal, only defined for integers */ int mpd_isodd(const mpd_t *dec); /* even decimal, only defined for integers */ int mpd_iseven(const mpd_t *dec); /* 0 if dec is positive, 1 if dec is negative */ uint8_t mpd_sign(const mpd_t *dec); /* 1 if dec is positive, -1 if dec is negative */ int mpd_arith_sign(const mpd_t *dec); long mpd_radix(void); int mpd_isdynamic(const mpd_t *dec); int mpd_isstatic(const mpd_t *dec); int mpd_isdynamic_data(const mpd_t *dec); int mpd_isstatic_data(const mpd_t *dec); int mpd_isshared_data(const mpd_t *dec); int mpd_isconst_data(const mpd_t *dec); mpd_ssize_t mpd_trail_zeros(const mpd_t *dec); /******************************************************************************/ /* Set attributes of a decimal */ /******************************************************************************/ /* set number of decimal digits in the coefficient */ void mpd_setdigits(mpd_t *result); void mpd_set_sign(mpd_t *result, uint8_t sign); /* copy sign from another decimal */ void mpd_signcpy(mpd_t *result, const mpd_t *a); void mpd_set_infinity(mpd_t *result); void mpd_set_qnan(mpd_t *result); void mpd_set_snan(mpd_t *result); void mpd_set_negative(mpd_t *result); void mpd_set_positive(mpd_t *result); void mpd_set_dynamic(mpd_t *result); void mpd_set_static(mpd_t *result); void mpd_set_dynamic_data(mpd_t *result); void mpd_set_static_data(mpd_t *result); void mpd_set_shared_data(mpd_t *result); void mpd_set_const_data(mpd_t *result); void mpd_clear_flags(mpd_t *result); void mpd_set_flags(mpd_t *result, uint8_t flags); void mpd_copy_flags(mpd_t *result, const mpd_t *a); /******************************************************************************/ /* Error Macros */ /******************************************************************************/ #define mpd_err_fatal(...) \ do {fprintf(stderr, "%s:%d: error: ", __FILE__, __LINE__); \ fprintf(stderr, __VA_ARGS__); fputc('\n', stderr); \ abort(); \ } while (0) #define mpd_err_warn(...) \ do {fprintf(stderr, "%s:%d: warning: ", __FILE__, __LINE__); \ fprintf(stderr, __VA_ARGS__); fputc('\n', stderr); \ } while (0) /******************************************************************************/ /* Memory handling */ /******************************************************************************/ extern void *(* mpd_mallocfunc)(size_t size); extern void *(* mpd_callocfunc)(size_t nmemb, size_t size); extern void *(* mpd_reallocfunc)(void *ptr, size_t size); extern void (* mpd_free)(void *ptr); void *mpd_callocfunc_em(size_t nmemb, size_t size); void *mpd_alloc(mpd_size_t nmemb, mpd_size_t size); void *mpd_calloc(mpd_size_t nmemb, mpd_size_t size); void *mpd_realloc(void *ptr, mpd_size_t nmemb, mpd_size_t size, uint8_t *err); void *mpd_sh_alloc(mpd_size_t struct_size, mpd_size_t nmemb, mpd_size_t size); mpd_t *mpd_qnew(void); mpd_t *mpd_new(mpd_context_t *ctx); mpd_t *mpd_qnew_size(mpd_ssize_t nwords); void mpd_del(mpd_t *dec); void mpd_uint_zero(mpd_uint_t *dest, mpd_size_t len); int mpd_qresize(mpd_t *result, mpd_ssize_t nwords, uint32_t *status); int mpd_qresize_zero(mpd_t *result, mpd_ssize_t nwords, uint32_t *status); void mpd_minalloc(mpd_t *result); int mpd_resize(mpd_t *result, mpd_ssize_t nwords, mpd_context_t *ctx); int mpd_resize_zero(mpd_t *result, mpd_ssize_t nwords, mpd_context_t *ctx); #ifdef __cplusplus } /* END extern "C" */ #endif #endif /* LIBMPDEC_MPDECIMAL_H_ */
0
repos/zig_demoJson/library
repos/zig_demoJson/library/lib/regPcre2.h
#include <pcre2posix.h> #include <stdbool.h> bool isMatch(regex_t *re, char const *input) { regmatch_t pmatch[0]; return pcre2_regexec(re, input, 0, pmatch, 0) == 0; }
0
repos/zig_demoJson/library
repos/zig_demoJson/library/mmap/zmmap.zig
///----------------------- /// gestion file mmap /// emulation *LDA IBM /// zig 0.12.0 dev ///----------------------- const std = @import("std"); const cry = @import("crypto"); const fs = std.fs; const allocZmmap = std.heap.page_allocator; //----------------------- // crypto //----------------------- pub const Aes256Gcm = cry.AesGcm(std.crypto.core.aes.Aes256); // key and nonce crypto // var key: [Aes256Gcm.key_length]u8 = undefined; // len 32 // var nonce: [Aes256Gcm.nonce_length]u8 = undefined; // len 12 // var tag: [Aes256Gcm.tag_length]u8 = undefined; // len 16 var dta: []const u8 = undefined; // data crypter var cipher: []u8 = undefined; var decipher: []u8 = undefined; //----------------------- var mmapOK : bool = false; var echoOK : bool = false; const dirfile = "./qtemp"; var cDIR = std.fs.cwd(); // name seq = times var parmTimes: [] const u8 = undefined; var ztext : [:0]u8 = undefined ; var zcrpt : [:0]u8 = undefined ; //================================================== const ZMMAP = struct { fileKEY : []const u8 , fileNONCE : []const u8 , fileTAG : []const u8 , fileUDS : []const u8 , fileLOG : []const u8 , ZKEY :fs.File , ZNONCE :fs.File , ZTAG :fs.File , ZUDS :fs.File , ZLOG :fs.File , key: [Aes256Gcm.key_length]u8 , // len 32 nonce: [Aes256Gcm.nonce_length]u8 , // len 12 tag: [Aes256Gcm.tag_length]u8 , // len 16 }; var COM : ZMMAP = undefined ; var SAVCOM : ZMMAP = undefined; var sav_parmTimes: [] const u8 = undefined; var sav_mmapOK : bool = false ; var sav_echoOK : bool = false ; pub fn savEnvMmap() void { SAVCOM = COM ; sav_mmapOK = mmapOK; sav_echoOK = echoOK; sav_parmTimes = parmTimes; COM = undefined ; mmapOK = false; echoOK = false; } pub fn rstEnvMmap() void { released(); COM = SAVCOM ; mmapOK = sav_mmapOK; echoOK = sav_echoOK; parmTimes = sav_parmTimes ; SAVCOM = undefined ; sav_mmapOK = false; sav_echoOK = false; sav_parmTimes = undefined; } //================================================== pub const COMLDA = struct { reply : bool , abort : bool , user : [] const u8 , init : [] const u8 , echo : [] const u8 , // alpha numeric zuds : [] const u8 , }; var LDA : COMLDA = undefined; fn initLDA() void { LDA = COMLDA{ .reply = true , .abort = false, .user = undefined , .init = undefined , .echo = undefined , // alpha numeric .zuds = undefined , }; LDA.user = std.posix.getenv("USER") orelse "INITLDA"; } //------------------------------------------- // create communication this file MAP //------------------------------------------- fn setNameFile() void { COM.fileKEY = std.fmt.allocPrintZ(allocZmmap,"KEY{s}" ,.{parmTimes}) catch unreachable; COM.fileNONCE = std.fmt.allocPrintZ(allocZmmap,"NONCE{s}" ,.{parmTimes}) catch unreachable; COM.fileTAG = std.fmt.allocPrintZ(allocZmmap,"TAG{s}" ,.{parmTimes}) catch unreachable; COM.fileUDS = std.fmt.allocPrintZ(allocZmmap,"UDS{s}" ,.{parmTimes}) catch unreachable; COM.fileLOG = std.fmt.allocPrintZ(allocZmmap,"LOG{s}" ,.{parmTimes}) catch unreachable; } fn creatFileMMAP() void { const timesStamp_ms: u64 = @bitCast(std.time.milliTimestamp()); parmTimes = std.fmt.allocPrintZ(allocZmmap,"{d}" ,.{std.fmt.fmtIntSizeDec(timesStamp_ms)}) catch unreachable; setNameFile(); cDIR = std.fs.cwd().openDir(dirfile,.{}) catch unreachable; COM.ZKEY = cDIR.createFile(COM.fileKEY , .{ .read = true, .truncate =true , .exclusive = false}) catch |e| @panic(std.fmt.allocPrint(allocZmmap,"err isFile Open CREAT FILEKEY .{any}\n", .{e}) catch unreachable); // ZKEY.close(); COM.ZNONCE = cDIR.createFile(COM.fileNONCE , .{ .read = true, .truncate =true , .exclusive = false}) catch |e| @panic(std.fmt.allocPrint(allocZmmap,"err isFile Open CREAT FILENONCE .{any}\n", .{e}) catch unreachable); // ZNONCE.close(); COM.ZTAG = cDIR.createFile(COM.fileTAG , .{ .read = true, .truncate =true , .exclusive = false}) catch |e| @panic(std.fmt.allocPrint(allocZmmap,"err isFile Open CREAT FILETAG .{any}\n", .{e}) catch unreachable); // ZTAG.close(); COM.ZUDS = cDIR.createFile(COM.fileUDS , .{ .read = true, .truncate =true , .exclusive = false}) catch |e| @panic(std.fmt.allocPrint(allocZmmap,"err isFile Open CREAT FILEUDS .{any}\n", .{e}) catch unreachable); // ZUDS.close(); COM.ZLOG = cDIR.createFile(COM.fileLOG , .{ .read = true, .truncate =true , .exclusive = false}) catch |e| @panic(std.fmt.allocPrint(allocZmmap,"err isFile Open CREAT FILELOG .{any}\n", .{e}) catch unreachable); // ZLOG.close(); } fn setOpenFile() void { setNameFile(); cDIR = std.fs.cwd().openDir(dirfile,.{}) catch unreachable; COM.ZKEY = cDIR.openFile(COM.fileKEY , .{.mode=.read_write}) catch |e| { @panic(std.fmt.allocPrint(allocZmmap,"\n{any} mmap fileKEY error open {s}\n",.{e,COM.fileKEY }) catch unreachable); }; COM.ZNONCE = cDIR.openFile(COM.fileNONCE , .{.mode=.read_write}) catch |e| { @panic(std.fmt.allocPrint(allocZmmap,"\n{any} mmap fileNONCE error open {s}\n",.{e,COM.fileNONCE }) catch unreachable); }; COM.ZTAG = cDIR.openFile(COM.fileTAG , .{.mode=.read_write}) catch |e| { @panic(std.fmt.allocPrint(allocZmmap,"\n{any} mmap fileTAG error open {s}\n",.{e,COM.fileTAG }) catch unreachable); }; COM.ZUDS = cDIR.openFile(COM.fileUDS , .{.mode=.read_write}) catch |e| { @panic(std.fmt.allocPrint(allocZmmap,"\n{any} mmap fileUDS error open {s}\n",.{e,COM.fileUDS }) catch unreachable); }; COM.ZLOG = cDIR.openFile(COM.fileLOG , .{.mode=.read_write}) catch |e| { @panic(std.fmt.allocPrint(allocZmmap,"\n{any} mmap fileLOG error open {s}\n",.{e,COM.fileLOG }) catch unreachable); }; } //-------------------------- // READ TAsG //-------------------------- fn readTAG() void { var zlen :usize = COM.ZTAG.getEndPos() catch unreachable; const rcvtag = std.posix.mmap( null, @sizeOf(u8) * zlen , std.posix.PROT.READ | std.posix.PROT.WRITE, .{.TYPE =.SHARED_VALIDATE} , COM.ZTAG.handle, 0 ) catch @panic(" violation intégrité readTAG rcvtag ") ; // si pblm violation intégrité defer std.posix.munmap(rcvtag); var ztag: [:0]u8 = undefined ; ztag = std.fmt.allocPrintZ(allocZmmap,"{s}",.{rcvtag}) catch unreachable; defer allocZmmap.free(ztag); zlen = ztag.len; for ( 0.. COM.tag.len - 1) |x| {COM.tag[x]= 0; } var it = std.mem.splitScalar(u8, ztag[0..zlen], '|'); var i : usize = 0; while (it.next()) |chunk| :( i += 1) { COM.tag[i] = std.fmt.parseInt(u8,chunk,10) catch unreachable; } } //-------------------------- // WRITE TAG //-------------------------- fn writeTAG() void { const ztag :[:0]u8 = std.fmt.allocPrintZ(allocZmmap, "{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}" ,.{ COM.tag[0],COM.tag[1],COM.tag[2],COM.tag[3],COM.tag[4], COM.tag[5],COM.tag[6],COM.tag[7],COM.tag[8],COM.tag[9], COM.tag[10],COM.tag[11],COM.tag[12],COM.tag[13],COM.tag[14],COM.tag[15], }) catch unreachable; defer allocZmmap.free(ztag); COM.ZTAG.setEndPos(ztag.len) catch unreachable; const sendtag = std.posix.mmap( null, @sizeOf(u8) * ztag.len, std.posix.PROT.READ | std.posix.PROT.WRITE, .{.TYPE =.SHARED_VALIDATE} , COM.ZTAG.handle, 0 ) catch @panic(" violation intégrité zmmap writeTAG") ; // si pblm violation intégrité defer std.posix.munmap(sendtag); std.mem.copyForwards(u8, sendtag,ztag); } //=========================================================================== //------------------------------------------- // name file mmap //------------------------------------------- // name file / mmap pub fn getParm() [] const u8 { return parmTimes;} // read DATAAREA LDA pub fn getLDA() COMLDA { return LDA;} //------------------------------------------- // isFile //------------------------------------------- fn isFile(name: []const u8 ) bool { var file = cDIR.createFile(name, .{ .read = true }) catch |e| switch (e) { error.PathAlreadyExists => return true, else =>return false, }; defer file.close(); return true; } //------------------------------------------- //restore base null //------------------------------------------- // released acces initMmap for new communication pub fn released() void { if (mmapOK == false) return; COM.ZKEY.close(); if ( isFile(COM.fileKEY) ) cDIR.deleteFile(COM.fileKEY) catch unreachable; COM.ZNONCE.close(); if ( isFile(COM.fileNONCE) ) cDIR.deleteFile(COM.fileNONCE) catch unreachable; COM.ZTAG.close(); cDIR.deleteFile(COM.fileTAG) catch unreachable; COM.ZLOG.close(); cDIR.deleteFile(COM.fileLOG) catch unreachable; COM.ZUDS.close(); cDIR.deleteFile(COM.fileUDS) catch unreachable; initLDA(); mmapOK = false; echoOK = false; } //=========================================================================== //------------------------------------------- // init Maitre //------------------------------------------- pub fn masterMmap() ! COMLDA { if (mmapOK == true ) @panic(std.fmt.allocPrintZ(allocZmmap,"process already initalized",.{}) catch unreachable); COM = undefined ; creatFileMMAP(); //---------------------------- // KEY //---------------------------- for ( 0.. COM.key.len - 1) |x| { COM.key[x]= 0; } std.crypto.random.bytes(&COM.key); const zkey :[:0]u8 = std.fmt.allocPrintZ(allocZmmap, "{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}" ,.{ COM.key[0],COM.key[1],COM.key[2],COM.key[3],COM.key[4],COM.key[5],COM.key[6], COM.key[7],COM.key[8],COM.key[9], COM.key[10],COM.key[11],COM.key[12],COM.key[13],COM.key[14],COM.key[15],COM.key[16], COM.key[17],COM.key[18],COM.key[19], COM.key[20],COM.key[21],COM.key[22],COM.key[23],COM.key[24],COM.key[25],COM.key[26], COM.key[27],COM.key[28],COM.key[29], COM.key[30],COM.key[31], }) catch unreachable; defer allocZmmap.free(zkey); COM.ZKEY.setEndPos(zkey.len) catch unreachable; const sendkey = std.posix.mmap( null, @sizeOf(u8) * zkey.len, std.posix.PROT.READ | std.posix.PROT.WRITE, .{.TYPE =.SHARED_VALIDATE} , COM.ZKEY.handle, 0 ) catch @panic(" violation intégrité initMAP fileKEY") ; defer std.posix.munmap(sendkey); std.mem.copyForwards(u8, sendkey,zkey); //---------------------------- // NONCE //---------------------------- for ( 0.. COM.nonce.len - 1) |x| { COM.nonce[x]= 0; } std.crypto.random.bytes(&COM.nonce); const znonce :[:0]u8 = std.fmt.allocPrintZ(allocZmmap, "{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}" ,.{ COM.nonce[0],COM.nonce[1],COM.nonce[2],COM.nonce[3],COM.nonce[4], COM.nonce[5],COM.nonce[6],COM.nonce[7],COM.nonce[8],COM.nonce[9], COM.nonce[10],COM.nonce[11], }) catch unreachable; defer allocZmmap.free(znonce); COM.ZNONCE.setEndPos(znonce.len) catch unreachable; const sendnonce = std.posix.mmap( null, @sizeOf(u8) * znonce.len, std.posix.PROT.READ | std.posix.PROT.WRITE, .{.TYPE =.SHARED_VALIDATE} , COM.ZNONCE.handle, 0 ) catch @panic(" violation intégrité initMAP fileNONCE") ; defer std.posix.munmap(sendnonce); std.mem.copyForwards(u8, sendnonce,znonce); //---------------------------- // TAG //---------------------------- for ( 0.. COM.tag.len - 1) |x| { COM.tag[x]= 0; } const ztag :[:0]u8 = std.fmt.allocPrintZ(allocZmmap, "{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}|{d}" ,.{ COM.tag[0],COM.tag[1],COM.tag[2],COM.tag[3],COM.tag[4], COM.tag[5],COM.tag[6],COM.tag[7],COM.tag[8],COM.tag[9], COM.tag[10],COM.tag[11],COM.tag[12],COM.tag[13],COM.tag[14],COM.tag[15], }) catch unreachable; defer allocZmmap.free(ztag); COM.ZTAG.setEndPos(ztag.len) catch unreachable; const sendtag = std.posix.mmap( null, @sizeOf(u8) * ztag.len, std.posix.PROT.READ | std.posix.PROT.WRITE, .{.TYPE =.SHARED_VALIDATE} , COM.ZTAG.handle, 0 ) catch @panic(" violation intégrité initMAP fileTAG") ; defer std.posix.munmap(sendtag); std.mem.copyForwards(u8, sendtag,ztag); //------------------------------------------- // init parameter LDA //------------------------------------------- initLDA(); mmapOK = true ; return LDA; } //------------------------------------------- // init ECHO //------------------------------------------- pub fn echoMmap(timesParm : [] const u8 ) !COMLDA { if (mmapOK == true ) @panic(std.fmt.allocPrintZ(allocZmmap,"process already initalized",.{}) catch unreachable); if (echoOK == true ) @panic(std.fmt.allocPrintZ(allocZmmap,"process already initalized",.{}) catch unreachable); parmTimes = std.fmt.allocPrintZ(allocZmmap,"{s}" ,.{timesParm}) catch unreachable; COM = undefined ; setOpenFile(); //-------------------------- // recover KEY //-------------------------- var zlen :usize = COM.ZKEY.getEndPos() catch unreachable; const rcvkey = std.posix.mmap( null, @sizeOf(u8) * zlen, std.posix.PROT.READ | std.posix.PROT.WRITE, .{.TYPE =.SHARED_VALIDATE} , COM.ZKEY.handle, 0 ) catch @panic(" violation intégrité echoMAP fileKEY") ; defer std.posix.munmap(rcvkey); for ( 0.. COM.key.len - 1) |x| {COM.key[x]= 0; } var ita = std.mem.splitScalar(u8, rcvkey[0..zlen], '|'); var i : usize = 0; while (ita.next()) |chunk| :( i += 1) { COM.key[i] = std.fmt.parseInt(u8,chunk,10) catch unreachable; } //-------------------------- // recover NONCE //-------------------------- zlen = COM.ZNONCE.getEndPos() catch unreachable; const rcvnonce = std.posix.mmap( null, @sizeOf(u8) * zlen, std.posix.PROT.READ | std.posix.PROT.WRITE, .{.TYPE =.SHARED_VALIDATE} , COM.ZNONCE.handle, 0 ) catch @panic(" violation intégrité echoMAP fileZNONCE") ; defer std.posix.munmap(rcvnonce); for ( 0.. COM.nonce.len - 1) |x| { COM.nonce[x]= 0; } var itb = std.mem.splitScalar(u8, rcvnonce[0..zlen], '|'); i = 0; while (itb.next()) |chunk| :( i += 1) { COM.nonce[i] = std.fmt.parseInt(u8,chunk,10) catch unreachable; } //-------------------------- // recover TAG //-------------------------- zlen = COM.ZTAG.getEndPos() catch unreachable; const rcvtag = std.posix.mmap( null, @sizeOf(u8) * zlen, std.posix.PROT.READ | std.posix.PROT.WRITE, .{.TYPE =.SHARED_VALIDATE} , COM.ZTAG.handle, 0 ) catch @panic(" violation intégrité echoMAP fileZNONCE") ; defer std.posix.munmap(rcvtag); for ( 0.. COM.tag.len - 1) |x| { COM.tag[x]= 0; } var itc = std.mem.splitScalar(u8, rcvtag[0..zlen], '|'); i = 0; while (itc.next()) |chunk| :( i += 1) { COM.tag[i] = std.fmt.parseInt(u8,chunk,10) catch unreachable; } //------------------------------------------- // cleaner //------------------------------------------- COM.ZKEY.close(); cDIR.deleteFile(COM.fileKEY) catch unreachable; COM.ZNONCE.close(); cDIR.deleteFile(COM.fileNONCE) catch unreachable; initLDA(); mmapOK = true; echoOK = true; return LDA; } //------------------------------------------- pub fn writeLDA( vLDA:*COMLDA) void { if (mmapOK == false) @panic(std.fmt.allocPrintZ(allocZmmap,"process not initalized",.{}) catch unreachable); //-------------------------------------------------------- // reply = true return message // reply = false return not found answer // abort = true caller exit not reply //-------------------------------------------------------- ztext = undefined; ztext = std.fmt.allocPrintZ(allocZmmap, "{}|{}|{s}|{s}|{s}" ,.{ vLDA.reply, vLDA.abort, vLDA.user, vLDA.init, vLDA.echo, }) catch |err| @panic(std.fmt.allocPrintZ(allocZmmap,"{}",.{err}) catch unreachable); defer allocZmmap.free(ztext); COM.ZLOG.setEndPos(ztext.len) catch unreachable; const sendlog = std.posix.mmap( null, @sizeOf(u8) * ztext.len, std.posix.PROT.READ | std.posix.PROT.WRITE, .{.TYPE =.SHARED_VALIDATE} , COM.ZLOG.handle, 0 ) catch |err| @panic(std.fmt.allocPrintZ(allocZmmap,"{}",.{err}) catch unreachable); defer std.posix.munmap(sendlog); // Write file via mmap std.mem.copyForwards(u8, sendlog,ztext); // ------------------------------------------------- // crypt for ( 0.. COM.tag.len - 1) |x| { COM.tag[x]= 0; } cipher = undefined; cipher = std.mem.Allocator.alloc(allocZmmap,u8,vLDA.zuds.len) catch unreachable; Aes256Gcm.encrypt(cipher, &COM.tag, vLDA.zuds, COM.nonce, COM.key); defer allocZmmap.free(cipher); COM.ZUDS.setEndPos(cipher.len) catch unreachable; const senduds = std.posix.mmap( null, @sizeOf(u8) * cipher.len, std.posix.PROT.READ | std.posix.PROT.WRITE, .{.TYPE =.SHARED_VALIDATE} , COM.ZUDS.handle, 0 ) catch |err| @panic(std.fmt.allocPrintZ(allocZmmap,"{}",.{err}) catch unreachable); defer std.posix.munmap(senduds); // Write file via mmap std.mem.copyForwards(u8, senduds,cipher); writeTAG(); } //------------------------------------------- // Read LDA //------------------------------------------- pub fn readLDA() COMLDA { if (mmapOK == false) @panic(std.fmt.allocPrintZ(allocZmmap,"process not initalised",.{}) catch unreachable); var zlen :usize = COM.ZLOG.getEndPos() catch unreachable; const rcvlog = std.posix.mmap( null, @sizeOf(u8) * zlen , std.posix.PROT.READ | std.posix.PROT.WRITE, .{.TYPE =.SHARED_VALIDATE} , COM.ZLOG.handle, 0 ) catch |err| @panic(std.fmt.allocPrintZ(allocZmmap,"{}",.{err}) catch unreachable); defer std.posix.munmap(rcvlog); var it = std.mem.splitScalar(u8, rcvlog, '|'); var i: usize = 0; while (it.next()) |chunk| :( i += 1) { switch(i) { 0 =>{ if (std.mem.eql(u8,chunk, "true")) LDA.reply = true else LDA.reply = false; }, 1 =>{ if (std.mem.eql(u8,chunk, "true")) LDA.abort = true else LDA.abort = false; }, 2 => LDA.user = std.fmt.allocPrintZ(allocZmmap,"{s}",.{chunk}) catch unreachable, 3 => LDA.init = std.fmt.allocPrintZ(allocZmmap,"{s}",.{chunk}) catch unreachable, 4 => LDA.echo = std.fmt.allocPrintZ(allocZmmap,"{s}",.{chunk}) catch unreachable, else => continue, } } //-------------------------- // read data //-------------------------- zlen = COM.ZUDS.getEndPos() catch unreachable; const rcvuds = std.posix.mmap( null, @sizeOf(u8) * zlen , std.posix.PROT.READ | std.posix.PROT.WRITE, .{.TYPE =.SHARED_VALIDATE} , COM.ZUDS.handle, 0 ) catch |err| @panic(std.fmt.allocPrintZ(allocZmmap,"{}",.{err}) catch unreachable); defer std.posix.munmap(rcvuds); readTAG(); zlen = rcvuds.len; decipher = undefined; decipher = std.mem.Allocator.alloc(allocZmmap,u8,zlen) catch unreachable; defer allocZmmap.free(decipher); Aes256Gcm.decrypt(rcvuds, COM.tag, decipher, COM.nonce, COM.key) catch |err| @panic(std.fmt.allocPrintZ(allocZmmap,"{}",.{err}) catch unreachable); LDA.zuds = undefined; LDA.zuds = std.fmt.allocPrint(allocZmmap,"{s}",.{decipher[0..zlen]}) catch unreachable; return LDA; }
0
repos/zig_demoJson/library
repos/zig_demoJson/library/curse/utils.zig
///---------------------- /// boite à outils /// zig 0.12.0 dev ///---------------------- const std = @import("std"); const utf = @import("std").unicode; // display grid pub const CTRUE = "✔"; pub const CFALSE = " "; pub const CMP = enum { LT, EQ, GT }; pub const ALIGNS = enum { left, rigth }; ///------------------------------------ /// utility ///------------------------------------ //free memory var arenaUtl = std.heap.ArenaAllocator.init(std.heap.page_allocator); pub var allocUtl = arenaUtl.allocator(); pub fn deinitUtl() void { arenaUtl.deinit(); arenaUtl = std.heap.ArenaAllocator.init(std.heap.page_allocator); allocUtl = arenaUtl.allocator(); } /// Errors that may occur when using String pub const ErrUtils = error{char_not_digital_invalide}; pub fn strToUint(str: []const u8) usize { if (str.len == 0) return 0; var digit: [1][]u8 = undefined; var buffer: [100]u8 = [_]u8{0} ** 100; digit[0] = std.fmt.bufPrint(buffer[0..], "{s}", .{str}) catch |err| { @panic(@errorName(err)); }; for (digit, 0..) |d, idx| { if (!std.ascii.isDigit(d[idx])) { @panic(@errorName(ErrUtils.char_not_digital_invalide)); } } return std.fmt.parseUnsigned(u64, str, 10) catch |err| { @panic(@errorName(err)); }; } pub fn UintToStr(v: usize) []const u8 { return std.fmt.allocPrint(allocUtl, "{d}", .{v}) catch |err| { @panic(@errorName(err)); }; } pub fn strToUsize(v: []const u8) usize { return std.fmt.parseUnsigned(u64, v, 10) catch |err| { @panic(@errorName(err)); }; } pub fn usizeToStr(v: usize) []const u8 { return std.fmt.allocPrint(allocUtl, "{d}", .{v}) catch |err| { @panic(@errorName(err)); }; } /// Iterator support iteration string pub const iteratStr = struct { var strbuf: []const u8 = undefined; /// Errors that may occur when using String pub const ErrNbrch = error{ InvalideAllocBuffer, }; pub const StringIterator = struct { buf: []u8, index: usize, fn allocBuffer(size: usize) ErrNbrch![]u8 { const buf = allocUtl.alloc(u8, size) catch { return ErrNbrch.InvalideAllocBuffer; }; return buf; } /// Deallocates the internal buffer pub fn deinit(self: *StringIterator) void { if (self.buf.len > 0) allocUtl.free(self.buf); strbuf = ""; } pub fn next(it: *StringIterator) ?[]const u8 { const optional_buf: ?[]u8 = allocBuffer(strbuf.len) catch return null; it.buf = optional_buf orelse ""; var idx: usize = 0; while (true) { if (idx >= strbuf.len) break; it.buf[idx] = strbuf[idx]; idx += 1; } if (it.index >= it.buf.len) return null; idx = it.index; it.index += getUTF8Size(it.buf[idx]); return it.buf[idx..it.index]; } pub fn preview(it: *StringIterator) ?[]const u8 { const optional_buf: ?[]u8 = allocBuffer(strbuf.len) catch return null; it.buf = optional_buf orelse ""; var idx: usize = 0; while (true) { if (idx >= strbuf.len) break; it.buf[idx] = strbuf[idx]; idx += 1; } if (it.index == 0) return null; idx = it.buf.len; it.index -= getUTF8Size(it.buf[idx]); return it.buf[idx..it.index]; } }; /// iterator String pub fn iterator(str: []const u8) StringIterator { strbuf = str; return StringIterator{ .buf = undefined, .index = 0, }; } /// Returns the UTF-8 character's size fn getUTF8Size(char: u8) u3 { return std.unicode.utf8ByteSequenceLength(char) catch |err| { @panic(@errorName(err)); }; } }; /// number characters String pub fn nbrCharStr(str: []const u8) usize { var wl : usize =0; var iter = iteratStr.iterator(str); defer iter.deinit(); while (iter.next()) |_| { wl += 1 ;} return wl; } /// remove espace to STRING left and rigth pub fn trimStr(str: []const u8) []const u8 { const val = std.mem.trim(u8, str, " "); return val; } /// is String isAlphabetic Latin pub fn isAlphabeticStr(str: []const u8) bool { const result = allocUtl.alloc(u8, str.len) catch |err| { @panic(@errorName(err)); }; defer allocUtl.free(result); std.mem.copy(u8, result, str); var idx: usize = 0; var b: bool = true; while (idx < result.len) : (idx += 1) { if (!std.ascii.isAlphabetic(result[idx])) b = false; } return b; } /// is String Upper Latin pub fn isUpperStr(str: []const u8) bool { const result = allocUtl.alloc(u8, str.len) catch |err| { @panic(@errorName(err)); }; defer allocUtl.free(result); std.mem.copy(u8, result, str); var idx: usize = 0; var b: bool = true; while (idx < result.len) : (idx += 1) { if (!std.ascii.isUpper(result[idx])) b = false; } return b; } /// is String Lower Latin pub fn isLowerStr(str: []const u8) bool { const result = allocUtl.alloc(u8, str.len) catch |err| { @panic(@errorName(err)); }; defer allocUtl.free(result); std.mem.copy(u8, result, str); var idx: usize = 0; var b: bool = true; while (idx < result.len) : (idx += 1) { if (!std.ascii.iLower(result[idx])) b = false; } return b; } /// is String isDigit pub fn isDigitStr(str: []const u8) bool { var iter = iteratStr.iterator(str); defer iter.deinit(); var b: bool = true; while (iter.next()) |ch| { const x = utf.utf8Decode(ch) catch |err| { @panic(@errorName(err)); }; switch (x) { '0'...'9' => continue, else => b = false, } } return b; } /// is String isDecimal pub fn isDecimalStr(str: []const u8) bool { var iter = iteratStr.iterator(str); defer iter.deinit(); var b: bool = true; var idx: usize = 0; var p: bool = false; // dot while (iter.next()) |ch| : (idx += 1) { const x = utf.utf8Decode(ch) catch |err| { @panic(@errorName(err)); }; switch (x) { '0'...'9' => continue, '.' => { if (p) b = false else { p = true; continue; } // control is . unique }, '-' => { if (idx == 0) continue else b = false; }, '+' => { if (idx == 0) continue else b = false; }, else => b = false, } } return b; } /// is String isDigit pub fn isSignedStr(str: []const u8) bool { var iter = iteratStr.iterator(std.mem.trim(u8, str, " ")); defer iter.deinit(); var b: bool = false; while (iter.next()) |ch| { const x = utf.utf8Decode(ch) catch |err| { @panic(@errorName(err)); }; switch (x) { '-' => b = true, '+' => b = true, else => b = false, } break; } return b; } /// is String isLetter /// testing caracter Keyboard 103 pub fn isLetterStr(str: []const u8) bool { var iter = iteratStr.iterator(str); defer iter.deinit(); var b: bool = true; while (iter.next()) |ch| { const x = utf.utf8Decode(ch) catch |err| { @panic(@errorName(err)); }; switch (x) { '0'...'9' => b = false, '&' => b = false, '¹' => b = false, '²' => b = false, '³' => b = false, '¼' => b = false, '½' => b = false, '¾' => b = false, '~' => b = false, '"' => b = false, '#' => b = false, '\'' => b = false, '{' => b = false, '(' => b = false, '[' => b = false, '-' => b = false, '|' => b = false, '`' => b = false, '_' => b = false, '\\' => b = false, '^' => b = false, '@' => b = false, '°' => b = false, ')' => b = false, ']' => b = false, '+' => b = false, '=' => b = false, '}' => b = false, '€' => b = false, '$' => b = false, '£' => b = false, '¢' => b = false, '¥' => b = false, 'þ' => b = false, '¨' => b = false, 'ø' => b = false, 'ß' => b = false, '‘' => b = false, '´' => b = false, '%' => b = false, 'µ' => b = false, '*' => b = false, '<' => b = false, '>' => b = false, '«' => b = false, '»' => b = false, '↕' => b = false, '↓' => b = false, '↑' => b = false, '←' => b = false, '→' => b = false, '↔' => b = false, '↙' => b = false, '↘' => b = false, '↖' => b = false, '↗' => b = false, '©' => b = false, '®' => b = false, '™' => b = false, '¬' => b = false, '¿' => b = false, '?' => b = false, ',' => b = false, '×' => b = false, '.' => b = false, ';' => b = false, '÷' => b = false, '/' => b = false, ':' => b = false, '¡' => b = false, '§' => b = false, '!' => b = false, else => {}, } } return b; } /// is String isSpecial // testing caracter Keyboard 103 // force omit ; csv pub fn isSpecialStr(str: []const u8) bool { var iter = iteratStr.iterator(str); defer iter.deinit(); var b: bool = true; while (iter.next()) |ch| { const x = utf.utf8Decode(ch) catch |err| { @panic(@errorName(err)); }; switch (x) { '&' => continue, '¹' => continue, '²' => continue, '³' => continue, '¼' => continue, '½' => continue, '¾' => continue, '#' => continue, '{' => continue, '(' => continue, '[' => continue, '-' => continue, '|' => continue, '\'' => continue, '@' => continue, '°' => continue, ')' => continue, ']' => continue, '+' => continue, '=' => continue, '}' => continue, '€' => continue, '$' => continue, '£' => continue, '¢' => continue, '¥' => continue, '%' => continue, '*' => continue, '¿' => continue, '?' => continue, ',' => continue, '.' => continue, '÷' => continue, '/' => continue, ':' => continue, '¡' => continue, '§' => continue, '!' => continue, '_' => continue, else => b = false, } } return b; } /// is String Punctuation /// force omit ' ; csv pub fn isPunct( str: []const u8, ) bool { var iter = iteratStr.iterator(str); defer iter.deinit(); var b: bool = true; while (iter.next()) |ch| { const x = utf.utf8Decode(ch) catch |err| { @panic(@errorName(err)); }; switch (x) { '.' => continue, ':' => continue, ',' => continue, '!' => continue, '-' => continue, '(' => continue, ')' => continue, '>' => continue, '<' => continue, '«' => continue, '»' => continue, '`' => continue, '/' => continue, '[' => continue, ']' => continue, else => b = false, } } return b; } /// is String omit char pub fn isCarOmit(str: []const u8) bool { var iter = iteratStr.iterator(str); defer iter.deinit(); var b: bool = true; while (iter.next()) |ch| { const x = utf.utf8Decode(ch) catch |err| { @panic(@errorName(err)); }; switch (x) { ';' => continue, '~' => continue, '|' => continue, '_' => continue, '"' => continue, '\'' => continue, '\\' => continue, else => b = false, } } return b; } /// is String to PASSWORD /// !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ /// omit , ; / \ _ ` | ~ pub fn isPassword(str: []const u8) bool { var iter = iteratStr.iterator(str); defer iter.deinit(); var b: bool = true; while (iter.next()) |ch| { const x = utf.utf8Decode(ch) catch |err| { @panic(@errorName(err)); }; switch (x) { '!' => continue, '#' => continue, '$' => continue, '%' => continue, '&' => continue, '(' => continue, ')' => continue, '*' => continue, '+' => continue, '-' => continue, '.' => continue, ':' => continue, '<' => continue, '=' => continue, '>' => continue, '?' => continue, '@' => continue, '[' => continue, ']' => continue, '^' => continue, '{' => continue, '}' => continue, else => { if (isLetterStr(ch)) continue; if (isDigitStr(ch)) continue; b = false; }, } } return b; } /// is String to Mail /// a-zA-Z 0-9 +.-_@ pub fn isMailStr(str: []const u8) bool { var iter = iteratStr.iterator(str); defer iter.deinit(); var b: bool = true; while (iter.next()) |ch| { const x = utf.utf8Decode(ch) catch |err| { @panic(@errorName(err)); }; switch (x) { '+' => continue, '-' => continue, '_' => continue, '.' => continue, '@' => continue, else => { if (x >= 191 and x <= 255) return false; if (isLetterStr(ch)) continue; if (isDigitStr(ch)) continue; b = false; }, } } return b; } /// upper-case String Latin pub fn upperStr(str: []const u8) []const u8 { const result = allocUtl.alloc(u8, str.len) catch |err| { @panic(@errorName(err)); }; defer allocUtl.free(result); @memcpy(result, str); var idx: usize = 0; while (idx < result.len) : (idx += 1) { result[idx] = std.ascii.toUpper(result[idx]); } return std.fmt.allocPrint( allocUtl, "{s}", .{result}, ) catch |err| { @panic(@errorName(err)); }; } /// Lower String Latin pub fn lowerStr(str: []const u8) []const u8 { const result = allocUtl.alloc(u8, str.len) catch |err| { @panic(@errorName(err)); }; defer allocUtl.free(result); std.mem.copy(u8, result, str); var idx: usize = 0; while (idx < result.len) : (idx += 1) { result[idx] = std.ascii.toLower(result[idx]); } return std.fmt.allocPrint( allocUtl, "{s}", .{result}, ) catch |err| { @panic(@errorName(err)); }; } /// concat String pub fn concatStr(a: []const u8, b: []const u8) []const u8 { return std.fmt.allocPrint( allocUtl, "{s}{s}", .{ a, b }, ) catch |err| { @panic(@errorName(err)); }; } /// comp string /// LT EQ GT -> enum CMP pub fn compStr(str1: []const u8, str2: []const u8) CMP { const c1 = std.fmt.count("{s}", .{str1}); const c2 = std.fmt.count("{s}", .{str2}); if (c1 > c2) return CMP.GT; if (c1 == c2) { var idx: u8 = 0; var n: i32 = 0; while (idx < c1) : (idx += 1) { if (str1[idx] < str2[idx]) n -= 1; if (str1[idx] > str2[idx]) n += 1; } if (n < 0) return CMP.LT; if (n > 0) return CMP.GT else return CMP.EQ; } return CMP.LT; } /// aligned string pub fn alignStr(text: []const u8, aligns: ALIGNS, wlen: usize) []const u8 { var idx: usize = 0; var iter = iteratStr.iterator(text); var string: []const u8 = ""; while (iter.next()) |ch| { idx += 1; if (idx > wlen) break; if (idx == 1) string = ch else { string = concatStr(string, ch); } } if (aligns == ALIGNS.left) { while (idx < wlen) : (idx += 1) { string = concatStr(string, " "); } } if (aligns == ALIGNS.rigth) { while (idx < wlen) : (idx += 1) { string = concatStr(" ", string); } } return string; } /// Delete Items ArrayList pub fn removeListStr(self: *std.ArrayList([]const u8), i: usize) void { var LIST = std.ArrayList([]const u8).init(allocUtl); var idx: usize = 0; for (self.items) |val| { if (idx != i - 1) LIST.append(val) catch |err| { @panic(@errorName(err)); }; idx += 1; } self.clearAndFree(); for (LIST.items) |val| { self.append(val) catch |err| { @panic(@errorName(err)); }; } } /// Add Text ArrayList pub fn addListStr(self: *std.ArrayList([]const u8), text: []const u8) void { var iter = iteratStr.iterator(text); defer iter.deinit(); while (iter.next()) |ch| { self.append(ch) catch |err| { @panic(@errorName(err)); }; } } /// ArrayList to String pub fn listToStr(self: std.ArrayList([]const u8)) []const u8 { var result: []const u8 = ""; for (self.items) |ch| { result = concatStr(result, ch); } return result; } ///------- bool-------------- /// bool to str pub fn boolToStr(v: bool) []const u8 { return if (v) "1" else "0"; } /// str to bool pub fn strToBool(v: []const u8) bool { return if (std.mem.eql(u8, v, "1")) true else false; } /// str to switch STRUE/SFALSE bool pub fn strToCbool(v: []const u8) []const u8 { return if (std.mem.eql(u8, v, "1")) CTRUE else CFALSE; } /// bool to switch STRUE/SFALSE pub fn boolToCbool(v: bool) []const u8 { return if (v == true) CTRUE else CFALSE; } /// switch STRUE/SFALSE bool to bool pub fn cboolToBool(v: []const u8) bool { return if (std.mem.eql(u8, v, CTRUE)) true else false; } // switch STRUE / SFALSE bool to str pub fn cboolToStr(v: []const u8) []const u8 { return if (std.mem.eql(u8, v, CTRUE)) "1" else "0"; }
0
repos/zig_demoJson/library
repos/zig_demoJson/library/curse/logger.zig
///---------------------------- /// looger / historique traçage /// zig 0.12.0 dev ///---------------------------- const std = @import("std"); const builtin = @import("builtin"); const root = @import("root"); var flog :std.fs.File = undefined; pub fn customLog( comptime message_level: std.log.Level, comptime scope: @Type(.EnumLiteral), comptime format: []const u8, args: anytype, ) void { if (builtin.os.tag == .freestanding) @compileError( \\freestanding targets do not have I/O configured; \\please provide at least an empty `log` function declaration ); const level_txt = comptime message_level.asText(); const scope_name = "(" ++ @tagName(scope) ++ ")"; // std.debug.getStderrMutex().lock(); // defer std.debug.getStderrMutex().unlock(); // const w = flog.writer(); // nosuspend w.print("[" ++ level_txt ++ scope_name ++ "] " ++ format ++ "\n", args) // catch { @panic("file write error zlog.txt");}; const stderr = std.io.getStdErr().writer(); var bw = std.io.bufferedWriter(stderr); const writer = bw.writer(); std.debug.lockStdErr(); defer std.debug.unlockStdErr(); nosuspend { writer.print("[" ++ level_txt ++ scope_name ++ "] " ++ format ++ "\n", args) catch return; bw.flush() catch return; } } pub fn scoped(comptime scope: @Type(.EnumLiteral)) type { return struct { pub fn err(comptime format: []const u8, args: anytype) void { @setCold(true); customLog(.err, scope, format, args); } pub fn warn(comptime format: []const u8, args: anytype) void { customLog(.warn, scope, format, args); } pub fn info(comptime format: []const u8, args: anytype) void { customLog(.info, scope, format, args); } pub fn debug(comptime format: []const u8, args: anytype) void { customLog(.debug, scope, format, args); } }; } pub fn openFile(log:[]const u8) void { flog = std.fs.cwd().createFile(log, .{ .read = true }) catch { @panic("impossible ouvrir file zlog;txt");}; } pub fn closeFile() void { flog.close(); } pub const default = scoped(.LOG); pub const err = default.err; pub const warn = default.warn; pub const info = default.info; pub const debug = default.debug;
0
repos/zig_demoJson/library
repos/zig_demoJson/library/curse/grid.zig
///---------------------------- /// gestion GRID / TABLEAU /// zig 0.12.0 dev ///---------------------------- const std = @import("std"); const utf = @import("std").unicode; /// terminal Fonction const term = @import("cursed"); // keyboard const kbd = @import("cursed").kbd; // tools utility const utl = @import("utils"); const os = std.os; const io = std.io; pub const CTRUE = "✔"; pub const CFALSE = " "; //------------------------------------------------------- // management grid // ---------------- // PadingCell() // setPageGrid() // initGrid() // getLenHeaders() // countColumns() // countRows() // setHeaders() // toRefColors() // newCell() // setCellEditCar() // getcellLen() // getHeadersText() // getHeadersPosy() // getHeadersType() // getHeadersCar() // getRowsText() // addRows() // dltRows() // resetRows() // resetGrid() // GridBox() // printGridHeader() // printGridRows() // ioGrid() // ioCombo() // ---------------- // defined GRID /// Errors that may occur when using String pub const ErrGrid = error{ grd_dltRows_Index_invalide, }; // buffer terminal MATRIX const TERMINAL_CHAR = struct { ch: []const u8, attribut: term.ZONATRB, on: bool }; pub const grd = struct { pub const CADRE = enum { line0, line1, line2 }; pub const REFTYP = enum { TEXT_FREE, // Free TEXT_FULL, // Letter Digit Char-special ALPHA, // Letter ALPHA_UPPER, // Letter ALPHA_NUMERIC, // Letter Digit espace - ALPHA_NUMERIC_UPPER, // Letter Digit espace - PASSWORD, // Letter Digit and normaliz char-special YES_NO, // 'y' or 'Y' / 'o' or 'O' UDIGIT, // Digit unsigned DIGIT, // Digit signed UDECIMAL, // Decimal unsigned DECIMAL, // Decimal signed DATE_ISO, // YYYY/MM/DD DATE_FR, // DD/MM/YYYY DATE_US, // MM/DD/YYYY TELEPHONE, // (+123) 6 00 01 00 02 MAIL_ISO, // normalize regex SWITCH, // CTRUE CFALSE FUNC, // call Function }; pub const allocatorArgData = std.heap.page_allocator; var arenaGrid = std.heap.ArenaAllocator.init(std.heap.page_allocator); pub var allocatorGrid = arenaGrid.allocator(); pub fn deinitGrid() void { arenaGrid.deinit(); arenaGrid = std.heap.ArenaAllocator.init(std.heap.page_allocator); allocatorGrid = arenaGrid.allocator(); } // define attribut default GRID pub var AtrGrid: term.ZONATRB = .{ .styled = [_]u32{ @intFromEnum(term.Style.styleDim), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle) }, .backgr = term.BackgroundColor.bgBlack, .foregr = term.ForegroundColor.fgGreen }; // define attribut default TITLE GRID pub var AtrTitle: term.ZONATRB = .{ .styled = [_]u32{ @intFromEnum(term.Style.styleDim), @intFromEnum(term.Style.styleUnderscore), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle) }, .backgr = term.BackgroundColor.bgBlack, .foregr = term.ForegroundColor.fgGreen }; // define attribut default CELL GRID pub var AtrCell: term.ZONATRB = .{ .styled = [_]u32{ @intFromEnum(term.Style.styleItalic), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle) }, .backgr = term.BackgroundColor.bgBlack, .foregr = term.ForegroundColor.fgCyan }; // define attribut default CELL GRID pub var AtrCellBar: term.ZONATRB = .{ .styled = [_]u32{ @intFromEnum(term.Style.styleReverse), @intFromEnum(term.Style.styleItalic), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle) }, .backgr = term.BackgroundColor.bgBlack, .foregr = term.ForegroundColor.fgCyan }; // use default Style separator pub var gridStyle: []const u8 = "│"; pub var gridStyle2: []const u8 = "║"; pub var gridnoStyle: []const u8 = " "; pub const CELL = struct { text: []const u8, long: usize, reftyp: REFTYP, posy: usize, edtcar: []const u8, atrCell: term.ZONATRB }; const ArgData = struct { buf: std.ArrayList([]const u8) = std.ArrayList([]const u8).init(allocatorArgData), }; /// define GRID pub const GRID = struct { name: []const u8, posx: usize, posy: usize, lines: usize, cols: usize, pageRows: usize, data: std.MultiArrayList(ArgData), cell: std.ArrayList(CELL), headers: std.ArrayList(CELL), separator: []const u8, attribut: term.ZONATRB, atrTitle: term.ZONATRB, atrCell: term.ZONATRB, cadre: CADRE, actif: bool, lignes: usize, pages: usize, maxligne: usize, cursligne: usize, curspage: usize, buf: std.ArrayList(TERMINAL_CHAR) }; /// concat String fn concatStr(a: []const u8, b: []const u8) []const u8 { return std.fmt.allocPrint( allocatorGrid, "{s}{s}", .{ a, b }, ) catch |err| { @panic(@errorName(err)); }; } /// substring String fn subStrGrid(a: []const u8, pos: usize, n: usize) []const u8 { if (n == 0 or n > a.len) @panic("Invalide_subStrGrid_Index"); if (pos > a.len) @panic("ErrGrid.Invalide_subStr_pos"); const result = allocatorGrid.alloc(u8, n - pos) catch |err| { @panic(@errorName(err)); }; defer allocatorGrid.free(result); @memcpy(result, a[pos..n]); return std.fmt.allocPrint( allocatorGrid, "{s}", .{result}, ) catch |err| { @panic(@errorName(err)); }; } // pading Cell fn padingCell(text: []const u8, cell: CELL) []const u8 { var i: usize = 0; var e_FIELD: []const u8 = text; var e_signed: []const u8 = undefined; if (cell.reftyp == REFTYP.PASSWORD) { i = 0; e_FIELD = ""; while (i < utl.nbrCharStr(text)) : (i += 1) e_FIELD = concatStr(e_FIELD, "*"); } if (cell.reftyp == REFTYP.UDIGIT or cell.reftyp == REFTYP.DIGIT or cell.reftyp == REFTYP.UDECIMAL or cell.reftyp == REFTYP.DECIMAL) { if (utl.isSignedStr(text) == true) { e_FIELD = subStrGrid(e_FIELD, 1, e_FIELD.len); e_signed = subStrGrid(text, 0, 1); } e_FIELD = utl.alignStr(e_FIELD, utl.ALIGNS.rigth, cell.long); if (cell.reftyp == REFTYP.DIGIT or cell.reftyp == REFTYP.DECIMAL) { e_FIELD = subStrGrid(e_FIELD, 1, e_FIELD.len); if (utl.isSignedStr(text) == false) e_FIELD = concatStr("+", e_FIELD) else e_FIELD = concatStr(e_signed, e_FIELD); } } else e_FIELD = utl.alignStr(e_FIELD, utl.ALIGNS.left, cell.long); if (cell.reftyp == REFTYP.SWITCH) { if (std.mem.eql(u8, text[0..], "true") or std.mem.eql(u8, text[0..], "1")) e_FIELD = CTRUE else e_FIELD = CFALSE; } if (std.mem.eql(u8, cell.edtcar, "") == false) e_FIELD = concatStr(e_FIELD, cell.edtcar); return e_FIELD; } // calculate the number of pages pub fn setPageGrid(self: *GRID) void { self.lignes = self.data.len; if (self.lignes < self.pageRows ) self.pages = 1 else { self.pages = self.lignes / (self.pageRows - 1); if (@rem(self.lignes, (self.pageRows - 1)) > 0) self.pages += 1; } } // new GRID object // Works like a panel with grid behavior pub fn initGrid( vname: []const u8, vposx: usize, vposy: usize, vpageRows: usize, // nbr ligne + header vseparator: []const u8, vcadre: CADRE, ) GRID { const device = GRID{ .name = vname, .posx = vposx, .posy = vposy, .lines = vpageRows + 2, // row per page + cadre .cols = 0, .separator = vseparator, .pageRows = vpageRows, .data = std.MultiArrayList(ArgData){}, .headers = std.ArrayList(CELL).init(allocatorGrid), .cell = std.ArrayList(CELL).init(allocatorGrid), .actif = true, .attribut = AtrGrid, .atrTitle = AtrTitle, .atrCell = AtrCell, .cadre = vcadre, .lignes = 0, .pages = 0, .maxligne = 0, .cursligne = 0, .curspage = 1, .buf = std.ArrayList(TERMINAL_CHAR).init(allocatorGrid) }; return device; } pub fn newGridC( vname: []const u8, vposx: usize, vposy: usize, vpageRows: usize, // nbr ligne + header vseparator: []const u8, vcadre: CADRE, ) *GRID { var device = allocatorGrid.create(GRID) catch |err| { @panic(@errorName(err)); }; device.name = vname; device.posx = vposx; device.posy = vposy; device.lines = vpageRows + 2; // row per page + cadre device.cols = 0; device.separator = vseparator; device.pageRows = vpageRows; device.data = std.MultiArrayList(ArgData){}; device.headers = std.ArrayList(CELL).init(allocatorGrid); device.cell = std.ArrayList(CELL).init(allocatorGrid); device.actif = true; device.attribut = AtrGrid; device.atrTitle = AtrTitle; device.atrCell = AtrCell; device.cadre = vcadre; device.lignes = 0; device.pages = 0; device.maxligne = 0; device.cursligne = 0; device.curspage = 1; device.buf = std.ArrayList(TERMINAL_CHAR).init(allocatorGrid); return device; } pub fn reLoadGrid( self: *GRID, vname: []const u8, vposx: usize, vposy: usize, vpageRows: usize, // nbr ligne + header vseparator: []const u8, vcadre: CADRE, ) void { if (self.actif) return; self.name = vname; self.posx = vposx; self.posy = vposy; self.lines = vpageRows + 2; // row per page + cadre self.cols = 0; self.separator = vseparator; self.pageRows = vpageRows; self.data = std.MultiArrayList(ArgData){}; self.headers = std.ArrayList(CELL).init(allocatorGrid); self.cell = std.ArrayList(CELL).init(allocatorGrid); self.actif = true; self.attribut = AtrGrid; self.atrTitle = AtrTitle; self.atrCell = AtrCell; self.cadre = vcadre; self.lignes = 0; self.pages = 0; self.maxligne = 0; self.cursligne = 0; self.curspage = 1; self.buf = std.ArrayList(TERMINAL_CHAR).init(allocatorGrid); } // return len header ---> arraylist panel-grid pub fn getLenHeaders(self: *GRID) usize { var vlen: usize = 0; for (self.headers.items) |xcell| { vlen += 1; // separator vlen += xcell.long; if (std.mem.eql(u8, xcell.edtcar, "") == false) vlen += 1; } vlen += 1; // separator return vlen; } // return number items-header ---> arraylist panel-grid pub fn countColumns(self: *GRID) usize { return self.headers.items.len; } // return number row-Data ---> arraylist panel-grid pub fn countRows(self: *GRID) usize { return self.data.len; } // initialization CELL -header ---> arraylist panel-grid pub fn setHeaders(self: *GRID) void { self.cols = 0; for (self.cell.items) |xcell| { self.headers.append(xcell) catch |err| { @panic(@errorName(err)); }; } self.cols += getLenHeaders(self); // this.lines + 2 = cadre + header cols + separator // INIT doublebuffer var i: usize = (self.lines) * self.cols; const doublebuffer = TERMINAL_CHAR{ .ch = " ", .attribut = self.attribut, .on = false }; // init matrix while (true) { if (i == 0) break; self.buf.append(doublebuffer) catch |err| { @panic(@errorName(err)); }; i -= 1; } } // return color fn toRefColor(TextColor: term.ForegroundColor) term.ZONATRB { var vAtrCell = AtrCell; switch (TextColor) { .fgdBlack => vAtrCell.foregr = term.ForegroundColor.fgdBlack, .fgdRed => vAtrCell.foregr = term.ForegroundColor.fgdRed, .fgdGreen => vAtrCell.foregr = term.ForegroundColor.fgdGreen, .fgdYellow => vAtrCell.foregr = term.ForegroundColor.fgdYellow, .fgdBlue => vAtrCell.foregr = term.ForegroundColor.fgdBlue, .fgdMagenta => vAtrCell.foregr = term.ForegroundColor.fgdMagenta, .fgdCyan => vAtrCell.foregr = term.ForegroundColor.fgdCyan, .fgdWhite => vAtrCell.foregr = term.ForegroundColor.fgdWhite, .fgBlack => vAtrCell.foregr = term.ForegroundColor.fgBlack, .fgRed => vAtrCell.foregr = term.ForegroundColor.fgRed, .fgGreen => vAtrCell.foregr = term.ForegroundColor.fgGreen, .fgYellow => vAtrCell.foregr = term.ForegroundColor.fgYellow, .fgBlue => vAtrCell.foregr = term.ForegroundColor.fgBlue, .fgMagenta => vAtrCell.foregr = term.ForegroundColor.fgMagenta, .fgCyan => vAtrCell.foregr = term.ForegroundColor.fgCyan, .fgWhite => vAtrCell.foregr = term.ForegroundColor.fgWhite, } return vAtrCell; } // New CELL --> arraylist panel-grid pub fn newCell(self: *GRID, vtext: []const u8, vlong: usize, vreftyp: REFTYP, TextColor: term.ForegroundColor) void { var nlong: usize = 0; if (utl.nbrCharStr(vtext) > vlong) nlong = utl.nbrCharStr(vtext) else nlong = vlong; const cell = CELL{ .text = vtext, .reftyp = vreftyp, .long = nlong, .posy = self.cell.items.len, .edtcar = "", .atrCell = toRefColor(TextColor) }; self.cell.append(cell) catch |err| { @panic(@errorName(err)); }; } // Set Char -cell ---> arraylist panel-grid pub fn setCellEditCar(self: *CELL, vedtcar: []const u8) void { self.edtcar = vedtcar; } // return len -cell ---> arraylist panel-grid pub fn getcellLen(cell: *CELL) usize { return cell.long; } // return name -header ---> arraylist panel-grid pub fn getHeadersText(self: *GRID, r: usize) []const u8 { return self.header.items[r].text; } // return posy -header ---> arraylist panel-grid pub fn getHeadersPosy(self: *GRID, r: usize) usize { return self.header.items[r].posy; } // return reference Type -header ---> arraylist panel-grid pub fn getHeadersType(self: *GRID, r: usize) REFTYP { return self.header.items[r].reftyp; } // return edit Char -header ---> arraylist panel-grid pub fn getHeadersCar(self: *GRID, r: usize) []const u8 { return self.header.items[r].edtcar; } // return Text -data ---> arraylist panel-grid // get text from grid,rows (multiArray) pub fn getRowsText(self: *GRID, r: usize, i: usize) []const u8 { return self.data.items(.buf)[r].items[i]; } // panel-grid ACTIF pub fn getActif(self: *GRID) bool { return self.actif; } // add row -data ---> arraylist panel-grid pub fn addRows(self: *GRID, vrows: []const []const u8) void { const vlist = std.ArrayList([]const u8); var m = vlist.init(allocatorGrid); m.appendSlice(vrows) catch |err| { @panic(@errorName(err)); }; self.data.append(allocatorArgData, .{ .buf = m }) catch |err| { @panic(@errorName(err)); }; setPageGrid(self); } // delete row -data ---> arraylist panel-grid pub fn dltRows(self: *GRID, r: usize) ErrGrid!void { if (r < self.data.len) { self.data.orderedRemove(r); setPageGrid(self); } else return ErrGrid.grd_dltRows_Index_invalide; } // reset row data -GRID ---> arraylist panel-grid pub fn resetRows(self: *GRID) void { while (self.data.len > 0) { self.data.orderedRemove(self.data.len - 1); } self.lignes = 0; self.pages = 0; self.maxligne = 0; self.cursligne = 0; self.curspage = 1; self.actif = true; } // reset -GRID ---> arraylist panel-grid pub fn freeGrid(self: *GRID) void { while (self.data.len > 0) { self.data.orderedRemove(self.data.len - 1); } self.data.deinit(allocatorArgData); self.headers.clearAndFree(); self.headers.deinit(); self.cell.clearAndFree(); self.cell.deinit(); self.lignes = 0; self.pages = 0; self.maxligne = 0; self.cursligne = 0; self.curspage = 0; self.buf.clearAndFree(); self.buf.deinit(); self.actif = false; } // assign -Box(fram) MATRIX TERMINAL ---> arraylist panel-grid fn GridBox(self: *GRID) void { if (CADRE.line0 == self.cadre) return; const ACS_Hlines = "─"; const ACS_Vlines = "│"; const ACS_UCLEFT = "┌"; const ACS_UCRIGHT = "┐"; const ACS_LCLEFT = "└"; const ACS_LCRIGHT = "┘"; const ACS_Hline2 = "═"; const ACS_Vline2 = "║"; const ACS_UCLEFT2 = "╔"; const ACS_UCRIGHT2 = "╗"; const ACS_LCLEFT2 = "╚"; const ACS_LCRIGHT2 = "╝"; var trait: []const u8 = ""; var edt: bool = undefined; var row: usize = 1; var y: usize = 0; var col: usize = 0; const cols: usize = getLenHeaders(self); var n: usize = 0; var x: usize = self.posx - 1; while (row <= self.lines) { y = self.posy; col = 1; while (col <= cols) { edt = false; if (row == 1) { if (col == 1) { if (CADRE.line1 == self.cadre) { trait = ACS_UCLEFT; } else trait = ACS_UCLEFT2; edt = true; } if (col == cols) { if (CADRE.line1 == self.cadre) { trait = ACS_UCRIGHT; } else trait = ACS_UCRIGHT2; edt = true; } if (col > 1 and col < cols) { if (CADRE.line1 == self.cadre) { trait = ACS_Hlines; } else trait = ACS_Hline2; edt = true; } } else if (row == self.lines) { if (col == 1) { if (CADRE.line1 == self.cadre) { trait = ACS_LCLEFT; } else trait = ACS_LCLEFT2; edt = true; } if (col == cols) { if (CADRE.line1 == self.cadre) { trait = ACS_LCRIGHT; } else trait = ACS_LCRIGHT2; edt = true; } if (col > 1 and col < cols) { if (CADRE.line1 == self.cadre) { trait = ACS_Hlines; } else trait = ACS_Hline2; edt = true; } } else if (row > 1 and row < self.lines) { if (col == 1 or col == cols) { if (CADRE.line1 == self.cadre) { trait = ACS_Vlines; } else trait = ACS_Vline2; edt = true; } } if (edt) { self.buf.items[n].ch = trait; self.buf.items[n].attribut = self.attribut; self.buf.items[n].on = true; } n += 1; y += 1; col += 1; } x += 1; row += 1; } } // assign and display -header MATRIX TERMINAL ---> arraylist panel-grid pub fn printGridHeader(self: *GRID) void { if (self.actif == false) return; var buf: []const u8 = ""; const Blanc = " "; var pos: usize = 0; for (self.headers.items, 0..) |_, idx| { self.headers.items[idx].posy = pos; if (self.headers.items[idx].edtcar.len == 0) pos = pos + self.headers.items[idx].long + 1 else pos = pos + self.headers.items[idx].long + 1 + 1; } for (self.headers.items) |cellx| { if (std.mem.eql(u8, cellx.edtcar, "") == true) buf = std.fmt.allocPrint(allocatorGrid, "{s}{s}{s}", .{ buf, self.separator, utl.alignStr(" ", utl.ALIGNS.left, cellx.long) }) catch |err| {@panic(@errorName(err)); } else buf = std.fmt.allocPrint(allocatorGrid, "{s}{s}{s}{s}", .{ buf, self.separator, utl.alignStr(" ", utl.ALIGNS.left, cellx.long), Blanc }) catch |err| {@panic(@errorName(err));}; } buf = std.fmt.allocPrint(allocatorGrid, "{s}{s}", .{ buf, self.separator }) catch |err| { @panic(@errorName(err)); }; defer allocatorGrid.free(buf); var x: usize = 1; var y: usize = 0; var n: usize = 0; while (x <= self.lines) : (x += 1) { y = 1; var iter = utl.iteratStr.iterator(buf); defer iter.deinit(); while (iter.next()) |ch| : (n += 1) { self.buf.items[n].ch = std.fmt.allocPrint(allocatorGrid, "{s}", .{ch}) catch unreachable; self.buf.items[n].attribut = self.attribut; self.buf.items[n].on = false; } } buf = ""; for (self.headers.items) |cellx| { if (cellx.reftyp == REFTYP.UDIGIT or cellx.reftyp == REFTYP.DIGIT or cellx.reftyp == REFTYP.UDECIMAL or cellx.reftyp == REFTYP.DECIMAL) buf = std.fmt.allocPrint(allocatorGrid, "{s}{s}{s}", .{ buf, self.separator, utl.alignStr(cellx.text, utl.ALIGNS.rigth, cellx.long) }) catch |err| {@panic(@errorName(err)); } else buf = std.fmt.allocPrint(allocatorGrid, "{s}{s}{s}", .{ buf, self.separator, utl.alignStr(cellx.text, utl.ALIGNS.left, cellx.long) }) catch |err| {@panic(@errorName(err)); }; if (std.mem.eql(u8, cellx.edtcar, "") == false) buf =std.fmt.allocPrint(allocatorGrid, "{s}{s}", .{ buf, Blanc }) catch |err| {@panic(@errorName(err)); }; n = getLenHeaders(self); var iter = utl.iteratStr.iterator(buf); defer iter.deinit(); while (iter.next()) |ch| : (n += 1) { self.buf.items[n].ch = std.fmt.allocPrint(allocatorGrid, "{s}", .{ch}) catch unreachable; self.buf.items[n].attribut = self.atrTitle; self.buf.items[n].on = true; } // this.lines + 2 = cadre + header GridBox(self); x = 1; y = 0; n = 0; while (x <= self.lines) : (x += 1) { y = 1; while (y <= getLenHeaders(self)) : (y += 1) { term.gotoXY(x + self.posx, y + self.posy); term.writeStyled(self.buf.items[n].ch, self.buf.items[n].attribut); n += 1; } } } } // assign and display -data MATRIX TERMINAL ---> arraylist panel-grid pub fn printGridRows(self: *GRID) void { if (self.actif == false) return; var nposy: usize = (getLenHeaders(self) * 2) + 1; var n: usize = 0; var x: usize = 0; var y: usize = 0; var h: usize = 0; const nColumns: usize = countColumns(self); var start: usize = 0; var l: usize = 0; var buf: []const u8 = ""; var bufItems: []const u8 = ""; self.maxligne = 0; if (self.curspage == 0) start = 0 else start = (self.pageRows - 1) * (self.curspage - 1); var r: usize = 0; while (r < self.pageRows - 1) : (r += 1) { l = r + start; if (l < self.lignes) { self.maxligne = r; h = 0; while (h < nColumns) : (h += 1) { // formatage buffer bufItems = self.data.items(.buf)[l].items[h]; buf = padingCell(bufItems, self.headers.items[h]); // write matrice var iter = utl.iteratStr.iterator(buf); defer iter.deinit(); n = nposy + self.headers.items[h].posy; while (iter.next()) |ch| : (n += 1) { self.buf.items[n].ch = std.fmt.allocPrint(allocatorGrid, "{s}", .{ch}) catch unreachable; if (self.cursligne == l or self.cursligne == r) self.buf.items[n].attribut = AtrCellBar else self.buf.items[n].attribut = self.headers.items[h].atrCell; self.buf.items[n].on = true; } } nposy = nposy + self.cols; } } x = 1; y = 0; n = 0; while (x <= self.lines) : (x += 1) { y = 1; while (y <= self.cols) : (y += 1) { if (self.buf.items[n].on == true) { term.gotoXY(x + self.posx, y + self.posy); term.writeStyled(self.buf.items[n].ch, self.buf.items[n].attribut); } n += 1; } } } //---------------------------------------------------------------- // Management GRID enter = select 1..n 0 = abort (Escape) // Turning on the mouse // UP DOWn PageUP PageDown // Automatic alignment based on the type reference //---------------------------------------------------------------- pub const GridSelect = struct { Key: term.kbd, Buf: std.ArrayList([]const u8) }; //------------------------------------ // manual= on return pageUp/pageDown no select // esc = return no select // enter = return enter and line select // ----------------------------------- pub fn ioGrid(self: *GRID, manual: bool) GridSelect { var gSelect: GridSelect = .{ .Key = term.kbd.none, .Buf = std.ArrayList([]const u8).init(allocatorGrid) }; if (self.actif == false) return gSelect; gSelect.Key = term.kbd.none; var CountLigne: usize = 0; self.cursligne = 0; printGridHeader(self); term.cursHide(); term.onMouse(); var grid_key: term.Keyboard = undefined; while (true) { printGridRows(self); grid_key = kbd.getKEY(); // bar espace if (grid_key.Key == kbd.char and std.mem.eql(u8, grid_key.Char, " ")) { grid_key.Key = kbd.enter; grid_key.Char = ""; } if (grid_key.Key == kbd.mouse) { grid_key.Key = kbd.none; if (term.MouseInfo.scroll) { switch (term.MouseInfo.scrollDir) { term.ScrollDirection.msUp => grid_key.Key = kbd.up, term.ScrollDirection.msDown => grid_key.Key = kbd.down, else => {}, } } else { if (term.MouseInfo.action == term.MouseAction.maReleased) continue; switch (term.MouseInfo.button) { term.MouseButton.mbLeft => grid_key.Key = kbd.enter, term.MouseButton.mbMiddle => grid_key.Key = kbd.enter, term.MouseButton.mbRight => grid_key.Key = kbd.enter, else => {}, } } } switch (grid_key.Key) { .none => continue, .esc => { self.cursligne = 0; gSelect.Key = kbd.esc; term.offMouse(); return gSelect; }, .enter => if (self.lignes > 0) { gSelect.Key = kbd.enter; if (self.curspage > 0) { CountLigne = (self.pageRows - 1) * (self.curspage - 1); CountLigne += self.cursligne; } gSelect.Buf = self.data.items(.buf)[CountLigne]; term.offMouse(); self.cursligne = 0; return gSelect; }, .up => if (CountLigne > 0) { CountLigne -= 1; self.cursligne -= 1; }, .down => if (CountLigne < self.maxligne) { CountLigne += 1; self.cursligne += 1; }, .pageUp => { if (self.curspage > 1) { self.curspage -= 1; self.cursligne = 0; CountLigne = 0; printGridHeader(self); } else { if (manual == true) { self.cursligne = 0; gSelect.Key = kbd.pageUp; term.offMouse(); return gSelect; } } }, .pageDown => { if (self.curspage < self.pages) { self.curspage += 1; self.cursligne = 0; CountLigne = 0; printGridHeader(self); } else { if (manual == true) { self.cursligne = 0; gSelect.Key = kbd.pageDown; term.offMouse(); return gSelect; } } }, else => {}, } } } ///------------------------------------ /// manual= on return pageUp/pageDown no select /// esc = return no select /// KEY = return select valide ex: management Grid to Grid /// enter = return enter and line select /// ----------------------------------- pub fn ioGridKey(self: *GRID, gKey: term.kbd, manual: bool) GridSelect { var gSelect: GridSelect = .{ .Key = term.kbd.none, .Buf = std.ArrayList([]const u8).init(allocatorGrid) }; if (self.actif == false) return gSelect; gSelect.Key = term.kbd.none; var CountLigne: usize = 0; self.cursligne = 0; printGridHeader(self); term.cursHide(); term.onMouse(); var grid_key: term.Keyboard = undefined; while (true) { printGridRows(self); grid_key = kbd.getKEY(); // bar espace if (grid_key.Key == kbd.char and std.mem.eql(u8, grid_key.Char, " ")) { grid_key.Key = kbd.enter; grid_key.Char = ""; } if (grid_key.Key == kbd.mouse) { grid_key.Key = kbd.none; if (term.MouseInfo.scroll) { switch (term.MouseInfo.scrollDir) { term.ScrollDirection.msUp => grid_key.Key = kbd.up, term.ScrollDirection.msDown => grid_key.Key = kbd.down, else => {}, } } else { if (term.MouseInfo.action == term.MouseAction.maReleased) continue; switch (term.MouseInfo.button) { term.MouseButton.mbLeft => grid_key.Key = kbd.enter, term.MouseButton.mbMiddle => grid_key.Key = kbd.enter, term.MouseButton.mbRight => grid_key.Key = kbd.enter, else => {}, } } } if (grid_key.Key == gKey) { self.cursligne = 0; gSelect.Key = kbd.ctrlV; term.offMouse(); return gSelect; } switch (grid_key.Key) { .none => continue, .F1 => {}, .esc => { self.cursligne = 0; gSelect.Key = kbd.esc; term.offMouse(); return gSelect; }, .enter => if (self.lignes > 0) { gSelect.Key = kbd.enter; if (self.curspage > 0) { CountLigne = (self.pageRows - 1) * (self.curspage - 1); CountLigne += self.cursligne; } gSelect.Buf = self.data.items(.buf)[CountLigne]; term.offMouse(); self.cursligne = 0; return gSelect; }, .up => if (CountLigne > 0) { CountLigne -= 1; self.cursligne -= 1; }, .down => if (CountLigne < self.maxligne) { CountLigne += 1; self.cursligne += 1; }, .pageUp => { if (self.curspage > 1) { self.curspage -= 1; self.cursligne = 0; CountLigne = 0; printGridHeader(self); } else { if (manual == true) { self.cursligne = 0; gSelect.Key = kbd.pageUp; term.offMouse(); return gSelect; } } }, .pageDown => { if (self.curspage < self.pages) { self.curspage += 1; self.cursligne = 0; CountLigne = 0; printGridHeader(self); } else { if (manual == true) { self.cursligne = 0; gSelect.Key = kbd.pageDown; term.offMouse(); return gSelect; } } }, else => {}, } } } // idem iogrid with Static table data pub fn ioCombo(self: *GRID, pos: usize) GridSelect { var CountLigne: usize = 0; var gSelect: GridSelect = .{ .Key = term.kbd.none, .Buf = std.ArrayList([]const u8).init(allocatorGrid) }; gSelect.Key = term.kbd.none; if (self.actif == false) return gSelect; printGridHeader(self); if (pos == 0) self.cursligne = 0 else { var r: usize = 0; var n: usize = 0; self.curspage = 1; while (r < self.lignes) : (r += 1) { if (n == self.pageRows - 1) { self.curspage += 1; n = 0; } if (r == pos) { self.cursligne = r; break; } n += 1; } if (self.curspage > 1) { if (((self.pageRows - 1) * (self.curspage - 1)) < pos) CountLigne = 0 else CountLigne = ((self.pageRows - 1) * (self.curspage - 1)) - pos; } CountLigne = pos; } term.cursHide(); term.onMouse(); var grid_key: term.Keyboard = undefined; while (true) { printGridRows(self); grid_key = kbd.getKEY(); // bar espace if (grid_key.Key == kbd.char and std.mem.eql(u8, grid_key.Char, " ")) { grid_key.Key = kbd.enter; grid_key.Char = ""; } if (grid_key.Key == kbd.mouse) { grid_key.Key = kbd.none; if (term.MouseInfo.scroll) { switch (term.MouseInfo.scrollDir) { term.ScrollDirection.msUp => grid_key.Key = kbd.up, term.ScrollDirection.msDown => grid_key.Key = kbd.down, else => {}, } } else { if (term.MouseInfo.action == term.MouseAction.maReleased) continue; switch (term.MouseInfo.button) { term.MouseButton.mbLeft => grid_key.Key = kbd.enter, term.MouseButton.mbMiddle => grid_key.Key = kbd.enter, term.MouseButton.mbRight => grid_key.Key = kbd.enter, else => {}, } } } switch (grid_key.Key) { .none => continue, .esc => { self.cursligne = 0; gSelect.Key = kbd.esc; term.offMouse(); return gSelect; }, .enter => if (self.lignes > 0) { gSelect.Key = kbd.enter; if (self.curspage > 0) { const vline = (self.pageRows - 1) * (self.curspage - 1); CountLigne += vline; } gSelect.Buf = self.data.items(.buf)[CountLigne]; term.offMouse(); self.cursligne = 0; return gSelect; }, .up => if (CountLigne > 0) { CountLigne -= 1; self.cursligne -= 1; }, .down => if (CountLigne < self.maxligne) { CountLigne += 1; self.cursligne += 1; }, .pageUp => if (self.curspage > 1) { self.curspage -= 1; self.cursligne = 0; CountLigne = 0; printGridHeader(self); }, .pageDown => if (self.curspage < self.pages) { self.curspage += 1; self.cursligne = 0; CountLigne = 0; printGridHeader(self); }, else => {}, } } } };
0
repos/zig_demoJson/library
repos/zig_demoJson/library/curse/cursed.zig
///----------------------- /// cursed /// connexion terminal /// zig 0.12.0 dev ///----------------------- const std = @import("std"); const utf = @import("std").unicode; const io = std.io; const os = std.os; const fs = std.fs; /// Define use terminal basic var TTY: fs.File = undefined; var original_termios: os.linux.termios = undefined; var use_termios: os.linux.termios = undefined; const stdout = std.io.getStdOut().writer(); const stdin = std.io.getStdIn().reader(); // outils // const allocstr = std.heap.page_allocator; var arenaTerm = std.heap.ArenaAllocator.init(std.heap.page_allocator); pub var allocatorTerm = arenaTerm.allocator(); pub fn deinitTerm() void { arenaTerm.deinit(); arenaTerm = std.heap.ArenaAllocator.init(std.heap.page_allocator); allocatorTerm = arenaTerm.allocator(); } pub const Style = enum(u8) { notStyle = 0, // not styled styleBold = 1, // bold text styleDim, // dim text styleItalic, // italic (or reverse on terminals not supporting) styleUnderscore, // underscored text styleBlink, // blinking/bold text styleBlinkRapid, // rapid blinking/bold text (not widely supported) styleReverse, // reverse styleHidden, // hidden text styleCrossed, // strikethrough }; pub const typeCursor = enum(u8) { cDefault, cBlink, cSteady, cBlinkUnderline, cSteadyUnderline, cBlinkBar, cSteadyBar }; // def standard color fgd dull color fg higth color pub const ForegroundColor = enum(u8) { // terminal's foreground colors fgdBlack = 30, // black fgdRed, // red fgdGreen, // green fgdYellow, // yellow fgdBlue, // blue fgdMagenta, // magenta fgdCyan, // cyan fgdWhite, // white fgBlack = 90, // black fgRed, // red fgGreen, // green fgYellow, // yellow fgBlue, // blue fgMagenta, // magenta fgCyan, // cyan fgWhite, // white }; pub const BackgroundColor = enum(u8) { // terminal's background colors bgBlack = 40, // black bgRed, // red bgGreen, // green bgYellow, // yellow bgBlue, // blue bgMagenta, // magenta bgCyan = 106, // cyan bgWhite = 47, // white }; // attribut standard pub const ZONATRB = struct { styled: [4]u32, backgr: BackgroundColor, foregr: ForegroundColor }; pub const iteratStr = struct { var strbuf: []const u8 = undefined; /// Errors that may occur when using String pub const ErrNbrch = error{ InvalideAllocBuffer, }; pub const StringIterator = struct { buf: []u8, index: usize, fn allocBuffer(size: usize) ErrNbrch![]u8 { const buf = allocatorTerm.alloc(u8, size) catch { return ErrNbrch.InvalideAllocBuffer; }; return buf; } /// Deallocates the internal buffer pub fn deinit(self: *StringIterator) void { if (self.buf.len > 0) allocatorTerm.free(self.buf); strbuf = ""; } pub fn next(it: *StringIterator) ?[]const u8 { const optional_buf: ?[]u8 = allocBuffer(strbuf.len) catch return null; it.buf = optional_buf orelse ""; var idx: usize = 0; while (true) { if (idx >= strbuf.len) break; it.buf[idx] = strbuf[idx]; idx += 1; } if (it.index >= it.buf.len) return null; idx = it.index; it.index += getUTF8Size(it.buf[idx]); return it.buf[idx..it.index]; } pub fn preview(it: *StringIterator) ?[]const u8 { const optional_buf: ?[]u8 = allocBuffer(strbuf.len) catch return null; it.buf = optional_buf orelse ""; var idx: usize = 0; while (true) { if (idx >= strbuf.len) break; it.buf[idx] = strbuf[idx]; idx += 1; } if (it.index == 0) return null; idx = it.buf.len; it.index -= getUTF8Size(it.buf[idx]); return it.buf[idx..it.index]; } }; /// iterator String pub fn iterator(str: []const u8) StringIterator { strbuf = str; return StringIterator{ .buf = undefined, .index = 0, }; } /// Returns the UTF-8 character's size fn getUTF8Size(char: u8) u3 { return std.unicode.utf8ByteSequenceLength(char) catch unreachable; } }; /// flush terminal in-out pub fn flushIO() void { _ = os.linux.tcsetattr(TTY.handle, .FLUSH, &use_termios); } ///------------- /// mouse ///------------- /// onMouse pub fn onMouse() void { stdout.writeAll("\x1b[?1000;1005;1006h") catch {}; } /// offMouse pub fn offMouse() void { stdout.writeAll("\x1b[?1000;1005;1006l") catch {}; } ///------------- /// clear ///------------- /// Clear from cursor until end of screen pub fn cls_from_cursor_toEndScreen() void { stdout.writeAll("\x1b[0J") catch {}; } /// Clear from cursor to beginning of screen pub fn cls_from_cursor_toStartScreen() void { stdout.writeAll("\x1b[1J") catch {}; } /// Clear all screen pub fn cls() void { stdout.writeAll("\x1b[2J") catch {}; stdout.writeAll("\x1b[3J") catch {}; } /// Clear from cursor to end of line pub fn cls_from_cursor_toEndline() void { stdout.writeAll("\x1b[0K") catch {}; } /// Clear start of line to the cursor pub fn cls_from_cursor_toStartLine() void { stdout.writeAll("\x1b[1K") catch {}; } /// Clear from cursor to end of line pub fn cls_line() void { stdout.writeAll("\x1b[2K") catch {}; } ///------------- /// cursor ///------------- const Point = struct { x: usize, y: usize }; pub var posCurs: Point = undefined; /// Moves cursor to `x` column and `y` row pub fn gotoXY(x: usize, y: usize) void { stdout.print("\x1b[{d};{d}H", .{ x, y }) catch {}; } /// Moves cursor up `y` rows pub fn gotoUp(x: usize) void { stdout.print("\x1b[{d}A", .{x}) catch {}; } /// Moves cursor down `y` rows pub fn gotoDown(x: usize) void { stdout.print("\x1b[{d}B", .{x}) catch {}; } /// Moves cursor left `y` columns pub fn gotoLeft(y: usize) void { stdout.print("\x1b[{d}D", .{y}) catch {}; } /// Moves cursor right `y` columns pub fn gotoRight(y: usize) void { stdout.print("\x1b[{d}C", .{y}) catch {}; } /// Hide the cursor pub fn cursHide() void { stdout.print("\x1b[?25l", .{}) catch {}; } /// Show the cursor pub fn cursShow() void { stdout.writeAll("\x1b[?25h") catch {}; } pub fn defCursor(e_curs: typeCursor) void { // define type Cursor form terminal switch (e_curs) { .cDefault => { stdout.writeAll("\x1b[0 q") catch {}; // 0 → default terminal }, .cBlink => { stdout.writeAll("\x1b[1 q") catch {}; // 1 → blinking block }, .cSteady => { stdout.writeAll("\x1b[2 q") catch {}; // 2 → steady block }, .cBlinkUnderline => { stdout.writeAll("\x1b[3 q") catch {}; // 3 → blinking underlines }, .cSteadyUnderline => { stdout.writeAll("\x1b[4 q") catch {}; // 4 → steady underlines }, .cBlinkBar => { stdout.writeAll("\x1b[5 q") catch {}; // 5 → blinking bar }, .cSteadyBar => { stdout.writeAll("\x1b[6 q") catch {}; // 6 → steady bar }, } stdout.writeAll("\x1b[?25h") catch {}; } fn convIntCursor(x: u8) usize { switch (x) { '0' => return 0, '1' => return 1, '2' => return 2, '3' => return 3, '4' => return 4, '5' => return 5, '6' => return 6, '7' => return 7, '8' => return 8, '9' => return 9, else => return 0, } } pub fn getCursor() void { // get Cursor form terminal var cursBuf: [13]u8 = undefined; posCurs.x = 0; posCurs.y = 0; flushIO(); // Don't forget to flush! stdout.writeAll("\x1b[?6n") catch {}; var c: usize = 0; while (c == 0) { c = stdin.read(&cursBuf) catch unreachable; } flushIO(); // columns = 1 digit if (cursBuf[4] == 59) { posCurs.x = convIntCursor(cursBuf[3]); if (cursBuf[6] == 59) posCurs.y = convIntCursor(cursBuf[5]); if (cursBuf[7] == 59) { posCurs.y = convIntCursor(cursBuf[5]); posCurs.y = (posCurs.y * 10) + convIntCursor(cursBuf[6]); } if (cursBuf[8] == 59) { posCurs.y = convIntCursor(cursBuf[5]); posCurs.y = (posCurs.y * 10) + convIntCursor(cursBuf[6]); posCurs.y = (posCurs.y * 10) + convIntCursor(cursBuf[7]); } } // columns = 2 digits if (cursBuf[5] == 59) { posCurs.x = convIntCursor(cursBuf[3]); posCurs.x = (posCurs.x * 10) + convIntCursor(cursBuf[4]); if (cursBuf[7] == 59) posCurs.y = convIntCursor(cursBuf[6]); if (cursBuf[8] == 59) { posCurs.y = convIntCursor(cursBuf[6]); posCurs.y = (posCurs.y * 10) + convIntCursor(cursBuf[7]); } if (cursBuf[9] == 59) { posCurs.y = convIntCursor(cursBuf[6]); posCurs.y = (posCurs.y * 10) + convIntCursor(cursBuf[7]); posCurs.y = (posCurs.y * 10) + convIntCursor(cursBuf[8]); } } flushIO(); } ///------------------------- /// style color writestyled ///------------------------- /// Reset the terminal style. pub fn resetStyle() void { stdout.writeAll("\x1b[0m") catch {}; } /// Sets the terminal style. fn setStyle(style: [4]u32) void { for (style) |v| { if (v != 0) { stdout.print("\x1b[{d}m", .{v}) catch {}; } } } /// Sets the terminal's foreground color. fn setForegroundColor(color: BackgroundColor) void { stdout.print("\x1b[{d}m", .{@intFromEnum(color)}) catch {}; } /// Sets the terminal's Background color. fn setBackgroundColor(color: ForegroundColor) void { stdout.print("\x1b[{d}m", .{@intFromEnum(color)}) catch {}; } /// write text and attribut pub fn writeStyled(text: []const u8, attribut: ZONATRB) void { setForegroundColor(attribut.backgr); setBackgroundColor(attribut.foregr); setStyle(attribut.styled); stdout.print("{s}\x1b[0m", .{text}) catch {}; } ///------------------------- /// Terminal ///------------------------- /// A raw terminal representation, you can enter terminal raw mode /// using this struct. Raw mode is essential to create a TUI. /// open terminal and config pub fn enableRawMode() void { TTY = fs.cwd().openFile("/dev/tty", .{ .mode = .read_write }) catch unreachable; //defer TTY.close(); _ = os.linux.tcgetattr(TTY.handle, &original_termios); _ = os.linux.tcgetattr(TTY.handle, &use_termios); // https://viewsourcecode.org/snaptoken/kilo/02.enteringRawMode.html // https://codeberg.org/josias/zigcurses/src/branch/master/src/main.zig // https://man7.org/linux/man-pages/man3/ttermios.3.html // https://manpages.ubuntu.com/manpages/trusty/fr/man3/termios.3.html // https://zig.news/lhp/want-to-create-a-tui-application-the-basics-of-uncooked-terminal-io-17gm //--------------------------------------------------------------- // v 0.11.0 //--------------------------------------------------------------- // use_termios.iflag &= ~(os.linux.IGNBRK | os.linux.BRKINT | os.linux.PARMRK | os.linux.INPCK | os.linux.ISTRIP | // os.linux.INLCR | os.linux.IGNCR | os.linux.ICRNL | os.linux.IXON); // use_termios.oflag &= ~(os.linux.OPOST); // use_termios.cflag &= ~(os.linux.CSIZE | os.linux.PARENB); // use_termios.cflag |= (os.linux.CS8); // use_termios.lflag &= ~(os.linux.ECHO | os.linux.ECHONL | os.linux.ICANON | os.linux.IEXTEN | os.linux.ISIG); // Wait until it reads at least one byte terminal standard // use_termios.cc[os.linux.V.MIN] = 1; // Wait 100 miliseconds at maximum. // use_termios.cc[os.linux.V.TIME] = 0; //--------------------------------------------------------------- // iflag; /* input modes */ // oflag; /* output modes */ // cflag; /* control modes */ // lflag; /* local modes */ // cc[NCCS]; /* special characters */ // V 0.12 0 > var iflags = use_termios.iflag; iflags.IGNBRK = false; iflags.BRKINT = false; iflags.PARMRK = false; iflags.INPCK = false; iflags.ISTRIP = false; iflags.INLCR = false; iflags.IGNCR = false; iflags.ICRNL = false; iflags.IXON = false; use_termios.iflag = iflags; var oflags = use_termios.oflag; oflags.OPOST = false; use_termios.oflag = oflags; var cflags = use_termios.cflag; cflags.CSIZE = std.c.CSIZE.CS8; cflags.PARENB = false; use_termios.cflag = cflags; var lflags = use_termios.lflag; lflags.ECHO = false; lflags.ECHONL = false; lflags.ICANON = false; lflags.IEXTEN = false; lflags.ISIG = false; use_termios.lflag = lflags; //Wait until it reads at least one byte terminal standard use_termios.cc[@intFromEnum(std.os.linux.V.MIN)] = 1; // Wait 100 miliseconds at maximum. use_termios.cc[@intFromEnum(os.linux.V.TIME)] = 1; // apply changes _ = os.linux.tcsetattr(TTY.handle, .NOW, &use_termios); // cursor HIDE par défault cursHide(); offMouse(); } /// Clear gross terminal fn reset() void { stdout.writeAll("\x1bc") catch {}; stdout.writeAll("\x1b[H") catch {}; } /// Returns to the previous terminal state pub fn disableRawMode() void { defCursor(typeCursor.cSteady); offMouse(); cursShow(); _ = os.linux.tcsetattr(TTY.handle, .FLUSH, &original_termios); reset(); } /// get size terminal const TermSize = struct { width: usize, height: usize }; pub fn getSize() TermSize { var win_size: std.os.linux.winsize = undefined; const err = os.linux.ioctl(TTY.handle, os.linux.T.IOCGWINSZ, @intFromPtr(&win_size)); if (std.posix.errno(err) != .SUCCESS) { @panic(" Cursed getSize error ioctl TTY"); //return os.unexpectedErrno(os.errno(err)); } return TermSize{ .height = win_size.ws_row, .width = win_size.ws_col, }; } /// Update title terminal pub fn titleTerm(title: []const u8) void { if (title.len > 0) { stdout.print("\x1b]0;{s}\x07", .{title}) catch {}; } } // if use resize ok : vte application terminal ex TermVte // change XTERM // sudo thunar /etc/X11/app-defaults/XTerm // *allowWindowOps: true *eightBitInput: false pub fn resizeTerm(line: usize, cols: usize) void { if (line > 0 and cols > 0) { stdout.print("\x1b[8;{d};{d};t", .{ line, cols }) catch {}; } } /// mouse struct pub const MouseAction = enum { maNone, maPressed, maReleased, }; pub const MouseButton = enum { mbNone, mbLeft, mbMiddle, mbRight, }; pub const ScrollDirection = enum { msNone, msUp, msDown, }; const Mouse = struct { x: usize, // x mouse position y: usize, // y mouse position button: MouseButton, // which button was pressed action: MouseAction, // if button was released or pressed ctrl: bool, // was ctrl was down on event shift: bool, // was shift was down on event scroll: bool, // if this is a mouse scroll scrollDir: ScrollDirection, move: bool, // if this a mouse move }; pub var MouseInfo: Mouse = undefined; pub const Keyboard = struct { Key: kbd, Char: []const u8 }; /// Decrypt the keyboard pub const kbd = enum { none, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16, F17, F18, F19, F20, F21, F22, F23, F24, altA, altB, altC, altD, altE, altF, altG, altH, altI, altJ, altK, altL, altM, altN, altO, altP, altQ, altR, altS, altT, altU, altV, altW, altX, altY, altZ, ctrlA, ctrlB, ctrlC, ctrlD, ctrlE, ctrlF, ctrlG, ctrlH, ctrlI, ctrlJ, ctrlK, ctrlL, ctrlM, ctrlN, ctrlO, ctrlP, ctrlQ, ctrlR, ctrlS, ctrlT, ctrlU, ctrlV, ctrlW, ctrlX, ctrlY, ctrlZ, // specific for grid pageUp, pageDown, home, end, esc, // Specific for typing mouse, char, up, down, left, right, delete, enter, ins, tab, stab, backspace, func, task, call, pub fn enumToStr(self: kbd) []const u8 { return @as([]const u8, @tagName(self)); } pub fn toEnum(name: []const u8) kbd { var vlen: usize = 0; var iter = iteratStr.iterator(name); defer iter.deinit(); var result: usize = 0; while (iter.next()) |_| { vlen += 1; } //return @intToEnum(kbd, @as(u8, name[1])); if (name[0] == 'F') { //f1..f9 if (vlen == 2) { result = @as(u8, name[1]) - 48; return @as(kbd, @enumFromInt(result)); } // f10..f19 if (vlen == 3 and name[1] == '1') { result = @as(u8, name[2]) - 48; return @as(kbd, @enumFromInt(10 + result)); } // f20..f24 if (vlen == 3 and name[1] == '2') { result = @as(u8, name[2]) - 48; return @as(kbd, @enumFromInt(20 + result)); } } if (name[0] == 'a' and name[1] == 'l' and name[2] == 't') { if (vlen != 4) return .none; result = @as(u8, name[3]) - 41; if (result < 25 or result > 50) return .none else return @as(kbd, @enumFromInt(result)); } if (name[0] == 'c' and name[1] == 't' and name[2] == 'r' and name[3] == 'l') { if (vlen != 5) return .none; result = @as(u8, name[4]) - 14; if (result < 51 or result > 76) return .none else return @as(kbd, @enumFromInt(result)); } //std.debug.print("{s}\r\n",.{name}); if (std.mem.eql(u8, name, "pageUp")) return kbd.pageUp; if (std.mem.eql(u8, name, "pageDown")) return kbd.pageDown; if (std.mem.eql(u8, name, "home")) return kbd.home; if (std.mem.eql(u8, name, "end")) return kbd.end; if (std.mem.eql(u8, name, "esc")) return kbd.esc; return .none; } /// converted keyboard variable fn convIntMouse(x: u8) usize { switch (x) { '0' => return 0, '1' => return 1, '2' => return 2, '3' => return 3, '4' => return 4, '5' => return 5, '6' => return 6, '7' => return 7, '8' => return 8, '9' => return 9, else => return 1, } } // get All keyboard keys allowed in terminal pub fn getKEY() Keyboard { // init Event var Event: Keyboard = Keyboard{ .Key = kbd.none, .Char = "" }; // TODO: Check buffer size var keybuf: [13]u8 = undefined; flushIO(); var c: usize = 0; while (c == 0) { c = stdin.read(&keybuf) catch { Event.Key = kbd.none; return Event; }; } const view = std.unicode.Utf8View.init(keybuf[0..c]) catch { Event.Key = kbd.none; return Event; }; var iter = view.iterator(); // TODO: Find a better way to iterate buffer if (iter.nextCodepoint()) |c0| switch (c0) { '\x1b' => { if (iter.nextCodepoint()) |c1| switch (c1) { // fn (1 - 4) // O - 0x6f - 111 '\x4f' => { switch ((1 + keybuf[2] - '\x50')) { 1 => { Event.Key = kbd.F1; return Event; }, 2 => { Event.Key = kbd.F2; return Event; }, 3 => { Event.Key = kbd.F3; return Event; }, 4 => { Event.Key = kbd.F4; return Event; }, else => { Event.Key = kbd.none; return Event; }, } }, // csi '[' => { return parse_csiFunc(keybuf[2..c]); }, // alt key else => { switch (c1) { 'a' => { Event.Key = kbd.altA; return Event; }, 'b' => { Event.Key = kbd.altB; return Event; }, 'c' => { Event.Key = kbd.altC; return Event; }, 'd' => { Event.Key = kbd.altD; return Event; }, 'e' => { Event.Key = kbd.altE; return Event; }, 'f' => { Event.Key = kbd.altF; return Event; }, 'g' => { Event.Key = kbd.altG; return Event; }, 'h' => { Event.Key = kbd.altH; return Event; }, 'i' => { Event.Key = kbd.altI; return Event; }, 'j' => { Event.Key = kbd.altJ; return Event; }, 'k' => { Event.Key = kbd.altK; return Event; }, 'l' => { Event.Key = kbd.altL; return Event; }, 'm' => { Event.Key = kbd.altM; return Event; }, 'n' => { Event.Key = kbd.altN; return Event; }, 'o' => { Event.Key = kbd.altO; return Event; }, 'p' => { Event.Key = kbd.altP; return Event; }, 'q' => { Event.Key = kbd.altQ; return Event; }, 'r' => { Event.Key = kbd.altR; return Event; }, 's' => { Event.Key = kbd.altS; return Event; }, 't' => { Event.Key = kbd.altT; return Event; }, 'u' => { Event.Key = kbd.altU; return Event; }, 'v' => { Event.Key = kbd.altV; return Event; }, 'w' => { Event.Key = kbd.altW; return Event; }, 'x' => { Event.Key = kbd.altX; return Event; }, 'y' => { Event.Key = kbd.altY; return Event; }, 'z' => { Event.Key = kbd.altZ; return Event; }, else => { Event.Key = kbd.none; return Event; }, } }, } else { Event.Key = kbd.esc; return Event; } }, // ctrl keys ( crtl-i (x09) ctrl-m (x0d) ) '\x01'...'\x08', '\x0A'...'\x0C', '\x0E'...'\x1A' => { switch (c0 + '\x60') { 'a' => { Event.Key = kbd.ctrlA; return Event; }, 'b' => { Event.Key = kbd.ctrlB; return Event; }, 'c' => { Event.Key = kbd.ctrlC; return Event; }, 'd' => { Event.Key = kbd.ctrlD; return Event; }, 'e' => { Event.Key = kbd.ctrlE; return Event; }, 'f' => { Event.Key = kbd.ctrlF; return Event; }, 'g' => { Event.Key = kbd.ctrlG; return Event; }, 'h' => { Event.Key = kbd.ctrlH; return Event; }, // 'i' => { Event.Key = kbd.ctrlI; return Event; }, 'j' => { Event.Key = kbd.ctrlJ; return Event; }, 'k' => { Event.Key = kbd.ctrlK; return Event; }, 'l' => { Event.Key = kbd.ctrlL; return Event; }, // 'm' => { Event.Key = kbd.ctrlM; return Event; }, 'n' => { Event.Key = kbd.ctrlN; return Event; }, 'o' => { Event.Key = kbd.ctrlO; return Event; }, 'p' => { Event.Key = kbd.ctrlP; return Event; }, 'q' => { Event.Key = kbd.ctrlQ; return Event; }, 'r' => { Event.Key = kbd.ctrlR; return Event; }, 's' => { Event.Key = kbd.ctrlS; return Event; }, 't' => { Event.Key = kbd.ctrlT; return Event; }, 'u' => { Event.Key = kbd.ctrlU; return Event; }, 'v' => { Event.Key = kbd.ctrlV; return Event; }, 'w' => { Event.Key = kbd.ctrlW; return Event; }, 'x' => { Event.Key = kbd.ctrlX; return Event; }, 'y' => { Event.Key = kbd.ctrlY; return Event; }, 'z' => { Event.Key = kbd.ctrlZ; return Event; }, else => { Event.Key = kbd.none; return Event; }, } }, // tab '\x09' => { Event.Key = kbd.tab; return Event; }, // backspace '\x7f' => { Event.Key = kbd.backspace; return Event; }, // Enter '\x0d' => { Event.Key = kbd.enter; return Event; }, else => { // return Character UTF8 var vUnicode: []u8 = undefined; vUnicode = allocatorTerm.alloc(u8, 4) catch unreachable; const i = utf.utf8Encode(c0, vUnicode) catch { Event.Key = kbd.none; return Event; }; Event.Char = vUnicode[0..i]; Event.Key = kbd.char; return Event; }, }; Event.Key = kbd.none; return Event; } fn parse_csiFunc(csibuf: []const u8) Keyboard { // init var Event: Keyboard = Keyboard{ .Key = kbd.none, .Char = "" }; switch (csibuf[0]) { // keys 'A' => { Event.Key = kbd.up; return Event; }, 'B' => { Event.Key = kbd.down; return Event; }, 'C' => { Event.Key = kbd.right; return Event; }, 'D' => { Event.Key = kbd.left; return Event; }, 'H' => { Event.Key = kbd.home; return Event; }, 'F' => { Event.Key = kbd.end; return Event; }, '3' => { Event.Key = kbd.delete; return Event; }, 'Z' => { Event.Key = kbd.stab; return Event; }, '1'...'2' => { if (csibuf[1] == 126) { switch (csibuf[0]) { // insert '2' => { Event.Key = kbd.ins; return Event; }, else => { Event.Key = kbd.none; return Event; }, } } if (csibuf[2] == 126) { switch (csibuf[1]) { // f5..f12 '5' => { Event.Key = kbd.F5; return Event; }, '7' => { Event.Key = kbd.F6; return Event; }, '8' => { Event.Key = kbd.F7; return Event; }, '9' => { Event.Key = kbd.F8; return Event; }, '0' => { Event.Key = kbd.F9; return Event; }, '1' => { Event.Key = kbd.F10; return Event; }, '3' => { Event.Key = kbd.F11; return Event; }, '4' => { Event.Key = kbd.F12; return Event; }, else => { Event.Key = kbd.none; return Event; }, } } if (csibuf[2] == 50) { // f11..f14 and // shift switch (csibuf[3]) { 'P' => { Event.Key = kbd.F13; return Event; }, 'Q' => { Event.Key = kbd.F14; return Event; }, 'R' => { Event.Key = kbd.F15; return Event; }, 'S' => { Event.Key = kbd.F16; return Event; }, 'A' => { Event.Key = kbd.up; return Event; }, 'B' => { Event.Key = kbd.down; return Event; }, 'C' => { Event.Key = kbd.right; return Event; }, 'D' => { Event.Key = kbd.left; return Event; }, 'H' => { Event.Key = kbd.home; return Event; }, 'F' => { Event.Key = kbd.end; return Event; }, '3' => { Event.Key = kbd.delete; return Event; }, '5' => { Event.Key = kbd.pageUp; return Event; }, '6' => { Event.Key = kbd.pageDown; return Event; }, else => { Event.Key = kbd.none; return Event; }, } } if (csibuf[2] == 53) { // sihft ctrl switch (csibuf[3]) { 'A' => { Event.Key = kbd.up; return Event; }, 'B' => { Event.Key = kbd.down; return Event; }, 'C' => { Event.Key = kbd.right; return Event; }, 'D' => { Event.Key = kbd.left; return Event; }, 'H' => { Event.Key = kbd.home; return Event; }, '5' => { Event.Key = kbd.pageUp; return Event; }, '6' => { Event.Key = kbd.pageDown; return Event; }, else => { Event.Key = kbd.none; return Event; }, } } if (csibuf[2] == 54) { // sihft / controle switch (csibuf[3]) { 'A' => { Event.Key = kbd.up; return Event; }, 'B' => { Event.Key = kbd.down; return Event; }, 'C' => { Event.Key = kbd.right; return Event; }, 'D' => { Event.Key = kbd.left; return Event; }, 'H' => { Event.Key = kbd.home; return Event; }, '5' => { Event.Key = kbd.pageUp; return Event; }, '6' => { Event.Key = kbd.pageDown; return Event; }, else => { Event.Key = kbd.none; return Event; }, } } if (csibuf[2] == 60) { // f11..f14 switch (csibuf[3]) { 'P' => { Event.Key = kbd.F13; return Event; }, 'Q' => { Event.Key = kbd.F14; return Event; }, 'R' => { Event.Key = kbd.F15; return Event; }, 'S' => { Event.Key = kbd.F16; return Event; }, else => { Event.Key = kbd.none; return Event; }, } } if (csibuf[4] == 126) { // f15..f24 switch (csibuf[1]) { '5' => { Event.Key = kbd.F17; return Event; }, '7' => { Event.Key = kbd.F18; return Event; }, '8' => { Event.Key = kbd.F19; return Event; }, '9' => { Event.Key = kbd.F20; return Event; }, '0' => { Event.Key = kbd.F21; return Event; }, '1' => { Event.Key = kbd.F22; return Event; }, '3' => { Event.Key = kbd.F23; return Event; }, '4' => { Event.Key = kbd.F24; return Event; }, else => { Event.Key = kbd.none; return Event; }, } } }, '5'...'6' => { if (csibuf[1] == 126) { switch (csibuf[0]) { '5' => { Event.Key = kbd.pageUp; return Event; }, '6' => { Event.Key = kbd.pageDown; return Event; }, else => { Event.Key = kbd.none; return Event; }, } } if (csibuf[3] == 126) { switch (csibuf[2]) { '5' => { Event.Key = kbd.pageUp; return Event; }, '6' => { Event.Key = kbd.pageDown; return Event; }, else => { Event.Key = kbd.none; return Event; }, } } }, '<' => { // mouse MouseInfo.action = MouseAction.maNone; MouseInfo.button = MouseButton.mbNone; MouseInfo.scrollDir = ScrollDirection.msNone; MouseInfo.scroll = false; MouseInfo.x = 0; MouseInfo.y = 0; Event.Key = kbd.mouse; Event.Char = ""; var i: usize = 3; while (true) { if (csibuf[i] != 59 and MouseInfo.y == 0) MouseInfo.y = convIntMouse(csibuf[3]); if (csibuf[i] == 59) break; if (csibuf[i] != 59 and i > 3) MouseInfo.y = (MouseInfo.y * 10) + convIntMouse(csibuf[i]); i += 1; } var u: usize = i + 1; while (true) { if (csibuf[u] != 59 and MouseInfo.x == 0) MouseInfo.x = convIntMouse(csibuf[u]); if (csibuf[u] == 59 or csibuf[u] == 77 or csibuf[u] == 109) break; if (csibuf[u] != 59 and u > (i + 1)) MouseInfo.x = (MouseInfo.x * 10) + convIntMouse(csibuf[u]); u += 1; } if (csibuf.len == 7) { if (csibuf[6] == 77) MouseInfo.action = MouseAction.maPressed; if (csibuf[6] == 109) MouseInfo.action = MouseAction.maReleased; } if (csibuf.len == 8) { if (csibuf[7] == 77) MouseInfo.action = MouseAction.maPressed; if (csibuf[7] == 109) MouseInfo.action = MouseAction.maReleased; } if (csibuf.len == 9) { if (csibuf[8] == 77) MouseInfo.action = MouseAction.maPressed; if (csibuf[8] == 109) MouseInfo.action = MouseAction.maReleased; } if (csibuf.len == 10) { if (csibuf[9] == 77) MouseInfo.action = MouseAction.maPressed; if (csibuf[9] == 109) MouseInfo.action = MouseAction.maReleased; } if (csibuf[1] == 48) MouseInfo.button = MouseButton.mbLeft; if (csibuf[1] == 49) MouseInfo.button = MouseButton.mbMiddle; if (csibuf[1] == 50) MouseInfo.button = MouseButton.mbRight; if (csibuf[1] == 54 and csibuf[2] == 52) { MouseInfo.scroll = true; MouseInfo.scrollDir = ScrollDirection.msUp; MouseInfo.x = 0; MouseInfo.y = 0; } if (csibuf[1] == 54 and csibuf[2] == 53) { MouseInfo.scroll = true; MouseInfo.scrollDir = ScrollDirection.msDown; MouseInfo.x = 0; MouseInfo.y = 0; } return Event; }, else => { Event.Key = kbd.none; return Event; }, } Event.Key = kbd.none; return Event; } };
0
repos/zig_demoJson/library
repos/zig_demoJson/library/curse/forms.zig
///----------------------- /// forms /// Label /// button /// cadre /// field /// panel /// zig 0.12.0 dev ///----------------------- const std = @import("std"); const utf = @import("std").unicode; const kbd = @import("cursed").kbd; const term= @import("cursed"); const utl = @import("utils"); const reg = @import("match"); const os = std.os; const io = std.io; const Child = @import("std").ChildProcess; ///------------------------------- /// FORMS ///------------------------------- // for panel all arraylist (forms. label button line field pnl:) var arenaForms = std.heap.ArenaAllocator.init(std.heap.page_allocator); pub var allocatorForms = arenaForms.allocator(); pub fn deinitForms() void { arenaForms.deinit(); arenaForms = std.heap.ArenaAllocator.init(std.heap.page_allocator); allocatorForms = arenaForms.allocator(); } pub const CTRUE = "✔"; pub const CFALSE = "◉"; pub const LINE = enum { line1, line2 }; pub const CADRE = enum { line0, line1, line2 }; pub const REFTYP = enum { TEXT_FREE, // Free TEXT_FULL, // Letter Digit Char-special ALPHA, // Letter ALPHA_UPPER, // Letter ALPHA_NUMERIC, // Letter Digit espace - ALPHA_NUMERIC_UPPER,// Letter Digit espace - PASSWORD, // Letter Digit and normaliz char-special YES_NO, // 'y' or 'Y' / 'o' or 'O' UDIGIT, // Digit unsigned DIGIT, // Digit signed UDECIMAL, // Decimal unsigned DECIMAL, // Decimal signed DATE_ISO, // YYYY/MM/DD DATE_FR, // DD/MM/YYYY DATE_US, // MM/DD/YYYY TELEPHONE, // (+123) 6 00 01 00 02 MAIL_ISO, // normalize regex SWITCH, // CTRUE CFALSE FUNC, // call Function }; // function special for developpeur pub fn debeug(vline : usize, buf: [] const u8) void { const AtrDebug : term.ZONATRB = .{ .styled=[_]u32{@intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle)}, .backgr = term.BackgroundColor.bgBlack, .foregr = term.ForegroundColor.fgYellow }; term.getCursor(); const Xterm = term.getSize(); term.gotoXY(Xterm.height,1) ; const allocator = std.heap.page_allocator; const msg =std.fmt.allocPrint(allocator,"line_src:{d} {s} ",.{vline, buf}) catch |err| { @panic(@errorName(err));}; term.writeStyled(msg,AtrDebug); _=term.kbd.getKEY(); term.gotoXY(term.posCurs.x,term.posCurs.y); allocator.free(msg); } /// Errors that may occur when using String pub const ErrForms = error{ lbl_getIndex_Name_Label_Invalide, lbl_getName_Index_invalide, lbl_getPosx_Index_invalide, lbl_getPosy_Index_invalide, lbl_getText_Index_invalide, lbl_getActif_Index_invalide, lbl_setText_Index_invalide, lbl_setActif_Index_invalide, lbl_updateText_Index_invalide, lbl_dltRows_Index_invalide, line_getIndex_Name_Vertical_Invalide, line_getIndex_Name_Horizontal_Invalide, btn_getIndex_Key_Button_Invalide, btn_getName_Index_invalide, btn_getKey_Index_invalide, btn_getShow_Index_invalide, btn_getText_Index_invalide, btn_getCheck_Index_invalide, btn_getActif_Index_invalide, btn_setShow_Index_invalide, btn_setText_Index_invalide, btn_setCheck_Index_invalide, btn_setActif_Index_invalide, btn_dltRows_Index_invalide, fld_getIndex_Name_Field_Invalide, fld_getName_Index_invalide, fld_getPosx_Index_invalide, fld_getPosy_Index_invalide, fld_getRefType_Index_invalide, fld_getWidth_Index_invalide, fld_getScal_Index_invalide, fld_getNbrCar_Index_invalide, fld_getRequier_Index_invalide, fld_getProtect_Index_invalide, fld_getPading_Index_invalide, fld_getEdtcar_Index_invalide, fld_getRegex_Index_invalide, fld_getErrMsg_Index_invalide, fld_getHelp_Index_invalide, fld_getText_Index_invalide, fld_getSwitch_Index_invalide, fld_getErr_Index_invalide, fld_getFunc_Index_invalide, fld_getTask_Index_invalide, fld_getCall_Index_invalide, fld_getTypeCall_Index_invalide, fld_getParmCall_Index_invalide, fld_getAttribut_Index_invalide, fld_getAtrProtect_Index_invalide, fld_getActif_Index_invalide, fld_setText_Index_invalide, fld_setName_Index_invalide, fld_setRefType_Index_invalide, fld_setWidth_Index_invalide, fld_setSwitch_Index_invalide, fld_setProtect_Index_invalide, fld_setRequier_Index_invalide, fld_setEdtcar_Index_invalide, fld_setRegex_Index_invalide, fld_setTask_Index_invalide, fld_setCall_Index_invalide, fld_setTypeCall_Index_invalide, fld_setParmCall_Index_invalide, fld_setActif_Index_invalide, fld_dltRows_Index_invalide, Invalide_subStrForms_Index, Invlide_subStrForms_pos, }; // Shows serious programming errors pub const dsperr = struct { pub fn errorForms(vpnl: *pnl.PANEL, errpgm :anyerror ) void { // define attribut default MSG Error const MsgErr : term.ZONATRB = .{ .styled=[_]u32{@intFromEnum(term.Style.styleBlink), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle)}, .backgr = term.BackgroundColor.bgBlack, .foregr = term.ForegroundColor.fgYellow, }; const allocator = std.heap.page_allocator; const errTxt:[]const u8 = std.fmt.allocPrint(allocator,"{any}",.{errpgm }) catch |err| { @panic(@errorName(err));}; defer allocator.free(errTxt); const x: usize = vpnl.lines; var n: usize = vpnl.cols * (x - 2) ; var y: usize = 1 ; var msgerr:[]const u8 = utl.concatStr("Info : ", errTxt) ; var boucle : bool= true ; if (vpnl.cols < (msgerr.len) ) msgerr = subStrForms(msgerr, 0, vpnl.cols - 2); // clear line button while (y <= (vpnl.cols - 2) ) : (y += 1) { term.gotoXY(vpnl.posx + x - 2 , y + vpnl.posy ); term.writeStyled(" ",vpnl.attribut); } // display msgerr y = 1 ; term.gotoXY(vpnl.posx + x - 2, y + vpnl.posy ); term.writeStyled(msgerr,MsgErr); while (boucle) { const e_key = kbd.getKEY(); switch ( e_key.Key ) { .esc=>boucle = false, else => {}, } } // restore line panel while (y <= (vpnl.cols - 2)) : (y += 1) { n += 1; term.gotoXY( vpnl.posx + x - 2, y + vpnl.posy ); term.writeStyled(vpnl.buf.items[n].ch,vpnl.buf.items[n].attribut); } } }; // buffer terminal MATRIX const TERMINAL_CHAR = struct { ch : [] const u8, attribut:term.ZONATRB, on:bool }; pub fn subStrForms( a: []const u8,pos: usize, n:usize) []const u8 { if (n == 0 or n > a.len) {@panic(@errorName(ErrForms.Invalide_subStrForms_Index));} if (pos > a.len) {@panic(@errorName(ErrForms.Invlide_subStrForms_pos));} const allocator = std.heap.page_allocator; const result = allocator.alloc(u8, n - pos) catch |err| { @panic(@errorName(err));}; defer allocator.free(result); @memcpy(result, a[pos..n]); return std.fmt.allocPrint(allocator ,"{s}",.{result},) catch |err| { @panic(@errorName(err));}; } // function special for developpeur // activat fld.myMouse = true // read ioField -> getKEY() pub fn dspMouse(vpnl: *pnl.PANEL) void { const AtrDebug: term.ZONATRB = .{ .styled = [_]u32{ @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle) }, .backgr = term.BackgroundColor.bgBlack, .foregr = term.ForegroundColor.fgRed, }; const allocator = std.heap.page_allocator; const msg = std.fmt.allocPrint(allocator, "{d:0>2}{s}{d:0>3}", .{ term.MouseInfo.x, "/", term.MouseInfo.y }) catch |err| { @panic(@errorName(err));}; term.gotoXY(vpnl.posx + vpnl.lines - 1, (vpnl.posy + vpnl.cols - 1) - 7); term.writeStyled(msg, AtrDebug); term.gotoXY(term.MouseInfo.x, term.MouseInfo.y); allocator.free(msg); } // function special for developpeur pub fn dspCursor(vpnl: *pnl.PANEL, x_posx: usize, x_posy: usize, text:[] const u8) void { const AtrDebug: term.ZONATRB = .{ .styled = [_]u32{ @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle) }, .backgr = term.BackgroundColor.bgBlack, .foregr = term.ForegroundColor.fgRed, }; if (std.mem.eql(u8, text, "") == false ) { term.gotoXY(vpnl.posx + vpnl.lines - 1, (vpnl.posy + vpnl.cols - 1) / 2); term.writeStyled(text, AtrDebug); } const allocator = std.heap.page_allocator; const msg = std.fmt.allocPrint(allocator, "{d:0>2}{s}{d:0>3}", .{ x_posx, "/", x_posy }) catch |err| { @panic(@errorName(err));}; term.gotoXY(vpnl.posx + vpnl.lines - 1, (vpnl.posy + vpnl.cols - 1) - 7); term.writeStyled(msg, AtrDebug); term.gotoXY(x_posx, x_posy); allocator.free(msg); } // defined Label pub const lbl = struct { // define attribut default LABEL pub var AtrLabel : term.ZONATRB = .{ .styled=[_]u32{@intFromEnum(term.Style.styleDim), @intFromEnum(term.Style.styleItalic), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle)}, .backgr = term.BackgroundColor.bgBlack, .foregr = term.ForegroundColor.fgGreen, }; // define attribut default TITLE pub var AtrTitle : term.ZONATRB = .{ .styled=[_]u32{@intFromEnum(term.Style.styleBold), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle)}, .backgr = term.BackgroundColor.bgBlack, .foregr = term.ForegroundColor.fgGreen, }; pub const LABEL = struct { name : []const u8, posx: usize, posy: usize, attribut:term.ZONATRB, text: []const u8, title: bool, actif: bool }; pub const Elabel = enum { name, posx, posy, text, title }; // New LABEL pub fn newLabel(vname: [] const u8, vposx:usize, vposy:usize, vtext: [] const u8) LABEL { const xlabel = LABEL { .name = vname, .posx = vposx , .posy = vposy, .attribut = AtrLabel, .text = vtext, .title = false, .actif = true, }; return xlabel; } // New LABEL-TITLE pub fn newTitle(vname: [] const u8, vposx:usize, vposy:usize, vtext: [] const u8) LABEL { const xlabel = LABEL { .name = vname, .posx = vposx , .posy = vposy, .attribut = AtrTitle, .text = vtext, .title = true, .actif = true, }; return xlabel; } // return index-label ---> arraylist panel-label pub fn getIndex(vpnl: *pnl.PANEL , name: [] const u8 ) ErrForms ! usize { for (vpnl.label.items, 0..) |l, idx| { if (std.mem.eql(u8, l.name, name)) return idx ; } return ErrForms.lbl_getIndex_Name_Label_Invalide; } // return name-label ---> arraylist panel-label pub fn getName(vpnl: *pnl.PANEL , n: usize) ErrForms ! [] const u8 { if ( n < vpnl.label.items.len) return vpnl.label.items[n].name; return ErrForms.lbl_getName_Index_invalide ; } // return posx-label ---> arraylist panel-label pub fn getPosx(vpnl: *pnl.PANEL , n: usize) ErrForms ! usize { if ( n < vpnl.label.items.len) return vpnl.label.items[n].posx; return ErrForms.lbl_getPosx_Index_invalide ; } // return posy-label ---> arraylist panel-label pub fn getPosy(vpnl: *pnl.PANEL , n: usize) ErrForms ! usize { if ( n < vpnl.label.items.len) return vpnl.label.items[n].posy; return ErrForms.lbl_getPosy_Index_invalide ; } // return Text-label ---> arraylist panel-label pub fn getText(vpnl: *pnl.PANEL , n: usize) ErrForms ! usize { if ( n < vpnl.label.items.len) return vpnl.label.items[n].text; return ErrForms.lbl_getText_Index_invalide ; } // return ON/OFF-label ---> arraylist panel-label pub fn getActif(vpnl: *pnl.PANEL , n: usize) ErrForms ! bool { if ( n < vpnl.label.items.len) return vpnl.label.items[n].actif; return ErrForms.lbl_getActif_Index_invalide ; } // Set TEXT -label ---> arraylist panel-label pub fn setText(vpnl: *pnl.PANEL , n: usize, val:[] const u8) ErrForms ! void { if ( n < vpnl.label.items.len) vpnl.label.items[n].text = val else return ErrForms.lbl_setText_Index_invalide; } // Set ON/OFF -label ---> arraylist panel-label pub fn setActif(vpnl: *pnl.PANEL , n: usize, val :bool) ErrForms ! void { if ( n < vpnl.label.items.len) vpnl.label.items[n].actif = val else return ErrForms.lbl_setActif_Index_invalide; } // delete -label ---> arraylist panel-label pub fn dltRows(vpnl: *pnl.PANEL, n :usize ) ErrForms ! void { if ( n < vpnl.label.items.len) _= vpnl.label.orderedRemove(n) else return ErrForms.lbl_dltRows_Index_invalide; } // update Label and Display ---> arraylist panel-label pub fn updateText(vpnl: *pnl.PANEL , n: usize, val:[] const u8) ErrForms ! void { if ( n < vpnl.label.items.len) { clsLabel(vpnl, vpnl.label.items[n]); vpnl.label.items[n].text = val; printLabel(vpnl, vpnl.label.items[n]); displayLabel(vpnl, vpnl.label.items[n]); } else return ErrForms.lbl_updateText_Index_invalide; } // assign -label MATRIX TERMINAL ---> arraylist panel-label pub fn printLabel(vpnl: *pnl.PANEL, vlbl : LABEL ) void { var n = (vpnl.cols * (vlbl.posx - 1)) + vlbl.posy - 1; var iter = utl.iteratStr.iterator(vlbl.text); defer iter.deinit(); while (iter.next()) |ch| { if (vlbl.actif == true) { vpnl.buf.items[n].ch = std.fmt.allocPrint(allocatorForms,"{s}",.{ch}) catch unreachable; vpnl.buf.items[n].attribut = vlbl.attribut; vpnl.buf.items[n].on = true; } else { vpnl.buf.items[n].ch = ""; vpnl.buf.items[n].attribut = vpnl.attribut; vpnl.buf.items[n].on = false; } n += 1; } } // matrix cleaning from label pub fn clsLabel(vpnl: *pnl.PANEL, vlbl : LABEL ) void { // display matrice PANEL if (vpnl.actif == false ) return ; if (vlbl.actif == false ) return ; const x :usize = vlbl.posx - 1; const y :usize = vlbl.posy - 1; const vlen = utl.nbrCharStr(vlbl.text); var n :usize = 0; var npos :usize = (vpnl.cols * (vlbl.posx - 1)) + vlbl.posy - 1 ; while (n < vlen) : (n += 1) { vpnl.buf.items[npos].ch = " "; vpnl.buf.items[npos].attribut = vpnl.attribut; vpnl.buf.items[npos].on = false; term.gotoXY(x + vpnl.posx , y + vpnl.posy + n ); term.writeStyled(vpnl.buf.items[npos].ch,vpnl.buf.items[npos].attribut); npos += 1; } } // display MATRIX to terminal ---> arraylist panel-label fn displayLabel(vpnl: *pnl.PANEL, vlbl : LABEL ) void { // display matrice PANEL if (vpnl.actif == false ) return ; const x :usize = vlbl.posx - 1 ; const y :usize = vlbl.posy - 1; const vlen = utl.nbrCharStr(vlbl.text); var n :usize = 0; var npos :usize = (vpnl.cols * vlbl.posx) + vlbl.posy - 1 ; while (n < vlen) : (n += 1) { term.gotoXY(x + vpnl.posx , y + vpnl.posy + n ); term.writeStyled(vpnl.buf.items[npos].ch,vpnl.buf.items[npos].attribut); npos += 1; } } }; // defined Trait and Frame for Panel pub const frm = struct { // define attribut default FRAME pub var AtrFrame : term.ZONATRB = .{ .styled=[_]u32{@intFromEnum(term.Style.styleDim), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle)}, .backgr = term.BackgroundColor.bgBlack, .foregr = term.ForegroundColor.fgRed }; // define attribut default TITLE FRAME pub var AtrTitle : term.ZONATRB = .{ .styled=[_]u32{@intFromEnum(term.Style.styleBold), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle)}, .backgr = term.BackgroundColor.bgWhite, .foregr = term.ForegroundColor.fgBlue }; /// FRAME pub const FRAME = struct { name: []const u8, posx: usize, posy: usize, lines: usize, cols: usize, cadre: CADRE, attribut:term.ZONATRB, title: []const u8, titleAttribut: term.ZONATRB, actif: bool }; // define Fram pub fn newFrame(vname:[]const u8, vposx:usize, vposy:usize, vlines:usize, vcols:usize, vcadre:CADRE, vattribut:term.ZONATRB, vtitle:[]const u8, vtitleAttribut:term.ZONATRB, ) FRAME { const xframe = FRAME { .name = vname, .posx = vposx, .posy = vposy, .lines = vlines, .cols = vcols, .cadre = vcadre, .attribut = vattribut, .title = vtitle, .titleAttribut = vtitleAttribut, .actif = true }; return xframe; } // write MATRIX TERMINAL ---> arraylist panel-fram pub fn printFrame(vpnl : *pnl.PANEL , vfram: FRAME) void { // assigne FRAME to init matrice for display if (CADRE.line0 == vfram.cadre ) return ; const ACS_Hlines = "─"; const ACS_Vlines = "│"; const ACS_UCLEFT = "┌"; const ACS_UCRIGHT = "┐"; const ACS_LCLEFT = "└"; const ACS_LCRIGHT = "┘"; const ACS_Hline2 = "═"; const ACS_Vline2 = "║"; const ACS_UCLEFT2 = "╔"; const ACS_UCRIGHT2 = "╗"; const ACS_LCLEFT2 = "╚"; const ACS_LCRIGHT2 = "╝"; var trait: []const u8 = ""; var edt :bool = undefined ; var row: usize = 1 ; var y: usize = 0 ; var col: usize = 0 ; var npos: usize = 0 ; const wlen : usize = utl.nbrCharStr(vfram.title); var n: usize = 0 ; var x:usize = vfram.posx - 1 ; while (row <= vfram.lines) { y = vfram.posy - 1; col = 1; while ( col <= vfram.cols ){ edt = false; if (row == 1) { if (col == 1) { if ( CADRE.line1 == vfram.cadre ) { trait = ACS_UCLEFT; } else trait = ACS_UCLEFT2 ; edt = true; } if ( col == vfram.cols ) { if (CADRE.line1 == vfram.cadre) { trait = ACS_UCRIGHT; } else trait = ACS_UCRIGHT2 ; edt = true; } if ( col > 1 and col < vfram.cols ) { if (CADRE.line1 == vfram.cadre ) { trait = ACS_Hlines; } else trait = ACS_Hline2; edt = true; } } else if ( row == vfram.lines ) { if (col == 1) { if ( CADRE.line1 == vfram.cadre ) { trait = ACS_LCLEFT; } else trait = ACS_LCLEFT2; edt = true; } if ( col == vfram.cols ) { if ( CADRE.line1 == vfram.cadre ) { trait = ACS_LCRIGHT; } else trait = ACS_LCRIGHT2 ; edt = true ; } if ( col > 1 and col < vfram.cols ) { if ( CADRE.line1 == vfram.cadre ) { trait = ACS_Hlines; } else trait = ACS_Hline2 ; edt = true; } } else if ( row > 1 and row < vfram.lines ) { if ( col == 1 or col == vfram.cols ) { if ( CADRE.line1 == vfram.cadre ) { trait = ACS_Vlines; } else trait = ACS_Vline2 ; edt = true; } } if ( edt ) { npos = vfram.cols * x; n = npos + y; vpnl.buf.items[n].ch = trait ; vpnl.buf.items[n].attribut = vfram.attribut; vpnl.buf.items[n].on = true; } y += 1; col += 1; } x += 1; row +=1 ; } if (wlen > vfram.cols - 2 or wlen == 0 ) return ; npos = vfram.posx; n = npos + (((vfram.cols - wlen ) / 2)) - 1 ; var iter = utl.iteratStr.iterator(vfram.title); defer iter.deinit(); while (iter.next()) |ch| { vpnl.buf.items[n].ch = std.fmt.allocPrint(allocatorForms,"{s}",.{ch}) catch unreachable; vpnl.buf.items[n].attribut = vfram.titleAttribut; vpnl.buf.items[n].on = true; n +=1; } } }; // defined Line and vertical for Panel pub const lnv = struct { // define attribut default FRAME pub var AtrLine : term.ZONATRB = .{ .styled=[_]u32{@intFromEnum(term.Style.styleDim), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle)}, .backgr = term.BackgroundColor.bgBlack, .foregr = term.ForegroundColor.fgYellow }; pub const Elinev = enum { name, posx, posy, lng, trace }; /// LINE VERTICAL pub const LINEV = struct { name : []const u8, posx: usize, posy: usize, lng: usize, trace: LINE, attribut:term.ZONATRB, actif: bool }; // define Fram pub fn newLine(vname:[]const u8, vposx:usize, vposy:usize, vlng:usize, vtrace:LINE, ) LINEV { const xframe = LINEV { .name = vname, .posx = vposx, .posy = vposy, .lng = vlng, .trace = vtrace, .attribut = AtrLine, .actif = true }; return xframe; } // write MATRIX TERMINAL ---> arraylist panel-line pub fn printLine(vpnl : *pnl.PANEL , vline: LINEV) void { if (vpnl.actif == false ) return ; if (vline.actif == false ) return ; // assigne FRAMELINE VERTICAL const ACS_Vlines = "│"; const ACS_Vline2 = "║"; var row: usize = 0 ; var x: usize = vline.posx - 1 ; var trait: []const u8 = ""; var n : usize = (vpnl.cols * (vline.posx - 1)) + vline.posy - 1 ; while (row <= vline.lng) { if ( LINE.line1 == vline.trace ) { trait = ACS_Vlines; } else trait = ACS_Vline2 ; vpnl.buf.items[n].ch = trait ; vpnl.buf.items[n].attribut = vline.attribut; vpnl.buf.items[n].on = true; row +=1 ; x += 1; n = (vpnl.cols * x ) + vline.posy - 1 ; } } // return index-LINE ---> arraylist panel-line pub fn getIndex(vpnl: *pnl.PANEL , name: [] const u8 ) ErrForms ! usize { for (vpnl.linev.items, 0..) |l, idx| { if (std.mem.eql(u8, l.name, name)) return idx ; } return ErrForms.line_getIndex_Name_Vertical_Invalide; } }; // defined Line and horizontal for Panel pub const lnh = struct { // define attribut default FRAME pub var AtrLine : term.ZONATRB = .{ .styled=[_]u32{@intFromEnum(term.Style.styleDim), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle)}, .backgr = term.BackgroundColor.bgBlack, .foregr = term.ForegroundColor.fgYellow }; pub const Elineh = enum { name, posx, posy, lng, trace }; /// LINE HORIZONTAL pub const LINEH = struct { name : []const u8, posx: usize, posy: usize, lng: usize, trace: LINE, attribut:term.ZONATRB, actif: bool }; // define Fram pub fn newLine(vname:[]const u8, vposx:usize, vposy:usize, vlng:usize, vtrace:LINE, ) LINEH { const xframe = LINEH { .name = vname, .posx = vposx, .posy = vposy, .lng = vlng, .trace = vtrace, .attribut = AtrLine, .actif = true }; return xframe; } // write MATRIX TERMINAL ---> arraylist panel-line pub fn printLine(vpnl : *pnl.PANEL , vline: LINEH) void { if (vpnl.actif == false ) return ; if (vline.actif == false ) return ; // assigne FRAMELINE HORIZONTAL const ACS_Hlines = "─"; const ACS_Hline2 = "═"; var coln: usize = 0 ; var n: usize = 0 ; var trait: []const u8 = ""; n = (vpnl.cols * (vline.posx - 1)) + vline.posy - 1 ; while (coln <= vline.lng) { if ( LINE.line1 == vline.trace ) { trait = ACS_Hlines; } else trait = ACS_Hline2 ; vpnl.buf.items[n].ch = trait ; vpnl.buf.items[n].attribut = vline.attribut; vpnl.buf.items[n].on = true; coln +=1 ; n += 1; } } // return index-LINE ---> arraylist panel-line pub fn getIndex(vpnl: *pnl.PANEL , name: [] const u8 ) ErrForms ! usize { for (vpnl.lineh.items, 0..) |l, idx| { if (std.mem.eql(u8, l.name, name)) return idx ; } return ErrForms.line_getIndex_Name_Horizontal_Invalide; } }; // defined button pub const btn = struct{ // nbr espace intercaler pub var btnspc : usize =3 ; // define attribut default PANEL pub var AtrButton : term.ZONATRB = .{ .styled=[_]u32{@intFromEnum(term.Style.styleDim), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle)}, .backgr = term.BackgroundColor.bgBlack, .foregr = term.ForegroundColor.fgRed }; pub var AtrTitle : term.ZONATRB = .{ .styled=[_]u32{@intFromEnum(term.Style.styleDim), @intFromEnum(term.Style.styleItalic), @intFromEnum(term.Style.styleUnderscore), @intFromEnum(term.Style.notStyle)}, .backgr = term.BackgroundColor.bgBlack, .foregr = term.ForegroundColor.fgdCyan, }; // define BUTTON pub const BUTTON = struct { name: [] const u8, key : kbd, show: bool, check: bool, title: []const u8, attribut:term.ZONATRB, titleAttribut: term.ZONATRB, actif: bool, }; pub const Ebutton = enum { name, key, show, check, title }; // func BUTTON pub fn newButton( vkey : kbd, vshow : bool, vcheck:bool, vtitle: [] const u8) BUTTON { const xbutton = BUTTON { .name = kbd.enumToStr(vkey), .key = vkey, .show = vshow, .check = vcheck, .title = vtitle, .attribut = AtrButton, .titleAttribut = AtrTitle, .actif = true }; return xbutton; } // return index-button ---> arraylist panel-button pub fn getIndex(vpnl: *pnl.PANEL , key: kbd ) ErrForms ! usize { for (vpnl.button.items, 0..) |b ,idx | { if (b.key == key) return idx; } return ErrForms.btn_getIndex_Key_Button_Invalide; } // return name-button ---> arraylist panel-button pub fn getName(vpnl: *pnl.PANEL , n: usize) ErrForms ! [] const u8 { if ( n < vpnl.button.items.len) return vpnl.button.items[n].name; return ErrForms.btn_getName_Index_invalide ; } // return key-button ---> arraylist panel-button pub fn getKey(vpnl: *pnl.PANEL , n: usize) ErrForms ! kbd { if ( n < vpnl.button.items.len) return vpnl.button.items[n].key; return ErrForms.btn_getKey_Index_invalide ; } // return show-button ---> arraylist panel-button pub fn getShow(vpnl: *pnl.PANEL , n: usize) ErrForms ! bool { if ( n < vpnl.button.items.len) return vpnl.button.items[n].show; return ErrForms.btn_getShow_Index_invalide ; } // return text-button ---> arraylist panel-button pub fn getTitle(vpnl: *pnl.PANEL , n: usize) ErrForms ! [] const u8 { if ( n < vpnl.button.items.len) return vpnl.button.items[n].title; return ErrForms.btn_getText_Index_invalide ; } // return check-button ---> arraylist panel-button // work for field input-field pub fn getCheck(vpnl: *pnl.PANEL , n: usize) ErrForms ! bool { if ( n < vpnl.button.items.len) return vpnl.button.items[n].check; return ErrForms.btn_getCheck_Index_invalide ; } // return ON/OFF-button ---> arraylist panel-button pub fn getActif(vpnl: *pnl.PANEL , n: usize) ErrForms ! bool { if ( n < vpnl.button.items.len) return vpnl.button.items[n].actif; return ErrForms.btn_getActif_Index_invalide ; } // set show-button ---> arraylist panel-button pub fn setShow(vpnl: *pnl.PANEL , n: usize, val :bool) ErrForms ! void { if ( n < vpnl.button.items.len) vpnl.button.items[n].show = val else return ErrForms.btn_setShow_Index_invalide ; } // set text-button ---> arraylist panel-button pub fn setText(vpnl: *pnl.PANEL , n: usize, val:[] const u8) ErrForms ! void { if ( n < vpnl.button.items.len) vpnl.button.items[n].text = val else return ErrForms.btn_setText_Index_invalide ; } // set chek-button ---> arraylist panel-button pub fn setCheck(vpnl: *pnl.PANEL , n: usize, val :bool) ErrForms ! void { if ( n < vpnl.button.items.len) vpnl.button.items[n].check = val else return ErrForms.btn_setCheck_Index_invalide ; } // set ON/OFF-button ---> arraylist panel-button pub fn setActif(vpnl: *pnl.PANEL , n: usize, val :bool) ErrForms ! void { if ( n < vpnl.button.items.len) vpnl.button.items[n].actif = val else return ErrForms.btn_setActif_Index_invalide ; } // delete -button ---> arraylist panel-button pub fn dltRows(vpnl:*pnl.PANEL, n :usize ) ErrForms ! void { if ( n < vpnl.button.items.len) _= vpnl.button.orderedRemove(n) else return ErrForms.btn_dltRows_Index_invalide ; } // assign -button MATRIX TERMINAL ---> arraylist panel-button pub fn printButton(vpnl: *pnl.PANEL) void { if (vpnl.actif == false ) return ; const espace :usize = 3; var x :usize = 0; var y :usize = 0; if (vpnl.frame.cadre == CADRE.line0 ) { x = vpnl.lines - 1; y = 1; } else { x = vpnl.lines - 2; y = 2; } const npos : usize = vpnl.cols * x ; var n = npos + y; for (vpnl.button.items) |button| { if (button.show == true) { // text Function KEY var iter = utl.iteratStr.iterator(button.name); defer iter.deinit(); while (iter.next()) |ch| { if (button.actif == true) { vpnl.buf.items[n].ch = std.fmt.allocPrint(allocatorForms,"{s}",.{ch}) catch unreachable; vpnl.buf.items[n].attribut = button.attribut; vpnl.buf.items[n].on = true; } else { vpnl.buf.items[n].ch = " "; vpnl.buf.items[n].attribut = vpnl.attribut; vpnl.buf.items[n].on = false; } n += 1; } n += 1; //text Title button iter = utl.iteratStr.iterator(button.title); while (iter.next()) |ch| { if (button.actif == true) { vpnl.buf.items[n].ch = std.fmt.allocPrint(allocatorForms,"{s}",.{ch}) catch unreachable; vpnl.buf.items[n].attribut = button.titleAttribut; vpnl.buf.items[n].on = true; } else { vpnl.buf.items[n].ch = " "; vpnl.buf.items[n].attribut = vpnl.attribut; vpnl.buf.items[n].on = false; } n += 1; } n += espace; } } } }; // defined INPUT_FIELD pub const fld = struct { pub fn ToStr(text : [] const u8 ) []const u8 { return std.fmt.allocPrint(allocatorForms,"{s}",.{text}) catch |err| { @panic(@errorName(err));}; } // define attribut default Field pub var AtrField : term.ZONATRB = .{ .styled=[_]u32{@intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle)}, .backgr = term.BackgroundColor.bgBlack, .foregr = term.ForegroundColor.fgWhite }; // field not input pub var AtrNil : term.ZONATRB = .{ .styled=[_]u32{@intFromEnum(term.Style.styleDim), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle)}, .backgr = term.BackgroundColor.bgBlack, .foregr = term.ForegroundColor.fgWhite }; // define attribut default func ioField pub var AtrIO : term.ZONATRB = .{ .styled=[_]u32{@intFromEnum(term.Style.styleReverse ), @intFromEnum(term.Style.styleDim), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle)}, .backgr = term.BackgroundColor.bgBlack, .foregr = term.ForegroundColor.fgWhite, }; // define attribut default Field protect pub var AtrProtect : term.ZONATRB = .{ .styled=[_]u32{@intFromEnum(term.Style.styleItalic), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle)}, .backgr = term.BackgroundColor.bgBlack, .foregr = term.ForegroundColor.fgCyan, }; // associated field and call program pub var AtrCall : term.ZONATRB = .{ .styled=[_]u32{@intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle)}, .backgr = term.BackgroundColor.bgBlack, .foregr = term.ForegroundColor.fgYellow }; pub var AtrCursor : term.ZONATRB = .{ .styled=[_]u32{@intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle)}, .backgr = term.BackgroundColor.bgBlack, .foregr = term.ForegroundColor.fgCyan, }; pub var MsgErr : term.ZONATRB = .{ .styled=[_]u32{@intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle)}, .backgr = term.BackgroundColor.bgBlack, .foregr = term.ForegroundColor.fgRed }; /// define FIELD pub const FIELD = struct { name : []const u8, posx: usize, posy: usize, attribut:term.ZONATRB, atrProtect:term.ZONATRB, atrCall:term.ZONATRB, reftyp: REFTYP, width: usize, scal: usize, nbrcar: usize, // nbrcar DECIMAL = (precision+scale + 1'.' ) + 1 this signed || other nbrcar = ALPA..DIGIT.. requier: bool, // requier or FULL protect: bool, // only display pading: bool, // pading blank edtcar: []const u8, // edtcar for monnaie € $ ¥ ₪ £ or % regex: []const u8, //contrôle regex errmsg: []const u8, //message this field help: []const u8, //help this field text: []const u8, zwitch: bool, // CTRUE CFALSE procfunc: []const u8, //name proc proctask: []const u8, //name proc progcall: []const u8, //name call typecall: []const u8, //type call SH / APPTERM parmcall: bool, // parm call Yes/No actif:bool, }; pub const Efield = enum { name, posx, posy, reftyp, width, scal, text, requier, protect, edtcar, errmsg, help, procfunc, proctask, progcall, typecall, parmcall, regex }; // for developpeur pub var MouseDsp : bool = false ; // New Field String ---> arraylist panel-label // refence type // TEXT_FREE, // ALPHA, // ALPHA_UPPER, // ALPHA_NUMERIC, // ALPHA_NUMERIC_UPPER, // ALPHA_FULL, // PASSWORD, // YES_NO, fn initFieldString( vname: [] const u8, vposx: usize, vposy: usize, vreftyp: REFTYP, vwidth: usize, vtext: []const u8, vrequier: bool, verrmsg: []const u8, vhelp: []const u8, vregex: []const u8) FIELD { var xfield = FIELD { .name = vname, .posx = vposx, .posy = vposy, .reftyp = vreftyp, .width = vwidth, .scal = 0, .nbrcar = vwidth, .requier = vrequier, .protect = false, .pading = true, .edtcar ="", .regex = "", .errmsg = verrmsg, .help = vhelp, .text = vtext, .zwitch = false, .procfunc ="", .proctask ="", .progcall ="", .typecall ="", .parmcall = false, .attribut = AtrField, .atrProtect = AtrProtect, .atrCall = AtrCall, .actif = true }; if (vregex.len > 0 ) xfield.regex = std.fmt.allocPrint(allocatorForms, "{s}",.{vregex}) catch |err| { @panic(@errorName(err));}; return xfield; } // New Field String ---> arraylist panel-lfield // refence type // .TEXT_FREE pub fn newFieldTextFree( vname: [] const u8, vposx: usize, vposy: usize, vwidth: usize, vtext: []const u8, vrequier: bool, verrmsg: []const u8, vhelp: []const u8, vregex: []const u8) FIELD { return initFieldString( vname, vposx, vposy, REFTYP.TEXT_FREE, vwidth, vtext, vrequier, verrmsg, vhelp, vregex); } // New Field String ---> arraylist panel-lfield // letter numeric punct // refence type // .TEXT_FULL pub fn newFieldTextFull( vname: [] const u8, vposx: usize, vposy: usize, vwidth: usize, vtext: []const u8, vrequier: bool, verrmsg: []const u8, vhelp: []const u8, vregex: []const u8) FIELD { return initFieldString( vname, vposx, vposy, REFTYP.TEXT_FULL, vwidth, vtext, vrequier, verrmsg, vhelp, vregex); } // New Field String ---> arraylist panel-lfield // refence type // .ALPHA pub fn newFieldAlpha(vname: [] const u8, vposx: usize, vposy: usize, vwidth: usize, vtext: []const u8, vrequier: bool, verrmsg: []const u8, vhelp: []const u8, vregex: []const u8) FIELD { return initFieldString(vname, vposx, vposy, REFTYP.ALPHA, vwidth, vtext, vrequier, verrmsg, vhelp, vregex); } // New Field String ---> arraylist panel-lfield // refence type // .ALPHA_UPPER pub fn newFieldAlphaUpper(vname: [] const u8, vposx: usize, vposy: usize, vwidth: usize, vtext: []const u8, vrequier: bool, verrmsg: []const u8, vhelp: []const u8, vregex: []const u8) FIELD { return initFieldString(vname, vposx, vposy, REFTYP.ALPHA_UPPER, vwidth, vtext, vrequier, verrmsg, vhelp, vregex); } // New Field String ---> arraylist panel-lfield // refence type // .ALPHA_NUMERIC pub fn newFieldAlphaNumeric(vname: [] const u8, vposx: usize, vposy: usize, vwidth: usize, vtext: []const u8, vrequier: bool, verrmsg: []const u8, vhelp: []const u8, vregex: []const u8) FIELD { return initFieldString(vname, vposx, vposy, REFTYP.ALPHA_NUMERIC, vwidth, vtext, vrequier, verrmsg, vhelp, vregex); } // New Field String ---> arraylist panel-lfield // refence type // .ALPHA_NUMERIC pub fn newFieldAlphaNumericUpper(vname: [] const u8, vposx: usize, vposy: usize, vwidth: usize, vtext: []const u8, vrequier: bool, verrmsg: []const u8, vhelp: []const u8, vregex: []const u8) FIELD { return initFieldString(vname, vposx, vposy, REFTYP.ALPHA_NUMERIC_UPPER, vwidth, vtext, vrequier, verrmsg, vhelp, vregex); } // New Field String ---> arraylist panel-lfield // refence type // .PASSWORD pub fn newFieldPassword(vname: [] const u8, vposx: usize, vposy: usize, vwidth: usize, vtext: []const u8, vrequier: bool, verrmsg: []const u8, vhelp: []const u8, vregex: []const u8) FIELD { return initFieldString(vname, vposx, vposy, REFTYP.PASSWORD, vwidth, vtext, vrequier, verrmsg, vhelp, vregex); } // New Field String ---> arraylist panel-lfield // refence type // .YES_NO pub fn newFieldYesNo(vname: [] const u8, vposx: usize, vposy: usize, vtext: []const u8, vrequier: bool, verrmsg: []const u8, vhelp: []const u8) FIELD { var xfield = FIELD { .name = vname, .posx = vposx, .posy = vposy, .reftyp = REFTYP.YES_NO , .width = 1, .scal = 0, .nbrcar = 1, .requier = vrequier, .protect = false, .pading = false, .edtcar = "", .regex = "", .errmsg = verrmsg, .help = vhelp, .text = vtext, .zwitch = false, .procfunc ="", .proctask ="", .progcall ="", .typecall ="", .parmcall = false, .attribut = AtrField, .atrProtect = AtrProtect, .atrCall = AtrCall, .actif = true }; if (xfield.help.len == 0 ) xfield.help = "to validate Y or N " ; return xfield; } // New Field Switch ---> arraylist panel-field // refence type // SWITCH, pub fn newFieldSwitch(vname: [] const u8, vposx: usize, vposy: usize, vzwitch: bool, verrmsg: []const u8, vhelp: []const u8) FIELD { var xfield = FIELD { .name = vname, .posx = vposx, .posy = vposy, .reftyp = REFTYP.SWITCH , .width = 1, .scal = 0, .nbrcar = 1, .requier = false, .protect = false, .pading = false, .edtcar = "", .regex = "", .errmsg = verrmsg, .help = vhelp, .text = "", .zwitch = vzwitch, .procfunc ="", .proctask ="", .progcall ="", .typecall ="", .parmcall = false, .attribut = AtrField, .atrProtect = AtrProtect, .atrCall = AtrCall, .actif = true }; if (xfield.help.len == 0 ) xfield.help = "check ok= ✔ not= ◉ : Select espace bar " ; if (xfield.zwitch == true ) xfield.text = CTRUE else xfield.text = CFALSE; return xfield; } // New Field Date ---> arraylist panel-field // refence type // DATE_FR, // regex fixe standard // Control yyyy = 0001-9999 as well as the traditional MM 02 DAY 28 or 29 values // I do not take into account the offset before 1500 ... etc. pub fn newFieldDateFR(vname: [] const u8, vposx: usize, vposy: usize, vtext: []const u8, vrequier: bool, verrmsg: []const u8, vhelp: []const u8) FIELD { var xfield = FIELD { .name = vname, .posx = vposx, .posy = vposy, .reftyp = REFTYP.DATE_FR, .width = 10, .scal = 0, .nbrcar = 10, .requier = vrequier, .protect = false, .pading = false, .edtcar ="", .regex = "", .errmsg = verrmsg, .help = vhelp, .text = vtext, .zwitch = false, .procfunc ="", .proctask ="", .progcall ="", .typecall ="", .parmcall = false, .attribut = AtrField, .atrProtect = AtrProtect, .atrCall = AtrCall, .actif = true }; xfield.regex = std.fmt.allocPrint(allocatorForms,"{s}" ,.{"^(0[1-9]|[12][0-9]|3[01])[\\/](0[1-9]|1[012])[\\/][0-9]{4,4}$"}) catch |err| { @panic(@errorName(err));}; if (xfield.help.len == 0 ) xfield.help = "ex: date DD/MM/YYYY" ; return xfield; } // New Field Date ---> arraylist panel-field // refence type // DATE_US, // regex fixe standard // Control yyyy = 0001-9999 as well as the traditional MM 02 DAY 28 or 29 values // I do not take into account the offset before 1500 ... etc. pub fn newFieldDateUS(vname: [] const u8, vposx: usize, vposy: usize, vtext: []const u8, vrequier: bool, verrmsg: []const u8, vhelp: []const u8) FIELD { var xfield = FIELD { .name = vname, .posx = vposx, .posy = vposy, .reftyp = REFTYP.DATE_US, .width = 10, .scal = 0, .nbrcar = 10, .requier = vrequier, .protect = false, .pading = false, .edtcar ="", .regex = "", .errmsg = verrmsg, .help = vhelp, .text = vtext, .zwitch = false, .procfunc ="", .proctask ="", .progcall ="", .typecall ="", .parmcall = false, .attribut = AtrField, .atrProtect = AtrProtect, .atrCall = AtrCall, .actif = true }; xfield.regex = std.fmt.allocPrint(allocatorForms,"{s}" ,.{"^(0[1-9]|1[012])[\\/](0[1-9]|[12][0-9]|3[01])[\\/][0-9]{4,4}$" }) catch |err| { @panic(@errorName(err));}; if (xfield.help.len == 0 ) xfield.help = "ex: date MM/DD/YYYY"; return xfield; } // New Field Date ---> arraylist panel-field // refence type // DATE_ISO, // regex fixe standard // Control yyyy = 0001-9999 as well as the traditional MM 02 DAY 28 or 29 values // I do not take into account the offset before 1500 ... etc. pub fn newFieldDateISO(vname: [] const u8, vposx: usize, vposy: usize, vtext: []const u8, vrequier: bool, verrmsg: []const u8, vhelp: []const u8) FIELD { var xfield = FIELD { .name = vname, .posx = vposx, .posy = vposy, .reftyp = REFTYP.DATE_ISO, .width = 10, .scal = 0, .nbrcar = 10, .requier = vrequier, .protect = false, .pading = false, .edtcar ="", .regex = "", .errmsg = verrmsg, .help = vhelp, .text = vtext, .zwitch = false, .procfunc ="", .proctask ="", .progcall ="", .typecall ="", .parmcall = false, .attribut = AtrField, .atrProtect = AtrProtect, .atrCall = AtrCall, .actif = true }; xfield.regex = std.fmt.allocPrint(allocatorForms,"{s}" ,.{"^([0-9]{4,4})[-](0[1-9]|1[012])[-](0[1-9]|[12][0-9]|3[01])$"}) catch |err| { @panic(@errorName(err));}; if (xfield.help.len == 0 ) xfield.help = "ex: date YYYY-MM-DD" ; return xfield; } // New Field Mail ---> arraylist panel-field // refence type // MAIL_ISO, // regex fixe standard pub fn newFieldMail(vname: [] const u8, vposx: usize, vposy: usize, vwidth: usize, vtext: []const u8, vrequier: bool, verrmsg: []const u8, vhelp: []const u8) FIELD { var xfield = FIELD { .name = vname, .posx = vposx, .posy = vposy, .reftyp = REFTYP.MAIL_ISO, .width = vwidth, .scal = 0, .nbrcar = vwidth, .requier = vrequier, .protect = false, .pading = true, .edtcar ="", .regex ="", .errmsg = verrmsg, .help = vhelp, .text = vtext, .zwitch = false, .procfunc ="", .proctask ="", .progcall ="", .typecall ="", .parmcall = false, .attribut = AtrField, .atrProtect = AtrProtect, .atrCall = AtrCall, .actif = true }; // https://stackoverflow.com/questions/201323/how-can-i-validate-an-email-address-using-a-regular-expression xfield.regex = std.fmt.allocPrint(allocatorForms,"{s}" ,.{"^[a-zA-Z0-9_!#$%&'*+/=?`{|}~^.-]+@([a-zA-Z0-9.-])+$"}) catch |err| { @panic(@errorName(err));}; if (xfield.help.len == 0 ) xfield.help = "ex: [email protected]" ; return xfield; } // New Field telephone ---> arraylist panel-field // refence type // TELEPHONE, // regex fixe standard pub fn newFieldTelephone(vname: [] const u8, vposx: usize, vposy: usize, vwidth: usize, vtext: []const u8, vrequier: bool, verrmsg: []const u8, vhelp: []const u8, vregex: []const u8) FIELD { var xfield = FIELD { .name = vname, .posx = vposx, .posy = vposy, .reftyp = REFTYP.TELEPHONE, .width = vwidth, .scal = 0, .nbrcar = vwidth, .requier = vrequier, .protect = false, .pading = true, .edtcar ="", .regex = "", .errmsg = verrmsg, .help = vhelp, .text = vtext, .zwitch = false, .procfunc ="", .proctask ="", .progcall ="", .typecall ="", .parmcall = false, .attribut = AtrField, .atrProtect = AtrProtect, .atrCall = AtrCall, .actif = true }; if (vregex.len > 0 ) xfield.regex = std.fmt.allocPrint(allocatorForms, "^{s}",.{vregex}) catch |err| { @panic(@errorName(err));}; // regex standar if (vregex.len == 0 ) xfield.regex = std.fmt.allocPrint(allocatorForms,"{s}" ,.{"^[+]{1,1}[(]{0,1}[0-9]{1,3}[)]([0-9]{1,3}){1,1}([-. ]?[0-9]{2,3}){2,4}$"}) catch |err| { @panic(@errorName(err));}; if (xfield.help.len == 0 ) xfield.help = "ex fr : +(33)6.12.131.141" ; return xfield; } // New Field Digit ---> arraylist panel-lfield // refence type // .DIGIT unsigned pub fn newFieldUDigit(vname: [] const u8, vposx: usize, vposy: usize, vwidth: usize, vtext: []const u8, vrequier: bool, verrmsg: []const u8, vhelp: []const u8, vregex: []const u8) FIELD { var xfield = FIELD { .name = vname, .posx = vposx, .posy = vposy, .reftyp = REFTYP.UDIGIT, .width = vwidth, .scal = 0, .nbrcar = vwidth, .requier = vrequier, .protect = false, .pading = true, .edtcar ="", .regex = vregex, .errmsg = verrmsg, .help = vhelp, .text = vtext, .zwitch = false, .procfunc ="", .proctask ="", .progcall ="", .typecall ="", .parmcall = false, .attribut = AtrField, .atrProtect = AtrProtect, .atrCall = AtrCall, .actif = true }; if (vregex.len == 0 ) { xfield.regex = std.fmt.allocPrint(allocatorForms,"^[0-9]{{1,{d}}}$",.{xfield.width}) catch |err| { @panic(@errorName(err));}; } if (xfield.help.len == 0 ) xfield.help = "ex: 0..9" ; return xfield; } // New Field DIGIT ---> arraylist panel-lfield // refence type // .DIGIT SIGNED pub fn newFieldDigit(vname: [] const u8, vposx: usize, vposy: usize, vwidth: usize, vtext: []const u8, vrequier: bool, verrmsg: []const u8, vhelp: []const u8, vregex: []const u8) FIELD { var xfield = FIELD { .name = vname, .posx = vposx, .posy = vposy, .reftyp = REFTYP.DIGIT, .width = vwidth, .scal = 0, .nbrcar = 0, .requier = vrequier, .protect = false, .pading = true, .edtcar ="", .regex = vregex, .errmsg = verrmsg, .help = vhelp, .text = vtext, .zwitch = false, .procfunc ="", .proctask ="", .progcall ="", .typecall ="", .parmcall = false, .attribut = AtrField, .atrProtect = AtrProtect, .atrCall = AtrCall, .actif = true }; xfield.nbrcar = xfield.width + xfield.scal + 1 ; if (vregex.len == 0 ) { xfield.regex = std.fmt.allocPrint(allocatorForms,"^[+-][0-9]{{1,{d}}}$",.{xfield.width}) catch |err| { @panic(@errorName(err));}; } if (xfield.help.len == 0 ) xfield.help = "ex: +0..9" ; return xfield; } // New Field Decimal ---> arraylist panel-lfield // refence type // .DECIMAL UNSIGNED pub fn newFieldUDecimal(vname: [] const u8, vposx: usize, vposy: usize, vwidth: usize, vscal: usize, vtext: []const u8, vrequier: bool, verrmsg: []const u8, vhelp: []const u8, vregex: []const u8) FIELD { var xfield = FIELD { .name = vname, .posx = vposx, .posy = vposy, .reftyp = REFTYP.UDECIMAL, .width = vwidth, .scal = vscal, .nbrcar = 0, .requier = vrequier, .protect = false, .pading = true, .edtcar ="", .regex = vregex, .errmsg = verrmsg, .help = vhelp, .text = vtext, .zwitch = false, .procfunc ="", .proctask ="", .progcall ="", .typecall ="", .parmcall = false, .attribut = AtrField, .atrProtect = AtrProtect, .atrCall = AtrCall, .actif = true }; // caculate len = width add scal add . if (vscal == 0 ) xfield.nbrcar = xfield.width else xfield.nbrcar = xfield.width + xfield.scal + 1 ; if (vregex.len == 0 ) { if (vscal == 0 ) xfield.regex = std.fmt.allocPrint(allocatorForms, "^[0-9]{{1,{d}}}$",.{vwidth}) catch |err| { @panic(@errorName(err));} else xfield.regex = std.fmt.allocPrint(allocatorForms, "^[0-9]{{1,{d}}}[.][0-9]{{{d}}}$",.{vwidth,vscal,}) catch |err| { @panic(@errorName(err));}; } if (xfield.help.len == 0 ) xfield.help = "ex: 12301 or 123.01" ; return xfield; } // New Field Decimal ---> arraylist panel-lfield // refence type // .DECIMAL SIGNED pub fn newFieldDecimal(vname: [] const u8, vposx: usize, vposy: usize, vwidth: usize, vscal: usize, vtext: []const u8, vrequier: bool, verrmsg: []const u8, vhelp: []const u8, vregex: []const u8) FIELD { var xfield = FIELD { .name = vname, .posx = vposx, .posy = vposy, .reftyp = REFTYP.DECIMAL, .width = vwidth, .scal = vscal, .nbrcar = 0, .requier = vrequier, .protect = false, .pading = true, .edtcar ="", .regex = vregex, .errmsg = verrmsg, .help = vhelp, .text = vtext, .zwitch = false, .procfunc ="", .proctask ="", .progcall ="", .typecall ="", .parmcall = false, .attribut = AtrField, .atrProtect = AtrProtect, .atrCall = AtrCall, .actif = true }; // caculate len = width add scal add + . if (vscal == 0 ) xfield.nbrcar = xfield.width + 1 else xfield.nbrcar = xfield.width + xfield.scal + 2 ; if (vregex.len == 0 ) { if (vscal == 0 ) xfield.regex = std.fmt.allocPrint(allocatorForms, "^[+-][0-9]{{1,{d}}}$",.{vwidth}) catch |err| { @panic(@errorName(err));} else xfield.regex = std.fmt.allocPrint(allocatorForms, "^[+-][0-9]{{1,{d}}}[.][0-9]{{{d}}}$",.{vwidth,vscal}) catch |err| { @panic(@errorName(err));}; } if (xfield.help.len == 0 ) xfield.help = "ex: +12301 or +123.01" ; return xfield; } // New Field Switch ---> arraylist panel-field // refence type // FUNC, pub fn newFieldFunc(vname: [] const u8, vposx: usize, vposy: usize, vwidth: usize, vtext: []const u8, vrequier: bool, vprocfunc: [] const u8, verrmsg: []const u8, vhelp: []const u8) FIELD { var xfield = FIELD { .name = vname, .posx = vposx, .posy = vposy, .reftyp = REFTYP.FUNC, .width = vwidth, .scal = 0, .nbrcar = vwidth, .requier = vrequier, .protect = false, .pading = false, .edtcar = "", .regex = "", .errmsg = verrmsg, .help = vhelp, .text = vtext, .zwitch = false, .procfunc =vprocfunc, .proctask ="", .progcall ="", .typecall ="", .parmcall = false, .attribut = AtrField, .atrProtect = AtrProtect, .atrCall = AtrCall, .actif = true }; if (xfield.help.len == 0 ) xfield.help = " Select espace bar " ; return xfield; } //======================================================================== //======================================================================== pub fn getIndex(vpnl: *pnl.PANEL , name: [] const u8 ) ErrForms ! usize { for (vpnl.field.items, 0..) |f, idx | { if (std.mem.eql(u8, f.name, name)) return idx; } return ErrForms.fld_getIndex_Name_Field_Invalide; } pub fn getName(vpnl: *pnl.PANEL , n: usize) ErrForms ! [] const u8 { if ( n < vpnl.field.items.len) return vpnl.field.items[n].name; return ErrForms.fld_getName_Index_invalide ; } pub fn getPosx(vpnl: *pnl.PANEL , n: usize) ErrForms ! usize { if ( n < vpnl.field.items.len) return vpnl.field.items[n].posx; return ErrForms.fld_getPosx_Index_invalide ; } pub fn getPosy(vpnl: *pnl.PANEL , n: usize) ErrForms ! usize { if ( n < vpnl.field.items.len) return vpnl.field.items[n].posy; return ErrForms.fld_getPosy_Index_invalide ; } pub fn getRefType(vpnl: *pnl.PANEL , n: usize) ErrForms ! REFTYP { if ( n < vpnl.field.items.len) return vpnl.field.items[n].reftyp; return ErrForms.fld_getRefType_Index_invalide ; } pub fn getWidth(vpnl: *pnl.PANEL , n: usize) ErrForms ! usize { if ( n < vpnl.field.items.len) return vpnl.field.items[n].width; return ErrForms.fld_getWidth_Index_invalide ; } pub fn getScal(vpnl: *pnl.PANEL , n: usize) ErrForms ! usize { if ( n < vpnl.field.items.len) return vpnl.field.items[n].scal; return ErrForms.fld_getScal_Index_invalide ; } pub fn getNbrCar(vpnl: *pnl.PANEL , n: usize) ErrForms ! usize { if ( n < vpnl.field.items.len) return vpnl.field.items[n].nbrcar; return ErrForms.fld_getNbrCar_Index_invalide ; } pub fn getRequier(vpnl: *pnl.PANEL , n: usize) ErrForms ! bool { if ( n < vpnl.field.items.len) return vpnl.field.items[n].requier; return ErrForms.fld_getRequier_Index_invalide ; } pub fn getProtect(vpnl: *pnl.PANEL , n: usize) ErrForms ! bool { if ( n < vpnl.field.items.len) return vpnl.field.items[n].protect; return ErrForms.fld_getProtect_Index_invalide ; } pub fn getPading(vpnl: *pnl.PANEL , n: usize) ErrForms ! bool { if ( n < vpnl.field.items.len) return vpnl.field.items[n].pading; return ErrForms.fld_getPading_Index_invalide ; } pub fn getEdtcar(vpnl: *pnl.PANEL , n: usize) ErrForms ! [] const u8 { if ( n < vpnl.field.items.len) return vpnl.field.items[n].edtcar; return ErrForms.fld_getEdtcar_Index_invalide ; } pub fn getRegex(vpnl: *pnl.PANEL , n: usize) ErrForms ! [] const u8 { if ( n < vpnl.field.items.len) return vpnl.field.items[n].regex; return ErrForms.fld_getRegex_Index_invalide ; } pub fn getErrMsg(vpnl: *pnl.PANEL , n: usize) ErrForms ! [] const u8 { if ( n < vpnl.field.items.len) return vpnl.field.items[n].errmsg; return ErrForms.fld_getErrMsg_Index_invalide ; } pub fn getHelp(vpnl: *pnl.PANEL , n: usize) ErrForms ! [] const u8 { if ( n < vpnl.field.items.len) return vpnl.field.items[n].help; return ErrForms.fld_getHelp_Index_invalide ; } pub fn getText(vpnl: *pnl.PANEL , n: usize) ErrForms ! [] const u8 { if ( n < vpnl.field.items.len) return vpnl.field.items[n].text; return ErrForms.fld_getText_Index_invalide ; } pub fn getSwitch(vpnl: *pnl.PANEL , n: usize) ErrForms ! bool { if ( n < vpnl.field.items.len) return vpnl.field.items[n].zwitch; return ErrForms.fld_getSwitch_Index_invalide ; } pub fn getErr(vpnl: *pnl.PANEL , n: usize) ErrForms ! bool { if ( n < vpnl.field.items.len) return vpnl.field.items[n].err; return ErrForms.fld_getErr_Index_invalide ; } pub fn getFunc(vpnl: *pnl.PANEL , n: usize) ErrForms ! [] const u8 { if ( n < vpnl.field.items.len) return vpnl.field.items[n].procfunc; return ErrForms.fld_getFunc_Index_invalide ; } pub fn getTask(vpnl: *pnl.PANEL , n: usize) ErrForms ! [] const u8 { if ( n < vpnl.field.items.len) return vpnl.field.items[n].proctask; return ErrForms.fld_getTask_Index_invalide ; } pub fn getCall(vpnl: *pnl.PANEL , n: usize) ErrForms ! [] const u8 { if ( n < vpnl.field.items.len) return vpnl.field.items[n].progcall; return ErrForms.fld_getCall_Index_invalide ; } pub fn getTypeCall(vpnl: *pnl.PANEL , n: usize) ErrForms ! [] const u8 { if ( n < vpnl.field.items.len) return vpnl.field.items[n].typecall; return ErrForms.fld_getTypeCall_Index_invalide ; } pub fn getParmCall(vpnl: *pnl.PANEL , n: usize) ErrForms ! bool { if ( n < vpnl.field.items.len) return vpnl.field.items[n].parmcall; return ErrForms.fld_getParmCall_Index_invalide ; } pub fn getAttribut(vpnl: *pnl.PANEL , n: usize) ErrForms ! term.ZONATRB { if ( n < vpnl.field.items.len) return vpnl.field.items[n].atribut; return ErrForms.fld_getAttribut_Index_invalide ; } pub fn getAtrProtect(vpnl: *pnl.PANEL , n: usize) ErrForms ! term.ZONATRB { if ( n < vpnl.field.items.len) return vpnl.field.items[n].atrProtect; return ErrForms.fld_AtrProtect_Index_invalide ; } pub fn getActif(vpnl: *pnl.PANEL , n: usize) ErrForms ! bool { if ( n < vpnl.field.items.len) return vpnl.field.items[n].actif; return ErrForms.fld_getActif_Index_invalide ; } pub fn setText(vpnl: *pnl.PANEL , n: usize, val:[] const u8) ErrForms ! void { if ( n < vpnl.field.items.len) vpnl.field.items[n].text = val else return ErrForms.fld_setText_Index_invalide; } // Input Field pub fn setSwitch(vpnl: *pnl.PANEL , n: usize, val :bool) ErrForms ! void { if ( n < vpnl.field.items.len) { vpnl.field.items[n].zwitch = val; vpnl.field.items[n].text = utl.boolToCbool(val); } else return ErrForms.fld_setSwitch_Index_invalide; } pub fn setProtect(vpnl: *pnl.PANEL , n: usize, val :bool) ErrForms ! void { if ( n < vpnl.field.items.len) vpnl.field.items[n].protect = val else return ErrForms.fld_setProtect_Index_invalide; } pub fn setRequier(vpnl: *pnl.PANEL , n: usize, val :bool) ErrForms ! void { if ( n < vpnl.field.items.len) vpnl.field.items[n].protect = val else return ErrForms.fld_setRequier_Index_invalide; } pub fn setEdtcar(vpnl: *pnl.PANEL , n: usize, val:[] const u8) ErrForms ! void { if ( n < vpnl.field.items.len) vpnl.field.items[n].edtcar = val else return ErrForms.fld_setEdtcar_Index_invalide; } pub fn setRegex(vpnl: *pnl.PANEL , n: usize, val:[] const u8) ErrForms ! void { if ( n < vpnl.field.items.len) vpnl.field.items[n].reftyp = val else return ErrForms.fld_setRegex_Index_invalide; } pub fn setTask(vpnl: *pnl.PANEL , n: usize, val :[]const u8) ErrForms ! void { if ( n < vpnl.field.items.len) vpnl.field.items[n].proctask = val else return ErrForms.fld_setTask_Index_invalide; } pub fn setCall(vpnl: *pnl.PANEL , n: usize, val :[]const u8) ErrForms ! void { if ( n < vpnl.field.items.len) vpnl.field.items[n].progcall = val else return ErrForms.fld_setCall_Index_invalide; } pub fn setTypeCall(vpnl: *pnl.PANEL , n: usize, val :[]const u8) ErrForms ! void { if ( n < vpnl.field.items.len) vpnl.field.items[n].typecall = val else return ErrForms.fld_setTypeCall_Index_invalide ; } pub fn setParmCall(vpnl: *pnl.PANEL , n: usize, val :bool) ErrForms ! void { if ( n < vpnl.field.items.len) vpnl.field.items[n].parmcall = val else return ErrForms.fld_setParmCall_Index_invalide ; } pub fn setActif(vpnl: *pnl.PANEL , n: usize, val :bool) ErrForms ! void { if ( n < vpnl.field.items.len) vpnl.field.items[n].actif = val else return ErrForms.fld_setActif_Index_invalide; } pub fn dltRows(vpnl: *pnl.PANEL, n :usize ) ErrForms ! void { if ( n < vpnl.field.items.len) _= vpnl.field.orderedRemove(n) else return ErrForms.fld_dltRows_Index_invalide; } // clear value ALL FIELD pub fn clearAll(vpnl: *pnl.PANEL) void { var n : usize = 0; for (vpnl.field.items) |_ | { vpnl.field.items[n].text = ""; vpnl.field.items[n].zwitch = false; n += 1 ; } } pub fn clearField(vpnl: *pnl.PANEL , n: usize,) void { if ( n > vpnl.field.items.len) return; vpnl.field.items[n].text = ""; vpnl.field.items[n].zwitch = false; } // matrix cleaning from Field pub fn clsField(vpnl: *pnl.PANEL, vfld : FIELD ) void { // display matrice PANEL if (vpnl.actif == false ) return ; if (vfld.actif == false ) return ; const x :usize = vfld.posx - 1; const y :usize = vfld.posy - 1; var n :usize = 0; var npos :usize = (vpnl.cols * vfld.posx) + vfld.posy - 1 ; while (n < vfld.nbrcar) : (n += 1) { vpnl.buf.items[npos].ch = " "; vpnl.buf.items[npos].attribut = vpnl.attribut; vpnl.buf.items[npos].on = false; term.gotoXY(x + vpnl.posx , y + vpnl.posy - n ); term.writeStyled(vpnl.buf.items[npos].ch,vpnl.buf.items[npos].attribut); npos += 1; } } pub fn printField(vpnl: *pnl.PANEL, vfld : FIELD) void { if ( vpnl.actif == false ) return ; // assigne FIELD to matrice for display var n = (vpnl.cols * (vfld.posx - 1)) + vfld.posy - 1; var nn: usize = 0; while (nn < vfld.nbrcar) : (nn += 1 ) { if (vfld.actif == true) { vpnl.buf.items[n].ch = " " ; if (vfld.protect == true) vpnl.buf.items[n].attribut = vfld.atrProtect else { if (std.mem.eql(u8,vfld.progcall ,"")) vpnl.buf.items[n].attribut = vpnl.attribut else vpnl.buf.items[n].attribut = vfld.atrCall; } vpnl.buf.items[n].on = true; } else { vpnl.buf.items[n].ch = " "; vpnl.buf.items[n].attribut = vpnl.attribut; vpnl.buf.items[n].on = false; } n += 1; } // The err field takes precedence, followed by protection, followed by the base attribute n = (vpnl.cols * (vfld.posx - 1)) + vfld.posy - 1 ; var nfld = vfld.text; var nile = false ; if (nfld.len == 0 and !vfld.protect ) { nfld = "_"; nile = true; } if (vfld.reftyp == REFTYP.SWITCH) { if ( vfld.zwitch ) nfld = CTRUE else nfld= CFALSE; } var iter = utl.iteratStr.iterator(nfld); defer iter.deinit(); while (iter.next()) |ch| { if (vfld.actif == true ) { if (vfld.reftyp == REFTYP.PASSWORD) vpnl.buf.items[n].ch = "*" else vpnl.buf.items[n].ch = std.fmt.allocPrint(allocatorForms,"{s}",.{ch}) catch unreachable; vpnl.buf.items[n].on = true; if (vfld.protect) vpnl.buf.items[n].attribut = vfld.atrProtect else { if (nile)vpnl.buf.items[n].attribut = AtrNil else { if (std.mem.eql(u8,vfld.progcall ,"")) vpnl.buf.items[n].attribut = vpnl.attribut else vpnl.buf.items[n].attribut = vfld.atrCall; } } } n += 1; } } pub fn displayField(vpnl: *pnl.PANEL, vfld : FIELD ) void { // display matrice PANEL if (vpnl.actif == false ) return ; if (vfld.actif == false ) return ; const x :usize = vfld.posx - 1; const y :usize = vfld.posy - 1; var n :usize = 0; var npos :usize = (vpnl.cols * (vfld.posx - 1)) + vfld.posy - 1 ; while (n < vfld.nbrcar) : (n += 1) { term.gotoXY(x + vpnl.posx , y + vpnl.posy + n ); term.writeStyled(vpnl.buf.items[npos].ch,vpnl.buf.items[npos].attribut); npos += 1; } } //----------------------------------------------------== // Input buffer management modeled on 5250/3270 // inspiration ncurse // application hold principe and new langage //----------------------------------------------------== var e_FIELD : std.ArrayList([] const u8) = undefined; var e_switch: bool = false; fn nbrCarField() usize { var wl : usize =0; var iter = utl.iteratStr.iterator(utl.listToStr(e_FIELD)); defer iter.deinit(); while (iter.next()) |_| { wl += 1 ;} return wl; } fn delete(n : usize) void { _=e_FIELD.orderedRemove(n); e_FIELD.append(" ") catch |err| { @panic(@errorName(err));}; } fn insert(c: [] const u8 , n : usize) void { _=e_FIELD.orderedRemove(nbrCarField() - 1); const allocator = std.heap.page_allocator; var x_FIELD = std.ArrayList([] const u8).init(allocator); defer x_FIELD.deinit(); for ( e_FIELD.items) |ch | { x_FIELD.append(ch) catch |err| { @panic(@errorName(err));}; } e_FIELD.clearRetainingCapacity(); for ( x_FIELD.items ,0..) |ch , idx | { if ( n != idx) e_FIELD.append(ch) catch |err| { @panic(@errorName(err));}; if ( n == idx) { e_FIELD.append(c) catch |err| { @panic(@errorName(err));}; e_FIELD.append(ch) catch |err| { @panic(@errorName(err));}; } } } fn isrequier() bool { var text = utl.listToStr(e_FIELD); text = utl.trimStr(text); if (text.len == 0 ) return true ; return false ; } /// Check if it is a space fn isSpace(c: [] const u8) bool { if ( std.mem.eql(u8, c, " ") ) return true; return false ; } /// if it is a KEY function fn isfuncKey(vpnl: *pnl.PANEL, e_key: term.Keyboard) bool { for ( vpnl.button.items) |xbtn| { if (xbtn.key == e_key.Key ) return true; } return false; } /// if it is a KEY function Check fn ischeckKey(vpnl: *pnl.PANEL, e_key: term.Keyboard) bool { for ( vpnl.button.items) |xbtn| { if (xbtn.key == e_key.Key and xbtn.check ) return true; } return false; } /// Hides the area entered with * fn password(s: std.ArrayList([] const u8)) [] const u8 { var i: usize = 0; var buf : [] const u8 = ""; while ( i < s.items.len ) : (i += 1) { if ( std.mem.eql(u8,s.items[i]," " )) buf = utl.concatStr(buf," ") else buf = utl.concatStr(buf,"*"); } return buf; } /// initialize the input field e_FIELD /// switch convert bool CTRUE /CFALSE /// the buffer displays field the text and completes with blanks fn initData(f:FIELD) void { e_FIELD.clearRetainingCapacity(); if ( f.reftyp == REFTYP.SWITCH) { if (e_switch == true ) utl.addListStr(&e_FIELD , CTRUE) else utl.addListStr(&e_FIELD , CFALSE); } else { utl.addListStr(&e_FIELD , f.text); var i:usize = 0 ; while (i < (f.nbrcar - utl.nbrCharStr(f.text))) : ( i += 1) { e_FIELD.append(" ") catch |err| { @panic(@errorName(err));}; } } } fn msgHelp(vpnl: *pnl.PANEL, f : FIELD ) void { // define attribut default MSG Error const MsgHelp : term.ZONATRB = .{ .styled=[_]u32{@intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle)}, .backgr = term.BackgroundColor.bgBlack, .foregr = term.ForegroundColor.fgRed }; const x: usize = vpnl.lines; var n: usize = vpnl.cols * (x - 2) ; var y: usize = 1 ; var msghlp:[]const u8 = utl.concatStr("Help : ", f.help) ; var boucle : bool= true ; if (vpnl.cols < (msghlp.len) ) msghlp = subStrForms( msghlp,0, vpnl.cols - 2); // clear line button while (y <= (vpnl.cols - 2) ) : (y += 1) { term.gotoXY(vpnl.posx + x - 2 , y + vpnl.posy ); term.writeStyled(" ",vpnl.attribut); } // display msgerr y = 1 ; term.gotoXY(vpnl.posx + x - 2, y + vpnl.posy ); term.writeStyled(msghlp,MsgHelp); while (boucle) { const e_key = kbd.getKEY(); switch ( e_key.Key ) { .esc=>boucle = false, else => {}, } } // restore line panel y = 1 ; while (y <= (vpnl.cols - 2)) : (y += 1) { n += 1; term.gotoXY( vpnl.posx + x - 2, y + vpnl.posy); term.writeStyled(vpnl.buf.items[n].ch,vpnl.buf.items[n].attribut); } } ///------------------------------------------------ /// Definition of the panel (window) on a lines /// Message display /// to exit press the Escape key /// restoration of the original panel lines ///------------------------------------------------ pub fn msgErr(vpnl: *pnl.PANEL, f : FIELD, info: [] const u8 ) void { term.gotoXY(vpnl.posx + f.posx - 1 , vpnl.posy + f.posy - 1); term.writeStyled(utl.listToStr(e_FIELD),MsgErr); const x: usize = vpnl.lines; var n: usize = vpnl.cols * (x - 2) ; var y: usize = 1 ; var msgerr:[]const u8 = utl.concatStr("Info : ", info) ; var boucle : bool= true ; if (vpnl.cols < (msgerr.len) ) msgerr = subStrForms( msgerr, 0, vpnl.cols - 2); // clear line button while (y <= (vpnl.cols - 2) ) : (y += 1) { term.gotoXY(vpnl.posx + x - 2 , y + vpnl.posy ); term.writeStyled(" ",vpnl.attribut); } // display msgerr y = 1 ; term.gotoXY(vpnl.posx + x - 2, y + vpnl.posy ); term.writeStyled(msgerr,MsgErr); while (boucle) { const e_key = kbd.getKEY(); switch ( e_key.Key ) { .esc=>boucle = false, else => {}, } } // restore line panel while (y <= (vpnl.cols - 2)) : (y += 1) { n += 1; term.gotoXY( vpnl.posx + x - 2, y + vpnl.posy ); term.writeStyled(vpnl.buf.items[n].ch,vpnl.buf.items[n].attribut); } } //==================================================== // ioFIELD //==================================================== pub fn ioField(vpnl: *pnl.PANEL, vfld : FIELD ) kbd { if (vfld.protect or !vfld.actif) return kbd.none; const e_posx :usize = vpnl.posx + vfld.posx - 1; const e_posy :usize = vpnl.posy + vfld.posy - 1; var e_curs :usize = e_posy ; var e_count :usize = 0; const e_nbrcar:usize = vfld.nbrcar; var statusCursInsert : bool = false ; var nfield :usize = 0 ; const allocator = std.heap.page_allocator; e_FIELD = std.ArrayList([] const u8).init(allocator); e_FIELD.clearAndFree(); defer e_FIELD.deinit(); e_switch = vfld.zwitch; const e_reftyp = vfld.reftyp; var tampon: [] const u8 = undefined; if ( e_posx == 0) return kbd.enter; vpnl.keyField = kbd.none; // prepare the switch edition initData(vfld); var Fkey : term.Keyboard = undefined ; var boucle : bool= true ; term.defCursor(term.typeCursor.cBlink); term.onMouse(); //=========================== // boucle saisie //=========================== while( boucle == true) { term.gotoXY(e_posx ,e_posy); switch(e_reftyp) { .PASSWORD => term.writeStyled(password(e_FIELD),AtrIO) , .SWITCH => if (e_switch) term.writeStyled(CTRUE,AtrIO) else term.writeStyled(CFALSE,AtrIO), else => term.writeStyled(utl.listToStr(e_FIELD),AtrIO) } term.gotoXY(e_posx,e_curs); if (statusCursInsert) term.defCursor(term.typeCursor.cSteadyBar) else term.defCursor(term.typeCursor.cBlink); // CHANGE CURSOR FORM BAR/BLOCK switch(e_reftyp) { .PASSWORD => { if ( std.mem.eql(u8,e_FIELD.items[e_count] , " ") ) term.writeStyled(" ", AtrCursor) else term.writeStyled("*", AtrCursor); }, else =>term.writeStyled(e_FIELD.items[e_count], AtrCursor), } term.gotoXY(e_posx,e_curs); term.cursShow(); Fkey = kbd.getKEY(); term.resetStyle(); if (isfuncKey(vpnl,Fkey)) boucle = false else { if (Fkey.Key == kbd.mouse ) { Fkey.Key = kbd.none; if (term.MouseInfo.scroll ) { switch (term.MouseInfo.scrollDir) { term.ScrollDirection.msUp => Fkey.Key = kbd.up, term.ScrollDirection.msDown => Fkey.Key = kbd.down, else => {} } } else { if (term.MouseInfo.action == term.MouseAction.maReleased ) continue; if (MouseDsp) dspMouse(vpnl); // active display Cursor x/y mouse switch (term.MouseInfo.button) { term.MouseButton.mbLeft => Fkey.Key = kbd.left, term.MouseButton.mbMiddle => Fkey.Key = kbd.enter, term.MouseButton.mbRight => Fkey.Key = kbd.right, else => {} } } } switch(Fkey.Key) { .none => { term.gotoXY(e_posx,e_curs); }, .esc => { initData(vfld) ; }, .ctrlH => { if ( vfld.help.len > 0 ) msgHelp(vpnl,vfld); }, .ctrlP => { // Call pgm if ( vfld.progcall.len > 0) { Fkey.Key = kbd.call; break; } }, .home => { e_count = 0; e_curs = e_posy; }, .end => { tampon = utl.listToStr(e_FIELD); if ( utl.trimStr(tampon).len > 0) { e_count = utl.trimStr(tampon).len - 1; e_curs = e_posy + utl.trimStr(tampon).len - 1; } else { e_count = 0 ; e_curs = e_posy; } }, .right , .tab => { if ( e_count < e_nbrcar - 1 and !isSpace(e_FIELD.items[0])) { e_count += 1; e_curs += 1; } }, .left , .stab=> { if( e_curs > e_posy) { e_count -= 1; e_curs -= 1; } }, .backspace => { if( e_reftyp != REFTYP.SWITCH) { delete(e_count); tampon = utl.listToStr(e_FIELD); if( e_count > 0 ) { e_count = utl.trimStr(tampon).len - 1 ; e_curs = e_posy + e_count; } else {e_count = 0; e_curs = e_posy ;} } }, .delete=> { if( e_reftyp != REFTYP.SWITCH) { if( e_count >= 0) { if (e_reftyp == REFTYP.DIGIT and e_count >= 0 or e_reftyp == REFTYP.DECIMAL and e_count >= 0 ) { delete(e_count); } else if (e_reftyp != REFTYP.DIGIT and e_reftyp != REFTYP.DECIMAL) { delete(e_count); } } } }, .ins=> { if( statusCursInsert ) statusCursInsert = false else statusCursInsert = true; }, .enter , .up , .down => { // enrg to Field //check requier and field.len > 0 if (vfld.requier and utl.trimStr(utl.listToStr(e_FIELD)).len == 0 ) { msgErr(vpnl,vfld,vfld.errmsg); e_curs = e_posy; e_count = 0; continue; } //check field.len > 0 and regexLen > 0 execute regex if ( vfld.regex.len > 0 and utl.trimStr(utl.listToStr(e_FIELD)).len > 0) { if ( ! reg.isMatch(utl.trimStr(utl.listToStr(e_FIELD)) ,vfld.regex) ) { msgErr(vpnl,vfld,vfld.errmsg); e_curs = e_posy; e_count = 0 ; continue; } } //write value keyboard to field.text return key nfield = getIndex(vpnl,vfld.name) catch |err| { @panic(@errorName(err));}; if (vfld.reftyp == REFTYP.SWITCH) setSwitch(vpnl, nfield, e_switch ) catch |err| { @panic(@errorName(err));} else { setText(vpnl, nfield, ToStr(utl.trimStr(utl.listToStr(e_FIELD)))) catch |err| { @panic(@errorName(err));}; } vpnl.keyField = Fkey.Key; // control is task if ( vfld.proctask.len > 0) { Fkey.Key = kbd.task; break; } break; }, .char=> { if (utl.isCarOmit(Fkey.Char) == false ) switch(e_reftyp) { .TEXT_FREE=> { if ( (e_count < e_nbrcar and isSpace(Fkey.Char) == false ) or (isSpace(Fkey.Char) == true and e_count > 0 and e_count < e_nbrcar) ) { if (statusCursInsert and e_count < e_nbrcar - 1) insert(Fkey.Char,e_count) else e_FIELD.items[e_count] = Fkey.Char; e_count += 1; e_curs += 1; if (e_count == e_nbrcar) { e_count -= 1; e_curs -= 1; } } }, .TEXT_FULL=> { if ( (e_count < e_nbrcar and isSpace(Fkey.Char) == false ) or (utl.isLetterStr(Fkey.Char) or utl.isDigitStr(Fkey.Char) or utl.isSpecialStr(Fkey.Char)) or (isSpace(Fkey.Char) == true and e_count > 0 and e_count < e_nbrcar) ) { if (statusCursInsert and e_count < e_nbrcar - 1) insert(Fkey.Char,e_count) else e_FIELD.items[e_count] = Fkey.Char; e_count += 1; e_curs += 1; if (e_count == e_nbrcar) { e_count -= 1; e_curs -= 1; } } }, .ALPHA, .ALPHA_UPPER => { if ( (e_count < e_nbrcar and isSpace(Fkey.Char) == false ) and (utl.isLetterStr(Fkey.Char) or std.mem.eql(u8, Fkey.Char, "-")) or (isSpace(Fkey.Char) == true and e_count > 0 and e_count < e_nbrcar) ) { if (vfld.reftyp == .ALPHA_UPPER) Fkey.Char = utl.upperStr(Fkey.Char); if (statusCursInsert and e_count < e_nbrcar - 1) insert(Fkey.Char,e_count) else e_FIELD.items[e_count] = Fkey.Char; e_count += 1; e_curs += 1; if (e_count == e_nbrcar) { e_count -= 1; e_curs -= 1; } } }, .ALPHA_NUMERIC, .ALPHA_NUMERIC_UPPER => { if ( (e_count < e_nbrcar and isSpace(Fkey.Char) == false ) and (utl.isLetterStr(Fkey.Char) or utl.isDigitStr(Fkey.Char) or std.mem.eql(u8, Fkey.Char, "-")) or (isSpace(Fkey.Char) == true and e_count > 0 and e_count < e_nbrcar) ) { if (vfld.reftyp == .ALPHA_NUMERIC_UPPER) Fkey.Char = utl.upperStr(Fkey.Char); if (statusCursInsert and e_count < e_nbrcar - 1) insert(Fkey.Char,e_count) else e_FIELD.items[e_count] = Fkey.Char; e_count += 1; e_curs += 1; if (e_count == e_nbrcar) { e_count -= 1; e_curs -= 1; } } }, .PASSWORD => { if ( (e_count < e_nbrcar and isSpace(Fkey.Char) == false ) and (utl.isPassword(Fkey.Char) ) ) { if (statusCursInsert and e_count < e_nbrcar - 1) insert(Fkey.Char,e_count) else e_FIELD.items[e_count] = Fkey.Char; e_count += 1; e_curs += 1; if (e_count == e_nbrcar) { e_count -= 1; e_curs -= 1; } } }, .YES_NO => { if (std.mem.eql(u8, Fkey.Char, "Y") or std.mem.eql(u8, Fkey.Char, "y") or std.mem.eql(u8, Fkey.Char, "N") or std.mem.eql(u8, Fkey.Char, "n") ) { Fkey.Char = utl.upperStr(Fkey.Char); if (statusCursInsert and e_count < e_nbrcar - 1) insert(Fkey.Char,e_count) else e_FIELD.items[e_count] = Fkey.Char; } }, .UDIGIT => { if (e_count < e_nbrcar and utl.isDigitStr(Fkey.Char) and ! std.mem.eql(u8, Fkey.Char, "-") and ! std.mem.eql(u8, Fkey.Char, "+") ) { if (statusCursInsert and e_count < e_nbrcar - 1) insert(Fkey.Char,e_count) else e_FIELD.items[e_count] = Fkey.Char; e_count += 1; e_curs += 1; if (e_count == e_nbrcar) { e_count -= 1; e_curs -= 1; } } }, .DIGIT => { if (e_count < e_nbrcar and utl.isDigitStr(Fkey.Char) and e_count > 0 or (std.mem.eql(u8, Fkey.Char, "-") and e_count == 0) or (std.mem.eql(u8, Fkey.Char, "+") and e_count == 0)) { if (statusCursInsert and e_count < e_nbrcar - 1) insert(Fkey.Char,e_count) else e_FIELD.items[e_count] = Fkey.Char; e_count += 1; e_curs += 1; if (e_count == e_nbrcar) { e_count -= 1; e_curs -= 1; } } }, .UDECIMAL => { if (e_count < e_nbrcar and utl.isDigitStr(Fkey.Char) or (std.mem.eql(u8, Fkey.Char, ".") and e_count > 1) or !std.mem.eql(u8, Fkey.Char, "-") and ! std.mem.eql(u8, Fkey.Char, "+") ) { if (vfld.scal == 0 and std.mem.eql(u8, Fkey.Char, ".") ) continue ; if (statusCursInsert and e_count < e_nbrcar - 1) insert(Fkey.Char,e_count) else e_FIELD.items[e_count] = Fkey.Char; e_count += 1; e_curs += 1; if (e_count == e_nbrcar) { e_count -= 1; e_curs -= 1; } } }, .DECIMAL => { if (e_count < e_nbrcar and utl.isDigitStr(Fkey.Char) and e_count > 0 or (std.mem.eql(u8, Fkey.Char, ".") and e_count > 1) or (std.mem.eql(u8, Fkey.Char, "-") and e_count == 0) or (std.mem.eql(u8, Fkey.Char, "+") and e_count == 0)) { if (vfld.scal == 0 and std.mem.eql(u8, Fkey.Char, ".") ) continue; if (statusCursInsert and e_count < e_nbrcar - 1) insert(Fkey.Char,e_count) else e_FIELD.items[e_count] = Fkey.Char; e_count += 1; e_curs += 1; if (e_count == e_nbrcar) { e_count -= 1; e_curs -= 1; } } }, .DATE_ISO => { if (e_count < e_nbrcar) { if (( utl.isDigitStr(Fkey.Char) and e_count <= 3) or ( utl.isDigitStr(Fkey.Char) and e_count == 5 ) or ( utl.isDigitStr(Fkey.Char) and e_count == 6 ) or ( utl.isDigitStr(Fkey.Char) and e_count == 8 ) or ( utl.isDigitStr(Fkey.Char) and e_count == 9 ) or (std.mem.eql(u8, Fkey.Char, "-") and e_count == 4) or (std.mem.eql(u8, Fkey.Char, "-") and e_count == 7) ) { if (statusCursInsert and e_count < e_nbrcar - 1) insert(Fkey.Char,e_count) else e_FIELD.items[e_count] = Fkey.Char; e_count += 1; e_curs += 1; if (e_count == e_nbrcar) { e_count -= 1; e_curs -= 1; } } } }, .DATE_FR , .DATE_US => { if (e_count < e_nbrcar ) { if (( utl.isDigitStr(Fkey.Char) and e_count <= 1) or ( utl.isDigitStr(Fkey.Char) and e_count == 3 ) or ( utl.isDigitStr(Fkey.Char) and e_count == 4 ) or ( utl.isDigitStr(Fkey.Char) and e_count >= 6 ) or (std.mem.eql(u8, Fkey.Char, "/") and e_count == 2) or (std.mem.eql(u8, Fkey.Char, "/") and e_count == 5) ) { if (statusCursInsert and e_count < e_nbrcar - 1) insert(Fkey.Char,e_count) else e_FIELD.items[e_count] = Fkey.Char; e_count += 1; e_curs += 1; if (e_count == e_nbrcar) { e_count -= 1; e_curs -= 1; } } } }, .TELEPHONE=> { if ((e_count < e_nbrcar ) and (utl.isDigitStr(Fkey.Char) or std.mem.eql(u8, Fkey.Char, "(") or std.mem.eql(u8, Fkey.Char, ")") or std.mem.eql(u8, Fkey.Char, " ") or std.mem.eql(u8, Fkey.Char, "+") or std.mem.eql(u8, Fkey.Char, "-") or std.mem.eql(u8, Fkey.Char, ".") ) ){ if (statusCursInsert) insert(Fkey.Char,e_count) else e_FIELD.items[e_count] = Fkey.Char; e_count += 1; e_curs += 1; if (e_count == e_nbrcar) { e_count -= 1; e_curs -= 1; } } }, .MAIL_ISO => { if (e_count < e_nbrcar and isSpace(Fkey.Char) == false and utl.isMailStr(Fkey.Char)) { if (statusCursInsert and e_count < e_nbrcar - 1) insert(Fkey.Char,e_count) else e_FIELD.items[e_count] = Fkey.Char; e_count += 1; e_curs += 1; if (e_count == e_nbrcar) { e_count -= 1; e_curs -= 1; } } }, .SWITCH => { if (isSpace(Fkey.Char)) { if (e_switch == false) { e_FIELD.items[e_count] = CTRUE; e_switch = true; } else { e_FIELD.items[e_count] = CFALSE; e_switch = false; } } }, .FUNC => { Fkey.Key =kbd.func; break; } }; }, else => {}, } } } return Fkey.Key; } }; // defined Panel pub const pnl = struct { // define attribut default PANELallocatorForms pub var AtrPanel : term.ZONATRB = .{ .styled=[_]u32{@intFromEnum(term.Style.styleDim), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle)}, .backgr = term.BackgroundColor.bgBlack, .foregr = term.ForegroundColor.fgWhite }; pub var MsgErr : term.ZONATRB = .{ .styled=[_]u32{@intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle)}, .backgr = term.BackgroundColor.bgBlack, .foregr = term.ForegroundColor.fgRed }; /// define PANEL pub const PANEL = struct { name: [] const u8, posx: usize, posy: usize, lines: usize, cols: usize, attribut: term.ZONATRB, frame: frm.FRAME , label: std.ArrayList(lbl.LABEL), button: std.ArrayList(btn.BUTTON), field: std.ArrayList(fld.FIELD), linev: std.ArrayList(lnv.LINEV), lineh: std.ArrayList(lnh.LINEH), // double buffer screen buf:std.ArrayList(TERMINAL_CHAR), idxfld: usize, key : kbd , // Func task call keyField : kbd , // enter up down actif: bool }; pub const Epanel = enum { name, posx, posy, lines, cols, cadre, title, button, label, field, linev, lineh, }; // Init Panel for arrayList exemple Gencurs modlPanel pub fn initPanel(vname: [] const u8, vposx: usize, vposy: usize, vlines: usize, vcols: usize, vcadre : CADRE, vtitle: [] const u8 ) PANEL { var xpanel = PANEL { .name = vname, .posx = vposx, .posy = vposy, .lines = vlines, .cols = vcols, .attribut = AtrPanel, .frame = undefined, .label = std.ArrayList(lbl.LABEL).init(allocatorForms), .button = std.ArrayList(btn.BUTTON).init(allocatorForms), .field = std.ArrayList(fld.FIELD).init(allocatorForms), .linev = std.ArrayList(lnv.LINEV).init(allocatorForms), .lineh = std.ArrayList(lnh.LINEH).init(allocatorForms), .buf = std.ArrayList(TERMINAL_CHAR).init(allocatorForms), .idxfld = 9999, .key = kbd.none, .keyField = kbd.none, .actif = true, }; // INIT doublebuffer var i:usize = (xpanel.lines+1) * (xpanel.cols+1); const doublebuffer = TERMINAL_CHAR { .ch = " ", .attribut = xpanel.attribut, .on = false}; // init matrix while (true) { if (i == 0) break ; xpanel.buf.append(doublebuffer) catch |err| { @panic(@errorName(err));}; i -=1 ; } // init frame Panel xpanel.frame = frm.newFrame(xpanel.name, 1 , 1, // border panel xpanel.lines, xpanel.cols, vcadre, frm.AtrFrame, vtitle, frm.AtrTitle ); return xpanel; } // decl New Panel use programe style C commun allocator pub fn newPanelC(vname: [] const u8, vposx: usize, vposy: usize, vlines: usize, vcols: usize, vcadre : CADRE, vtitle: [] const u8 ) *PANEL { var device = allocatorForms.create(PANEL) catch |err| { @panic(@errorName(err)) ; }; device.name = vname; device.posx = vposx; device.posy = vposy; device.lines = vlines; device.cols = vcols; device.attribut = AtrPanel; device.frame = undefined; device.label = std.ArrayList(lbl.LABEL).init(allocatorForms); device.button = std.ArrayList(btn.BUTTON).init(allocatorForms); device.field = std.ArrayList(fld.FIELD).init(allocatorForms); device.linev = std.ArrayList(lnv.LINEV).init(allocatorForms); device.lineh = std.ArrayList(lnh.LINEH).init(allocatorForms); device.buf = std.ArrayList(TERMINAL_CHAR).init(allocatorForms); device.idxfld = 9999; device.key = kbd.none; device.keyField = kbd.none; device.actif = true; // INIT doublebuffer var i:usize = (device.lines+1) * (device.cols+1); const doublebuffer = TERMINAL_CHAR { .ch = " ", .attribut = device.attribut, .on = false}; // init matrix while (true) { if (i == 0) break ; device.buf.append(doublebuffer) catch |err| { @panic(@errorName(err));}; i -=1 ; } // init frame Panel device.frame = frm.newFrame(device.name, 1 , 1, // border panel device.lines, device.cols, vcadre, frm.AtrFrame, vtitle, frm.AtrTitle ); return device; } pub fn initMatrix(vpnl: *PANEL) void { vpnl.buf.deinit(); vpnl.buf = std.ArrayList(TERMINAL_CHAR).init(allocatorForms); // INIT doublebuffer var i:usize = (vpnl.lines+1) * (vpnl.cols+1); const doublebuffer = TERMINAL_CHAR { .ch = " ", .attribut = vpnl.attribut, .on = false}; // init matrix while (true) { if (i == 0) break ; vpnl.buf.append(doublebuffer) catch |err| { @panic(@errorName(err));}; i -=1 ; } } pub fn freePanel(vpnl: *PANEL) void { vpnl.label.clearAndFree(); vpnl.button.clearAndFree(); vpnl.field.clearAndFree(); vpnl.lineh.clearAndFree(); vpnl.linev.clearAndFree(); vpnl.buf.clearAndFree(); vpnl.label.deinit(); vpnl.button.deinit(); vpnl.field.deinit(); vpnl.lineh.deinit(); vpnl.linev.deinit(); vpnl.buf.deinit(); } pub fn getName(vpnl: *PANEL) [] const u8 { return vpnl.name; } pub fn getPosx(vpnl: *PANEL) usize { return vpnl.posx; } pub fn getPosy(vpnl: *PANEL) usize { return vpnl.posy; } pub fn getCols(vpnl: *PANEL) usize { return vpnl.cols; } pub fn getLines(vpnl: *PANEL) usize { return vpnl.lines; } pub fn getTitle(vpnl: *PANEL) [] const u8 { return vpnl.frame.title; } pub fn getIdxfld(vpnl: *PANEL) usize { return vpnl.idxfld; } pub fn getActif(vpnl: *PANEL) bool { return vpnl.actif; } pub fn setIdxfld(vpnl: *PANEL , n :usize) void { vpnl.idxfld = n ; } pub fn setActif(vpnl: *PANEL , b :bool) void { vpnl.items.actif = b ; } pub fn displayPanel(vpnl: *PANEL) void { // display matrice PANEL if (vpnl.actif == false ) return ; var x :usize = 1; var y :usize = 0; var n :usize = 0; while (x <= vpnl.lines) : (x += 1) { y = 1; while (y <= vpnl.cols) : (y += 1) { term.gotoXY(x + vpnl.posx - 1 , y + vpnl.posy - 1 ); term.writeStyled(vpnl.buf.items[n].ch,vpnl.buf.items[n].attribut); n += 1; } } } // clear matrix pub fn clsPanel( vpnl : *PANEL) void { var x :usize = 0; var y :usize = 0; var n :usize = 0; while (x < vpnl.lines) : (x += 1) { y = 1; while (y <= vpnl.cols) : (y += 1) { vpnl.buf.items[n].ch = " "; vpnl.buf.items[n].attribut = vpnl.attribut; vpnl.buf.items[n].on = false; n += 1; } } //displayPanel(vpnl); } // clear Panel pub fn clearPanel( vpnl : *PANEL) void { vpnl.idxfld =9999; vpnl.keyField =kbd.none; for (vpnl.field.items, 0..) |_, idx| { vpnl.field.items[idx].text =" "; vpnl.field.items[idx].zwitch =false; } } // restor -panel MATRIX to terminal pub fn rstPanel(comptime T: type , vsrc: *T , vdst : *PANEL) void { if (vdst.actif == false) return ; if (vsrc.posx + vsrc.lines > vdst.posx + vdst.lines ) return ; if (vsrc.posy + vsrc.cols > vdst.posy + vdst.cols ) return ; var x :usize = 0; var y :usize = 0; var n :usize = 0; var npos : usize = vsrc.posx - vdst.posx ; while (x <= vsrc.lines) : (x += 1) { n = (vdst.cols * npos) + vsrc.posy - vdst.posy ; y = 0; while (y <= vsrc.cols ) : (y += 1) { term.gotoXY(x + vsrc.posx , y + vsrc.posy ); term.writeStyled(vdst.buf.items[n].ch,vdst.buf.items[n].attribut); n += 1; } npos += 1; } } /// print PANEL pub fn printPanel (vpnl: *PANEL) void { if ( vpnl.actif == false ) return; // assigne PANEL and all OBJECT to matrix for display // cursor HIDE par défault term.cursHide(); // clear matrix clsPanel(vpnl); // FRAME (window panel) frm.printFrame(vpnl,vpnl.frame); // LABEL for (vpnl.label.items) |lblprt| { if (lblprt.actif) lbl.printLabel(vpnl, lblprt); } // FIELD for (vpnl.field.items) |fldprt| { if (fldprt.actif) fld.printField(vpnl, fldprt); } // BUTTON if (vpnl.button.items.len > 0) { btn.printButton(vpnl); } // LINE Vertical for (vpnl.linev.items) |lnvprt| { if (lnvprt.actif) lnv.printLine(vpnl, lnvprt); } // LINE Horizontal for (vpnl.lineh.items) |lnhprt| { if (lnhprt.actif) lnh.printLine(vpnl, lnhprt); } displayPanel(vpnl); } pub fn msgErr(vpnl: *PANEL, info: [] const u8) void { const x: usize = vpnl.lines; var n: usize = vpnl.cols * (x - 2) ; var y: usize = 1 ; var msgerr:[]const u8 = utl.concatStr("Info : ", info); if (vpnl.cols < (msgerr.len) ) msgerr = subStrForms( msgerr, 0, vpnl.cols - 2) ; while (y <= (vpnl.cols - 2) ) : (y += 1) { term.gotoXY(vpnl.posx + x - 2 , y + vpnl.posy ); term.writeStyled(" ",vpnl.attribut); } y = 1 ; term.gotoXY(vpnl.posx + x - 2 , y + vpnl.posy ); term.writeStyled(msgerr,MsgErr); while (true) { const e_key = kbd.getKEY(); switch ( e_key.Key ) { .esc => break, else => {}, } } while (y <= (vpnl.cols - 2)) : (y += 1) { n += 1; term.gotoXY(vpnl.posx + x - 2, y + vpnl.posy ); term.writeStyled(vpnl.buf.items[n].ch,vpnl.buf.items[n].attribut); } } /// Check if it is a KEY function fn isPanelKey(vpnl: *PANEL, e_key: kbd) bool { for ( vpnl.button.items) |xbtn| { if (xbtn.key == e_key ) return true; } return false; } /// if it is a KEY function Check fn isPanelCtrl( vpnl: *PANEL, e_key: kbd) bool { for ( vpnl.button.items) |xbtn| { if ( xbtn.check and xbtn.key == e_key ) return true; } return false; } ///search there available field fn isNextIO(vpnl: *PANEL, idx : usize ) usize { var i : usize = idx + 1; if (idx == vpnl.field.items.len) i = 0; while ( i < vpnl.field.items.len) : (i += 1) { if (vpnl.field.items[i].actif and !vpnl.field.items[i].protect ) break ; } if (i == vpnl.field.items.len) i = vpnl.field.items.len - 1; if (vpnl.field.items[i].actif and vpnl.field.items[i].protect ) i = isPriorIO(vpnl, i); return i; } ///search there available field fn isPriorIO(vpnl: *PANEL, idx : usize) usize { const x : i64 = @intCast(idx - 1) ; var i : usize = 0; if ( x > 0) i = @intCast(x); while ( i > 0 ) : (i -= 1) { if (vpnl.field.items[i].actif and !vpnl.field.items[i].protect ) break ; } if (vpnl.field.items[i].actif and vpnl.field.items[i].protect ) i = isNextIO(vpnl, i); return i; } pub fn isValide(vpnl: *PANEL) bool { if (vpnl.actif == false ) return false ; for (vpnl.field.items, 0..) |f, idx| { if ( !f.protect and f.actif) { //check requier and field.len > 0 if (f.requier and utl.trimStr(f.text).len == 0 ) { vpnl.idxfld = idx; return false; } //check requier and field.len > 0 and regexLen > 0 execute regex if ( f.regex.len > 0 and f.requier and utl.trimStr(f.text).len > 0) { if ( !reg.isMatch(utl.trimStr(f.text) ,f.regex)) { vpnl.idxfld = idx; return false; } } // function call proctask } } vpnl.idxfld = 0; return true; } ///------------------------------------------------------ /// Format management including zones /// idxfld == 9999 print panel else position field /// keyboard proction keys are returned to the calling procedure /// /// only the key CtrlH = Aide / Help for field /// only the key CtrlP = call to the program associated with the Field zone /// Reserved keys for FIELD management /// traditionally UP, DOWN, TAB, STAB, CtrlA, F1..F24, /// ENTER, HOME, END, RIGTH, LEFt, BACKSPACE, DELETE, INSERT /// FUNC Triggered by ioField function /// predefined and customizable REGEX control /// CALL execve Application Terminal and module ///------------------------------------------------------ pub fn ioPanel(vpnl: *PANEL) kbd { if (vpnl.actif == false ) return kbd.none; var nField :usize = 0; var fld_key : kbd = kbd.enter; const nbrFieldIO : usize = vpnl.field.items.len; var nbrField : usize = 0; // search field activ if (vpnl.field.items.len > 0 ) { for(0..vpnl.field.items.len) | x | { if (vpnl.field.items[x].actif and !vpnl.field.items[x].protect ) nbrField += 1; } } // first time if ( vpnl.idxfld == 9999) { printPanel(vpnl); nField = 0; // positioning on the first active Field zone if (nbrField > 0 ) { if (!vpnl.field.items[0].actif or vpnl.field.items[0].protect ) nField = isNextIO(vpnl, 0);} } else { switch(vpnl.key ) { .func => nField = vpnl.idxfld, .task => { nField = vpnl.idxfld; switch(vpnl.keyField) { .enter => { if ( nField + 1 > nbrFieldIO - 1 ) nField = 0 else nField= isNextIO(vpnl,nField); vpnl.idxfld = nField; }, .up => { if (nField == 0) nField = nbrFieldIO - 1 else nField= isPriorIO(vpnl,nField); vpnl.idxfld = nField; }, .down => { if (nField + 1 > nbrFieldIO - 1) nField = 0 else nField= isNextIO(vpnl,nField); vpnl.idxfld = nField; }, else => nField = vpnl.idxfld, } }, else => nField = vpnl.idxfld, } } vpnl.keyField = kbd.none; // Processing of the panel's Fields while (true) { if (nbrField == 0 or vpnl.field.items.len == 0 ) { const vKey= kbd.getKEY(); if (isPanelKey(vpnl,vKey.Key)) { vpnl.idxfld = 9999; return vKey.Key; } continue ; } else if ( !vpnl.field.items[nField ].protect and vpnl.field.items[nField ].actif) { fld.printField(vpnl,vpnl.field.items[nField ]); fld.displayField(vpnl,vpnl.field.items[nField ]); fld_key = fld.ioField(vpnl,vpnl.field.items[nField ]); fld.printField(vpnl,vpnl.field.items[nField ]); fld.displayField(vpnl,vpnl.field.items[nField ]); vpnl.key = kbd.none; // function call procfunc if (fld_key == kbd.func ) { vpnl.idxfld = nField; vpnl.key = kbd.func; return fld_key; } // function call proctask if (fld_key == kbd.task) { vpnl.idxfld = nField; vpnl.key = kbd.task; return fld_key; } // function call pgm if (fld_key == kbd.call) { vpnl.idxfld = nField; vpnl.key = kbd.call; return fld_key; } // control validity if (isPanelKey(vpnl,fld_key )) { if (!isPanelCtrl(vpnl,fld_key)){ vpnl.idxfld = nField ; return fld_key; } else { if (isValide(vpnl)) { return fld_key; } else { msgErr(vpnl,"Format invalide"); nField = vpnl.idxfld ; fld_key = kbd.none ; } } } } switch(fld_key) { .enter => { if ( nField + 1 > nbrFieldIO - 1 ) nField = 0 else nField= isNextIO(vpnl,nField); vpnl.idxfld = nField; }, .up => { if (nField == 0) nField = nbrFieldIO - 1 else nField= isPriorIO(vpnl,nField); vpnl.idxfld = nField; }, .down => { if (nField + 1 > nbrFieldIO - 1) nField = 0 else nField= isNextIO(vpnl,nField); vpnl.idxfld = nField; }, else => {} } } } };
0
repos/zig_demoJson/library
repos/zig_demoJson/library/curse/menu.zig
///---------------------- /// gestion de menu /// zig 0.12.0 dev ///---------------------- const std = @import("std"); const utf = @import("std").unicode; /// terminal Fonction const term = @import("cursed"); // keyboard const kbd = @import("cursed").kbd; // tools utility const utl = @import("utils"); const os = std.os; const io = std.io; ///------------------------------- /// MENU ///------------------------------- /// Errors that may occur when using String pub const ErrMenu = error{ mnu_getIndex_Name_Menu_Invalide, mnu_getName_Index_invalide, mnu_getPosx_Index_invalide, mnu_getPosy_Index_invalide, mnu_getText_Index_invalide, mnu_getActif_Index_invalide, mnu_dltRows_Index_invalide, }; // defined Menu pub const mnu = struct { pub const CADRE = enum { line0, line1, line2 }; pub const MNUVH = enum { vertical, horizontal }; // nbr espace intercaler pub var mnuspc: usize = 3; // define attribut default CADRE pub var AtrMnu: term.ZONATRB = .{ .styled = [_]u32{ @intFromEnum(term.Style.styleDim), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle) }, .backgr = term.BackgroundColor.bgBlack, .foregr = term.ForegroundColor.fgRed }; pub var AtrBar: term.ZONATRB = .{ .styled = [_]u32{ @intFromEnum(term.Style.styleReverse), @intFromEnum(term.Style.styleItalic), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle) }, .backgr = term.BackgroundColor.bgBlack, .foregr = term.ForegroundColor.fgWhite }; pub var AtrCell: term.ZONATRB = .{ .styled = [_]u32{ @intFromEnum(term.Style.styleItalic), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle), @intFromEnum(term.Style.notStyle) }, .backgr = term.BackgroundColor.bgBlack, .foregr = term.ForegroundColor.fgWhite, }; // define MENU pub const MENU = struct { name: []const u8, posx: usize, posy: usize, lines: usize, cols: usize, cadre: CADRE, mnuvh: MNUVH, attribut: term.ZONATRB, attrBar: term.ZONATRB, attrCell: term.ZONATRB, xitems: []const []const u8, nbr: usize, actif: bool }; // NEW MENU pub fn newMenu(vname: []const u8, vposx: usize, vposy: usize, vcadre: CADRE, vmnuvh: MNUVH, vitems: []const []const u8) MENU { var xmenu = MENU{ .name = vname, .posx = vposx, .posy = vposy, .lines = 0, .cols = 0, .cadre = vcadre, .mnuvh = vmnuvh, .attribut = AtrMnu, .attrBar = AtrBar, .attrCell = AtrCell, .xitems = vitems, .nbr = 0, .actif = true }; for (xmenu.xitems) |txt| { if (xmenu.cols < txt.len) xmenu.cols = txt.len; xmenu.nbr += 1; } xmenu.lines += xmenu.nbr + 2; //nbr ligne + header =cadre xmenu.cols += 2; return xmenu; } // return index-menu ---> arraylist panel-menu pub fn getIndex(vmnu: *mnu.MENU, name: []const u8) ErrMenu!usize { for (vmnu.items, 0..) |l, idx| { if (std.mem.eql(u8, l.name, name)) return idx; } return ErrMenu.mnu_getIndex_Name_Menu_Invalide; } // return name-menu ---> arraylist panel-menu pub fn getName(vmnu: *mnu.MENU, n: usize) ErrMenu![]const u8 { if (n < vmnu.items.len) return vmnu.items[n].name; return ErrMenu.mnu_getName_Index_invalide; } // return posx-menu ---> arraylist panel-menu pub fn getPosx(vmnu: *mnu.MENU, n: usize) ErrMenu!usize { if (n < vmnu.items.len) return vmnu.items[n].posx; return ErrMenu.mnu_getPosx_Index_invalide; } // return posy-menu ---> arraylist panel-menu pub fn getPosy(vmnu: *mnu.MENU, n: usize) ErrMenu!usize { if (n < vmnu.items.len) return vmnu.items[n].posy; return ErrMenu.mnu_getPosy_Index_invalide; } // return Text-menu ---> arraylist panel-menu pub fn getText(vmnu: *mnu.MENU, n: usize) ErrMenu!usize { if (n < vmnu.items.len) return vmnu.items[n].text; return ErrMenu.mnu_getText_Index_invalide; } // return ON/OFF-menu ---> arraylist panel-menu pub fn getActif(vmnu: *mnu.MENU, n: usize) ErrMenu!bool { if (n < vmnu.items.len) return vmnu.items[n].actif; return ErrMenu.mnu_getActif_Index_invalide; } // delete -menu ---> arraylist panel-menu pub fn dltRows(vmnu: *mnu.MENU, n: usize) ErrMenu!void { if (n < vmnu.items.len) _ = vmnu.orderedRemove(n) else return ErrMenu.mnu_dltRows_Index_invalide; } // assign -menu MATRIX TERMINAL ---> arraylist panel-menu fn printMenu(vmnu: MENU) void { if (vmnu.actif == false) return; const ACS_Hlines = "─"; const ACS_Vlines = "│"; const ACS_UCLEFT = "┌"; const ACS_UCRIGHT = "┐"; const ACS_LCLEFT = "└"; const ACS_LCRIGHT = "┘"; const ACS_Hline2 = "═"; const ACS_Vline2 = "║"; const ACS_UCLEFT2 = "╔"; const ACS_UCRIGHT2 = "╗"; const ACS_LCLEFT2 = "╚"; const ACS_LCRIGHT2 = "╝"; var trait: []const u8 = ""; var edt: bool = undefined; var row: usize = 1; var y: usize = 0; var col: usize = 0; var x: usize = vmnu.posx; // if line 0 ex: directory tab if (CADRE.line0 != vmnu.cadre) { while (row <= vmnu.lines) : (row += 1) { y = vmnu.posy; col = 1; while (col <= vmnu.cols) { edt = false; if (row == 1) { if (col == 1) { if (CADRE.line1 == vmnu.cadre) { trait = ACS_UCLEFT; } else trait = ACS_UCLEFT2; edt = true; } if (col == vmnu.cols) { if (CADRE.line1 == vmnu.cadre) { trait = ACS_UCRIGHT; } else trait = ACS_UCRIGHT2; edt = true; } if (col > 1 and col < vmnu.cols) { if (CADRE.line1 == vmnu.cadre) { trait = ACS_Hlines; } else trait = ACS_Hline2; edt = true; } } else if (row == vmnu.lines) { if (col == 1) { if (CADRE.line1 == vmnu.cadre) { trait = ACS_LCLEFT; } else trait = ACS_LCLEFT2; edt = true; } if (col == vmnu.cols) { if (CADRE.line1 == vmnu.cadre) { trait = ACS_LCRIGHT; } else trait = ACS_LCRIGHT2; edt = true; } if (col > 1 and col < vmnu.cols) { if (CADRE.line1 == vmnu.cadre) { trait = ACS_Hlines; } else trait = ACS_Hline2; edt = true; } } else if (row > 1 and row < vmnu.lines) { if (col == 1 or col == vmnu.cols) { if (CADRE.line1 == vmnu.cadre) { trait = ACS_Vlines; } else trait = ACS_Vline2; edt = true; } } if (edt) { term.gotoXY(row + vmnu.posx, col + vmnu.posy); term.writeStyled(trait, vmnu.attribut); } else { term.gotoXY(row + vmnu.posx, col + vmnu.posy); term.writeStyled(" ", vmnu.attribut); } y += 1; col += 1; } x += 1; } } } // display MATRIX to terminal ---> arraylist panel-menu fn displayMenu(vmnu: MENU, npos: usize) void { var pos: usize = npos; var n: usize = 0; var h: usize = 0; const x: usize = vmnu.posx + 1; const y: usize = vmnu.posy + 1; printMenu(vmnu); term.onMouse(); term.cursHide(); if (npos > vmnu.nbr or npos == 0) pos = 0; n = 0; h = 0; for (vmnu.xitems) |cell| { if (vmnu.mnuvh == MNUVH.vertical) { if (vmnu.cadre == CADRE.line0) term.gotoXY(x + n, y) else term.gotoXY(x + n + 1, y + 1); } if (vmnu.mnuvh == MNUVH.horizontal) { if (vmnu.cadre == CADRE.line0) term.gotoXY(x, h + y) else term.gotoXY(x + 1, h + y + 1); } //var xcell = utl.Trim(cell); if (pos == n) term.writeStyled(cell, vmnu.attrBar) else term.writeStyled(cell, vmnu.attrCell); n += 1; h += utl.nbrCharStr(cell); if (vmnu.mnuvh == MNUVH.horizontal) h += mnuspc; } } //---------------------------------------------------------------- // menu enter = select 1..n 0 = abort (Escape) // Turning on the mouse // UP DOWN LEFT RIGHT // movement width the wheel and validation width the clik //---------------------------------------------------------------- pub fn ioMenu(vmnu: MENU, npos: usize) usize { if (vmnu.actif == false) return 999; var pos: usize = npos; var n: usize = 0; var h: usize = 0; const x: usize = vmnu.posx + 1; const y: usize = vmnu.posy + 1; term.onMouse(); term.cursHide(); if (npos > vmnu.nbr or npos == 0) pos = 0; displayMenu(vmnu, pos); term.flushIO(); while (true) { n = 0; h = 0; for (vmnu.xitems) |cell| { if (vmnu.mnuvh == MNUVH.vertical) { if (vmnu.cadre == CADRE.line0) term.gotoXY(x + n, y) else term.gotoXY(x + n + 1, y + 1); } if (vmnu.mnuvh == MNUVH.horizontal) { if (vmnu.cadre == CADRE.line0) term.gotoXY(x, h + y) else term.gotoXY(x + 1, h + y + 1); } if (pos == n) term.writeStyled(cell, vmnu.attrBar) else term.writeStyled(cell, vmnu.attrCell); n += 1; h += utl.nbrCharStr(cell); if (vmnu.mnuvh == MNUVH.horizontal) h += mnuspc; } var Tkey = kbd.getKEY(); if (Tkey.Key == kbd.char and std.mem.eql(u8, Tkey.Char, " ")) { Tkey.Key = kbd.enter; Tkey.Char = ""; } if (Tkey.Key == kbd.mouse) { Tkey.Key = kbd.none; if (term.MouseInfo.scroll) { if (term.MouseInfo.scrollDir == term.ScrollDirection.msUp) { if (vmnu.mnuvh == MNUVH.vertical) Tkey.Key = kbd.up; if (vmnu.mnuvh == MNUVH.horizontal) Tkey.Key = kbd.left; } if (term.MouseInfo.scrollDir == term.ScrollDirection.msDown) { if (vmnu.mnuvh == MNUVH.vertical) Tkey.Key = kbd.down; if (vmnu.mnuvh == MNUVH.horizontal) Tkey.Key = kbd.right; } } else { if (term.MouseInfo.action == term.MouseAction.maReleased) continue; switch (term.MouseInfo.button) { term.MouseButton.mbLeft => Tkey.Key = kbd.enter, term.MouseButton.mbMiddle => Tkey.Key = kbd.enter, term.MouseButton.mbRight => Tkey.Key = kbd.enter, else => {}, } } } switch (Tkey.Key) { .none => continue, .esc => { term.offMouse(); return 9999; }, .enter => { term.offMouse(); return pos; }, .down => { if (pos < vmnu.nbr - 1) pos += 1; }, .up => { if (pos > 0) pos -= 1; }, .right => { if (pos < vmnu.nbr - 1) pos += 1; }, .left => { if (pos > 0) pos -= 1; }, else => {}, } } } };
0
repos/zig_demoJson/library
repos/zig_demoJson/library/curse/match.zig
///---------------------- /// match regex pcre2 /// zig 0.12.0 dev ///--------------------- const std = @import("std"); const re = @cImport({ @cDefine("PCRE2_CODE_UNIT_WIDTH", "8"); @cInclude("regPcre2.h"); }); // Linux PCRE2 // function macth regex.h standard libc // display patern only test // linux aligne i64 = usize pub fn isMatch(strVal : [] const u8, regVal : [] const u8 ) bool { const allocator = std.heap.page_allocator; const slice = allocator.alignedAlloc(u8, @sizeOf(usize),@sizeOf(usize)) catch unreachable; defer allocator.free(slice); const regex: *re.regex_t = @ptrCast(slice ); defer re.pcre2_regfree(regex); // IMPORTANT!! const creg: []u8 = allocator.alloc(u8, regVal.len , ) catch |err| { @panic(@errorName(err));}; defer allocator.free(creg); @memcpy(creg, regVal); if (re.pcre2_regcomp(regex,@ptrCast(creg),re.REG_EXTENDED) != 0) { // TODO: the pattern is invalid // display for test // std.debug.print("error patern {s}\n", .{regVal}); return false ; } const cval: []u8 = allocator.alloc(u8, strVal.len ) catch |err| { @panic(@errorName(err));}; defer allocator.free(cval); @memcpy(cval, strVal); const vBool = re.isMatch(regex, @ptrCast(cval)); return vBool; }
0
repos/zig_demoJson
repos/zig_demoJson/src-zig/buildmodlJson.zig
const std = @import("std"); pub fn build(b: *std.Build) void { // Standard release options allow the person running `zig build` to select // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); // zig-src source projet // zig-src/deps curs/ form / outils .... // src_c source c/c++ // zig-src/lib source .h // Building the executable const Prog = b.addExecutable(.{ .name = "modlJson", .root_source_file = b.path( "./modlJson.zig" ), .target = target, .optimize = optimize, }); // for match use regex //Prog.linkLibC(); // Resolve the 'library' dependency. const library_dep = b.dependency("library", .{}); // Import the smaller 'cursed' and 'utils' modules exported by the library. etc... Prog.root_module.addImport("cursed", library_dep.module("cursed")); Prog.root_module.addImport("utils", library_dep.module("utils")); Prog.root_module.addImport("match", library_dep.module("match")); Prog.root_module.addImport("forms", library_dep.module("forms")); Prog.root_module.addImport("logger", library_dep.module("logger")); b.installArtifact(Prog); }
0
repos/zig_demoJson
repos/zig_demoJson/src-zig/build.zig.zon
.{ .name = "program", .version = "0.0.0", .dependencies = .{ .library = .{ .path = "../library", }, }, .paths = .{ "", }, }
0
repos/zig_demoJson
repos/zig_demoJson/src-zig/modlJson.zig
const std = @import("std"); // keyboard const kbd = @import("cursed").kbd; // tools utility const utl = @import("utils"); const deb_Log = @import("logger").openFile; // open file const end_Log = @import("logger").closeFile; // close file const plog = @import("logger").scoped; // print file const allocator = std.heap.page_allocator; pub const CADRE = enum { line0, line1, line2 }; const Ctype = enum { null, bool, integer, float, number_string, string, array, object, decimal_string }; //..............................// const DEFBUTTON = struct { name: [] const u8, key : kbd, show: bool, check: bool, title: []const u8 }; const Jbutton = enum { name, key, show, check, title }; //..............................// const DEFLABEL = struct { name : []const u8, posx: usize, posy: usize, text: []const u8, title: bool }; const Jlabel = enum { name, posx, posy, text, title }; //..............................// const RPANEL = struct { name: [] const u8, posx: usize, posy: usize, lines: usize, cols: usize, cadre: CADRE, title: []const u8 , button: std.ArrayList(DEFBUTTON), label: std.ArrayList(DEFLABEL) }; const Jpanel = enum { name, posx, posy, lines, cols, cadre, title, button, label }; //var NPANEL = std.ArrayList(pnl.PANEL).init(allocator); var ENRG : RPANEL= undefined; //--------------------------------------------------------------------------- // string return enum fn strToEnum ( comptime EnumTag : type , vtext: [] const u8 ) EnumTag { inline for (@typeInfo(EnumTag).Enum.fields) |f| { if ( std.mem.eql(u8, f.name , vtext) ) return @field(EnumTag, f.name); } var buffer : [128] u8 = [_]u8{0} ** 128; const result = std.fmt.bufPrintZ(buffer[0..], "invalid Text {s} for strToEnum ",.{vtext}) catch unreachable; @panic(result); } //---------------------------------------------------- // JSON //---------------------------------------------------- const T = struct { x: ?std.json.Value, pub fn init(self: std.json.Value) T { return T { .x = self }; } pub fn get(self: T, query: []const u8) T { if (self.x.?.object.get(query) == null) { std.debug.print("ERROR::{s}::", .{ "invalid" }); return T.init(self.x.?); } return T.init(self.x.?.object.get(query).?); } pub fn ctrlPack(self: T , Xtype : Ctype) !bool { try printPack(self,Xtype); var out = std.ArrayList(u8).init(allocator); defer out.deinit(); switch (self.x.?) { .null => { if (Xtype != .null) return false; }, .bool => { if (Xtype != Ctype.bool ) return false; }, .integer => { if (Xtype != Ctype.integer) return false; }, .float =>{ if (Xtype != Ctype.float) return false; }, .number_string =>{ if (Xtype != Ctype.number_string) return false; }, .string =>{ if (Xtype != Ctype.string) return false; if (Xtype == Ctype.decimal_string) return utl.isDecimalStr(try std.fmt.allocPrint(allocator,"{s}",.{self.x.?.string})); }, .array =>{ if (Xtype != Ctype.array) return false; }, .object => { if (Xtype != Ctype.object) return false; //try printPack(self,Xtype); } } return true; } pub fn index(self: T, i: usize) T { switch (self.x.?) { .array => { if (i > self.x.?.array.items.len) { std.debug.print("ERROR::{s}::\n", .{ "index out of bounds" }); return T.init(self.x.?); } }, else => { std.debug.print("ERROR::{s}:: {s}\n", .{ "Not array", @tagName(self.x.?) }); return T.init(self.x.?); } } return T.init(self.x.?.array.items[i]); } pub fn printPack(self: T , Xtype : Ctype) !void { std.debug.print("{}:",.{Xtype}); var out = std.ArrayList(u8).init(allocator); defer out.deinit(); const i = self.x.?; const P = struct { value: ?std.json.Value }; try std.json.stringify(P{ .value = i }, .{ }, out.writer()); std.debug.print("{s}\n", .{ out.items }); } }; pub fn jsonDecode(my_json : []const u8) !void { var val: T = undefined; const parsed = try std.json.parseFromSlice(std.json.Value, allocator, my_json, .{ }); defer parsed.deinit(); std.debug.print("\n", .{ }); const json = T.init(parsed.value); _= try json.ctrlPack(Ctype.object); val = json.get("PANEL"); const nbrPanel = val.x.?.array.items.len; var p: usize = 0 ; const Rpanel = std.enums.EnumIndexer(Jpanel); const Rlabel = std.enums.EnumIndexer(Jlabel); const Rbutton = std.enums.EnumIndexer(Jbutton); while (p < nbrPanel) : ( p +=1 ) { var n: usize = 0 ; // index while (n < Rpanel.count) : ( n +=1 ) { var v: usize = 0 ; // index var y: usize = 0 ; // array len var z: usize = 0 ; // compteur var b: usize = 0 ; // button var l: usize = 0 ; // label switch(Rpanel.keyForIndex(n)) { Jpanel.name => { val = json.get("PANEL").index(p).get(@tagName(Rpanel.keyForIndex(n))); if ( try val.ctrlPack(Ctype.string) ) ENRG.name = try std.fmt.allocPrint(allocator,"{s}",.{val.x.?.string}) else @panic(try std.fmt.allocPrint(allocator,"Json Panel err_Field :{s}\n", .{ @tagName(Rpanel.keyForIndex(n))})); }, Jpanel.posx => { val = json.get("PANEL").index(p).get(@tagName(Rpanel.keyForIndex(n))); if ( try val.ctrlPack(Ctype.integer) ) ENRG.posx = @intCast(val.x.?.integer) else @panic(try std.fmt.allocPrint(allocator,"Json err_Field :{s}\n", .{ @tagName(Rpanel.keyForIndex(n))})); }, Jpanel.posy => { val = json.get("PANEL").index(p).get(@tagName(Rpanel.keyForIndex(n))); if ( try val.ctrlPack(Ctype.integer) ) ENRG.posy = @intCast(val.x.?.integer) else @panic(try std.fmt.allocPrint(allocator,"Json err_Field :{s}\n", .{ @tagName(Rpanel.keyForIndex(n))})); }, Jpanel.lines => { val = json.get("PANEL").index(p).get(@tagName(Rpanel.keyForIndex(n))); if ( try val.ctrlPack(Ctype.integer) ) ENRG.lines = @intCast(val.x.?.integer) else @panic(try std.fmt.allocPrint(allocator,"Json err_Field :{s}\n", .{ @tagName(Rpanel.keyForIndex(n))})); }, Jpanel.cols => { val = json.get("PANEL").index(p).get(@tagName(Rpanel.keyForIndex(n))); if ( try val.ctrlPack(Ctype.integer) ) ENRG.cols = @intCast(val.x.?.integer) else @panic(try std.fmt.allocPrint(allocator,"Json err_Field :{s}\n", .{ @tagName(Rpanel.keyForIndex(n))})); }, Jpanel.cadre => { val = json.get("PANEL").index(p).get(@tagName(Rpanel.keyForIndex(n))); if ( try val.ctrlPack(Ctype.string) ) { ENRG.cadre = strToEnum(CADRE, val.x.?.string); } else @panic(try std.fmt.allocPrint(allocator,"Json err_Field :{s}\n", .{ @tagName(Rpanel.keyForIndex(n))})); }, Jpanel.title => { val = json.get("PANEL").index(p).get(@tagName(Rpanel.keyForIndex(n))); if ( try val.ctrlPack(Ctype.string) ) ENRG.title = try std.fmt.allocPrint(allocator,"{s}",.{val.x.?.string}) else @panic(try std.fmt.allocPrint(allocator,"Json err_Field :{s}\n", .{ @tagName(Rpanel.keyForIndex(n))})); }, Jpanel.button => { val = json.get("PANEL").index(p).get(@tagName(Rpanel.keyForIndex(n))); var bt :DEFBUTTON =undefined; y = val.x.?.array.items.len; z = 0; b = 0; while(z < y) : (z += 1 ) { v =0; while (v < Rbutton.count) : ( v +=1 ) { val = json.get("PANEL").index(p).get("button").index(b).get(@tagName(Rbutton.keyForIndex(v))); switch(Rbutton.keyForIndex(v)) { Jbutton.name => { if ( try val.ctrlPack(Ctype.string)) bt.name = try std.fmt.allocPrint(allocator,"{s}",.{val.x.?.string}) else @panic(try std.fmt.allocPrint(allocator,"Json err_Field :{s}.{s}\n", .{ @tagName(Rpanel.keyForIndex(n)), @tagName(Rbutton.keyForIndex(v))})); }, Jbutton.key => { if ( try val.ctrlPack(Ctype.string)) { bt.key = strToEnum(kbd, val.x.?.string); } else @panic(try std.fmt.allocPrint(allocator,"Json err_Field :{s}.{s}\n", .{ @tagName(Rpanel.keyForIndex(n)), @tagName(Rbutton.keyForIndex(v))})); }, Jbutton.show => { if ( try val.ctrlPack(Ctype.bool)) bt.show = val.x.?.bool else @panic(try std.fmt.allocPrint(allocator,"Json err_Field :{s}.{s}\n", .{ @tagName(Rpanel.keyForIndex(n)), @tagName(Rbutton.keyForIndex(v))})); }, Jbutton.check=> { if ( try val.ctrlPack(Ctype.bool)) bt.check = val.x.?.bool else @panic(try std.fmt.allocPrint(allocator,"Json err_Field :{s}.{s}\n", .{ @tagName(Rpanel.keyForIndex(n)), @tagName(Rbutton.keyForIndex(v))})); }, Jbutton.title => { if ( try val.ctrlPack(Ctype.string)) bt.title = try std.fmt.allocPrint(allocator,"{s}",.{val.x.?.string}) else @panic(try std.fmt.allocPrint(allocator,"Json err_Field :{s}.{s}\n", .{ @tagName(Rpanel.keyForIndex(n)), @tagName(Rbutton.keyForIndex(v))})); ENRG.button.append(bt) catch unreachable; } } } b +=1; } }, Jpanel.label => { val = json.get("PANEL").index(p).get(@tagName(Rpanel.keyForIndex(n))); var lb :DEFLABEL =undefined; y = val.x.?.array.items.len; z = 0 ; l = 0 ; while(z < y) : (z += 1 ) { v =0; while (v < Rlabel.count) : ( v +=1 ) { val = json.get("PANEL").index(p).get("label").index(l).get(@tagName(Rlabel.keyForIndex(v))); try val.printPack(Ctype.array); switch(Rlabel.keyForIndex(v)) { Jlabel.name => { if ( try val.ctrlPack(Ctype.string)) lb.name = try std.fmt.allocPrint(allocator,"{s}",.{val.x.?.string}) else @panic(try std.fmt.allocPrint(allocator,"Json err_Field :{s}.{s}\n", .{ @tagName(Rpanel.keyForIndex(n)), @tagName(Rlabel.keyForIndex(v))})); }, Jlabel.posx => { if ( try val.ctrlPack(Ctype.integer)) { lb.posx = @intCast(val.x.?.integer); } else @panic(try std.fmt.allocPrint(allocator,"Json err_Field :{s}.{s}\n", .{ @tagName(Rpanel.keyForIndex(n)), @tagName(Rbutton.keyForIndex(v))})); }, Jlabel.posy => { if ( try val.ctrlPack(Ctype.integer)) { lb.posy = @intCast(val.x.?.integer); } else @panic(try std.fmt.allocPrint(allocator,"Json err_Field :{s}.{s}\n", .{ @tagName(Rpanel.keyForIndex(n)), @tagName(Rbutton.keyForIndex(v))})); }, Jlabel.text => { if ( try val.ctrlPack(Ctype.string)) lb.text = try std.fmt.allocPrint(allocator,"{s}",.{val.x.?.string}) else @panic(try std.fmt.allocPrint(allocator,"Json err_Field :{s}.{s}\n", .{ @tagName(Rpanel.keyForIndex(n)), @tagName(Rlabel.keyForIndex(v))})); }, Jlabel.title => { if ( try val.ctrlPack(Ctype.bool)) lb.title = val.x.?.bool else @panic(try std.fmt.allocPrint(allocator,"Json err_Field :{s}.{s}\n", .{ @tagName(Rpanel.keyForIndex(n)), @tagName(Rbutton.keyForIndex(v))})); ENRG.label.append(lb) catch unreachable; } } } l +=1; } } } } } } pub const ErrMain = error{ Invalide_size, }; // astuce dangereuse reserve internal function fn strToUsize_01(str: []const u8) usize{ return std.fmt.parseUnsigned(u64, str,10) catch { plog(.ERROR).err(" err{s}",.{str}); @panic("panic à bord");}; } pub fn main() !void { var out_buf: [1024]u8 = undefined; var slice_stream = std.io.fixedBufferStream(&out_buf); const out = slice_stream.writer(); var w = std.json.writeStream(out, .{ .whitespace = .indent_2 }); defer w.deinit(); try w.beginObject(); try w.objectField("PANEL"); try w.beginArray(); try w.beginObject(); try w.objectField("name"); try w.print(" \"{s}\"", .{"panel01"}); try w.objectField("posx"); try w.print(" {d}", .{1}); try w.objectField("posy"); try w.print(" {d}", .{2}); try w.objectField("lines"); try w.print(" {d}", .{3}); try w.objectField("cols"); try w.print(" {d}", .{4}); try w.objectField("cadre"); try w.print(" \"{s}\"", .{"line1"}); try w.objectField("title"); try w.print(" \"{s}\"", .{"Title-PANEL"}); try w.objectField("button"); try w.beginArray(); try w.beginObject(); try w.objectField("name"); try w.print(" \"{s}\"", .{"nF3"}); try w.objectField("key"); try w.print(" \"{s}\"", .{"F3"}); try w.objectField("show"); try w.print(" {}", .{true}); try w.objectField("check"); try w.print(" {}", .{false}); try w.objectField("title"); try w.print(" \"{s}\"", .{"F3 exit"}); try w.endObject(); try w.beginObject(); try w.objectField("name"); try w.print(" \"{s}\"", .{"nF9"}); try w.objectField("key"); try w.print(" \"{s}\"", .{"F9"}); try w.objectField("show"); try w.print(" {}", .{true}); try w.objectField("check"); try w.print(" {}", .{false}); try w.objectField("title"); try w.print(" \"{s}\"", .{"F9 Enrg."}); try w.endObject(); try w.endArray(); try w.objectField("label"); try w.beginArray(); try w.beginObject(); try w.objectField("name"); try w.print(" \"{s}\"", .{"lbl01"}); try w.objectField("posx"); try w.print(" {d}", .{10}); try w.objectField("posy"); try w.print(" {d}", .{11}); try w.objectField("text"); try w.print(" \"{s}\"", .{"Nom.......:"}); try w.objectField("title"); try w.print(" {}", .{true}); try w.endObject(); try w.beginObject(); try w.objectField("name"); try w.print(" \"{s}\"", .{"lbl02"}); try w.objectField("posx"); try w.print(" {d}", .{11}); try w.objectField("posy"); try w.print(" {d}", .{11}); try w.objectField("text"); try w.print(" \"{s}\"", .{"Prénom....:"}); try w.objectField("title"); try w.print(" {}", .{true}); try w.endObject(); try w.endArray(); try w.endObject(); try w.endArray(); try w.endObject(); const result = slice_stream.getWritten(); //std.debug.print("{s}\r\n",.{result}); var my_file = try std.fs.cwd().createFile("fileJson.txt", .{ .read = true }); _ = try my_file.write(result); my_file.close(); my_file = try std.fs.cwd().openFile("fileJson.txt", .{}); defer my_file.close(); var buf : []u8= allocator.alloc(u8, result.len) catch unreachable ; try my_file.seekTo(0); _= try my_file.read(buf[0..]); std.debug.print("{s}\r\n",.{buf}); // init arraylist ENRG.button = std.ArrayList(DEFBUTTON).init(allocator); ENRG.label = std.ArrayList(DEFLABEL).init(allocator); // return catch after panic jsonDecode(buf) catch return ; deb_Log("zmodlJson.txt"); plog(.main).debug("Begin\n", .{}); plog(.schema).debug("\nwrite Json",.{}); plog(.schema).debug("\n{s}\n",.{buf}); plog(.schema).debug("\nRead Json",.{}); plog(.Panel).debug("\n",.{}); plog(.Panel).debug("{s}",.{ENRG.name}); plog(.Panel).debug("{d}",.{ENRG.posx}); plog(.Panel).debug("{d}",.{ENRG.posy}); plog(.Panel).debug("{}", .{ENRG.cadre}); plog(.Panel).debug("{s}\n",.{ENRG.title}); plog(.Button).debug("\n", .{}); for (ENRG.button.items ) | f|{ plog(.Button).debug("{s}",.{f.name}); plog(.Button).debug("{any}" ,.{f.key}); plog(.Button).debug("{}" ,.{f.show}); plog(.Button).debug("{}" ,.{f.check}); plog(.Button).debug("{s}\n",.{f.title}); } plog(.Label).debug("\n", .{}); for (ENRG.label.items ) | f|{ plog(.Label).debug("{s}",.{f.name}); plog(.Label).debug("{d}" ,.{f.posx}); plog(.Label).debug("{d}" ,.{f.posy}); plog(.Label).debug("{s}" ,.{f.text}); plog(.Label).debug("{}\n",.{f.title}); } _= strToUsize_01("test"); plog(.end).debug("End.\n", .{}); end_Log(); } // end
0
repos
repos/resfs/README.md
# resfs **Res**ource **F**ile **S**ystem, or ResFS is a file system abstraction layer made specifically for games and applications in Zig. It includes file type detection, resource lookup, etc. To use it, just add it to your dependency tree in `build.zig.zon`. TODO: Better README.
0
repos
repos/resfs/build.zig.zon
.{ .name = "resfs", .version = "0.0.0", .paths = .{ "src", "build.zig.zon", "build.zig", }, }
0
repos
repos/resfs/build.zig
const std = @import("std"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const lib = b.addStaticLibrary(.{ .name = "resfs", .root_source_file = .{ .path = "src/root.zig" }, .target = target, .optimize = optimize, }); b.installArtifact(lib); const lib_unit_tests = b.addTest(.{ .root_source_file = .{ .path = "src/root.zig" }, .target = target, .optimize = optimize, }); const run_lib_unit_tests = b.addRunArtifact(lib_unit_tests); const test_step = b.step("test", "Run unit tests"); test_step.dependOn(&run_lib_unit_tests.step); }
0
repos/resfs
repos/resfs/src/filetype_map.zig
const std = @import("std"); pub const image_extensions = std.ComptimeStringMap(void, .{ .{ "jpg", {} }, .{ "jpeg", {} }, .{ "jpe", {} }, .{ "jif", {} }, .{ "jfif", {} }, .{ "jfi", {} }, .{ "png", {} }, .{ "webp", {} }, .{ "gif", {} }, .{ "tiff", {} }, .{ "tif", {} }, .{ "psd", {} }, .{ "raw", {} }, .{ "arw", {} }, .{ "cr2", {} }, .{ "nrw", {} }, .{ "k25", {} }, .{ "bmp", {} }, .{ "dib", {} }, .{ "heif", {} }, .{ "heic", {} }, .{ "ind", {} }, .{ "indd", {} }, .{ "indt", {} }, .{ "jp2", {} }, .{ "j2k", {} }, .{ "jpf", {} }, .{ "jpx", {} }, .{ "jpm", {} }, .{ "mj2", {} }, .{ "svg", {} }, .{ "svgz", {} }, .{ "ai", {} }, .{ "eps", {} }, .{ "pdf", {} }, }); pub const video_extensions = std.ComptimeStringMap(void, .{ .{ "webm", {} }, .{ "mpg", {} }, .{ "mpeg", {} }, .{ "mpe", {} }, .{ "mpv", {} }, .{ "mp4", {} }, .{ "m4p", {} }, .{ "m4v", {} }, .{ "avi", {} }, .{ "wmv", {} }, .{ "mov", {} }, .{ "qt", {} }, .{ "flv", {} }, .{ "swf", {} }, .{ "avchd", {} }, .{ "mkv", {} }, }); pub const audio_extensions = std.ComptimeStringMap(void, .{ .{ "ogg", .{} }, .{ "wav", .{} }, .{ "mp3", .{} }, .{ "flac", .{} }, .{ "m4a", {} }, .{ "midi", {} }, .{ "aac", {} }, .{ "amr", {} }, .{ "ra", {} }, .{ "wma", {} }, .{ "aiff", {} }, .{ "asf", {} }, .{ "vqf", {} }, .{ "mp2", {} }, .{ "ape", {} }, .{ "ac3", {} }, .{ "3ga", {} }, }); // pub const code_extensions = std.ComptimeStringMap(void, .{ // .{ ".abap", {} }, // .{ ".asc", {} }, // .{ ".ash", {} }, // .{ ".ampl", {} }, // .{ ".mod", {} }, // .{ ".g4", {} }, // .{ ".apib", {} }, // .{ ".apl", {} }, // .{ ".dyalog", {} }, // .{ ".asp", {} }, // .{ ".asax", {} }, // .{ ".ascx", {} }, // .{ ".ashx", {} }, // .{ ".asmx", {} }, // .{ ".aspx", {} }, // .{ ".axd", {} }, // .{ ".dats", {} }, // .{ ".hats", {} }, // .{ ".sats", {} }, // .{ ".as", {} }, // .{ ".adb", {} }, // .{ ".ada", {} }, // .{ ".ads", {} }, // .{ ".agda", {} }, // .{ ".als", {} }, // .{ ".apacheconf", {} }, // .{ ".vhost", {} }, // .{ ".cls", {} }, // .{ ".applescript", {} }, // .{ ".scpt", {} }, // .{ ".arc", {} }, // .{ ".ino", {} }, // .{ ".asciidoc", {} }, // .{ ".adoc", {} }, // .{ ".asc", {} }, // .{ ".aj", {} }, // .{ ".asm", {} }, // .{ ".a51", {} }, // .{ ".inc", {} }, // .{ ".nasm", {} }, // .{ ".aug", {} }, // .{ ".ahk", {} }, // .{ ".ahkl", {} }, // .{ ".au3", {} }, // .{ ".awk", {} }, // .{ ".auk", {} }, // .{ ".gawk", {} }, // .{ ".mawk", {} }, // .{ ".nawk", {} }, // .{ ".bat", {} }, // .{ ".cmd", {} }, // .{ ".befunge", {} }, // .{ ".bison", {} }, // .{ ".bb", {} }, // .{ ".bb", {} }, // .{ ".decls", {} }, // .{ ".bmx", {} }, // .{ ".bsv", {} }, // .{ ".boo", {} }, // .{ ".b", {} }, // .{ ".bf", {} }, // .{ ".brs", {} }, // .{ ".bro", {} }, // .{ ".c", {} }, // .{ ".cats", {} }, // .{ ".h", {} }, // .{ ".idc", {} }, // .{ ".w", {} }, // .{ ".cs", {} }, // .{ ".cake", {} }, // .{ ".cshtml", {} }, // .{ ".csx", {} }, // .{ ".cpp", {} }, // .{ ".c++", {} }, // .{ ".cc", {} }, // .{ ".cp", {} }, // .{ ".cxx", {} }, // .{ ".h", {} }, // .{ ".h++", {} }, // .{ ".hh", {} }, // .{ ".hpp", {} }, // .{ ".hxx", {} }, // .{ ".inc", {} }, // .{ ".inl", {} }, // .{ ".ipp", {} }, // .{ ".tcc", {} }, // .{ ".tpp", {} }, // .{ ".c-objdump", {} }, // .{ ".chs", {} }, // .{ ".clp", {} }, // .{ ".cmake", {} }, // .{ ".cmake.in", {} }, // .{ ".cob", {} }, // .{ ".cbl", {} }, // .{ ".ccp", {} }, // .{ ".cobol", {} }, // .{ ".cpy", {} }, // .{ ".css", {} }, // .{ ".csv", {} }, // .{ ".capnp", {} }, // .{ ".mss", {} }, // .{ ".ceylon", {} }, // .{ ".chpl", {} }, // .{ ".ch", {} }, // .{ ".ck", {} }, // .{ ".cirru", {} }, // .{ ".clw", {} }, // .{ ".icl", {} }, // .{ ".dcl", {} }, // .{ ".click", {} }, // .{ ".clj", {} }, // .{ ".boot", {} }, // .{ ".cl2", {} }, // .{ ".cljc", {} }, // .{ ".cljs", {} }, // .{ ".cljs.hl", {} }, // .{ ".cljscm", {} }, // .{ ".cljx", {} }, // .{ ".hic", {} }, // .{ ".coffee", {} }, // .{ "._coffee", {} }, // .{ ".cake", {} }, // .{ ".cjsx", {} }, // .{ ".cson", {} }, // .{ ".iced", {} }, // .{ ".cfm", {} }, // .{ ".cfml", {} }, // .{ ".cfc", {} }, // .{ ".lisp", {} }, // .{ ".asd", {} }, // .{ ".cl", {} }, // .{ ".l", {} }, // .{ ".lsp", {} }, // .{ ".ny", {} }, // .{ ".podsl", {} }, // .{ ".sexp", {} }, // .{ ".cp", {} }, // .{ ".cps", {} }, // .{ ".cl", {} }, // .{ ".coq", {} }, // .{ ".v", {} }, // .{ ".cppobjdump", {} }, // .{ ".c++-objdump", {} }, // .{ ".c++objdump", {} }, // .{ ".cpp-objdump", {} }, // .{ ".cxx-objdump", {} }, // .{ ".creole", {} }, // .{ ".cr", {} }, // .{ ".feature", {} }, // .{ ".cu", {} }, // .{ ".cuh", {} }, // .{ ".cy", {} }, // .{ ".pyx", {} }, // .{ ".pxd", {} }, // .{ ".pxi", {} }, // .{ ".d", {} }, // .{ ".di", {} }, // .{ ".d-objdump", {} }, // .{ ".com", {} }, // .{ ".dm", {} }, // .{ ".zone", {} }, // .{ ".arpa", {} }, // .{ ".d", {} }, // .{ ".darcspatch", {} }, // .{ ".dpatch", {} }, // .{ ".dart", {} }, // .{ ".diff", {} }, // .{ ".patch", {} }, // .{ ".dockerfile", {} }, // .{ ".djs", {} }, // .{ ".dylan", {} }, // .{ ".dyl", {} }, // .{ ".intr", {} }, // .{ ".lid", {} }, // .{ ".E", {} }, // .{ ".ecl", {} }, // .{ ".eclxml", {} }, // .{ ".ecl", {} }, // .{ ".sch", {} }, // .{ ".brd", {} }, // .{ ".epj", {} }, // .{ ".e", {} }, // .{ ".ex", {} }, // .{ ".exs", {} }, // .{ ".elm", {} }, // .{ ".el", {} }, // .{ ".emacs", {} }, // .{ ".emacs.desktop", {} }, // .{ ".em", {} }, // .{ ".emberscript", {} }, // .{ ".erl", {} }, // .{ ".es", {} }, // .{ ".escript", {} }, // .{ ".hrl", {} }, // .{ ".xrl", {} }, // .{ ".yrl", {} }, // .{ ".fs", {} }, // .{ ".fsi", {} }, // .{ ".fsx", {} }, // .{ ".fx", {} }, // .{ ".flux", {} }, // .{ ".f90", {} }, // .{ ".f", {} }, // .{ ".f03", {} }, // .{ ".f08", {} }, // .{ ".f77", {} }, // .{ ".f95", {} }, // .{ ".for", {} }, // .{ ".fpp", {} }, // .{ ".factor", {} }, // .{ ".fy", {} }, // .{ ".fancypack", {} }, // .{ ".fan", {} }, // .{ ".fs", {} }, // .{ ".for", {} }, // .{ ".eam.fs", {} }, // .{ ".fth", {} }, // .{ ".4th", {} }, // .{ ".f", {} }, // .{ ".for", {} }, // .{ ".forth", {} }, // .{ ".fr", {} }, // .{ ".frt", {} }, // .{ ".fs", {} }, // .{ ".ftl", {} }, // .{ ".fr", {} }, // .{ ".g", {} }, // .{ ".gco", {} }, // .{ ".gcode", {} }, // .{ ".gms", {} }, // .{ ".g", {} }, // .{ ".gap", {} }, // .{ ".gd", {} }, // .{ ".gi", {} }, // .{ ".tst", {} }, // .{ ".s", {} }, // .{ ".ms", {} }, // .{ ".gd", {} }, // .{ ".glsl", {} }, // .{ ".fp", {} }, // .{ ".frag", {} }, // .{ ".frg", {} }, // .{ ".fs", {} }, // .{ ".fsh", {} }, // .{ ".fshader", {} }, // .{ ".geo", {} }, // .{ ".geom", {} }, // .{ ".glslv", {} }, // .{ ".gshader", {} }, // .{ ".shader", {} }, // .{ ".vert", {} }, // .{ ".vrx", {} }, // .{ ".vsh", {} }, // .{ ".vshader", {} }, // .{ ".gml", {} }, // .{ ".kid", {} }, // .{ ".ebuild", {} }, // .{ ".eclass", {} }, // .{ ".po", {} }, // .{ ".pot", {} }, // .{ ".glf", {} }, // .{ ".gp", {} }, // .{ ".gnu", {} }, // .{ ".gnuplot", {} }, // .{ ".plot", {} }, // .{ ".plt", {} }, // .{ ".go", {} }, // .{ ".golo", {} }, // .{ ".gs", {} }, // .{ ".gst", {} }, // .{ ".gsx", {} }, // .{ ".vark", {} }, // .{ ".grace", {} }, // .{ ".gradle", {} }, // .{ ".gf", {} }, // .{ ".gml", {} }, // .{ ".graphql", {} }, // .{ ".dot", {} }, // .{ ".gv", {} }, // .{ ".man", {} }, // .{ ".1", {} }, // .{ ".1in", {} }, // .{ ".1m", {} }, // .{ ".1x", {} }, // .{ ".2", {} }, // .{ ".3", {} }, // .{ ".3in", {} }, // .{ ".3m", {} }, // .{ ".3qt", {} }, // .{ ".3x", {} }, // .{ ".4", {} }, // .{ ".5", {} }, // .{ ".6", {} }, // .{ ".7", {} }, // .{ ".8", {} }, // .{ ".9", {} }, // .{ ".l", {} }, // .{ ".me", {} }, // .{ ".ms", {} }, // .{ ".n", {} }, // .{ ".rno", {} }, // .{ ".roff", {} }, // .{ ".groovy", {} }, // .{ ".grt", {} }, // .{ ".gtpl", {} }, // .{ ".gvy", {} }, // .{ ".gsp", {} }, // .{ ".hcl", {} }, // .{ ".tf", {} }, // .{ ".hlsl", {} }, // .{ ".fx", {} }, // .{ ".fxh", {} }, // .{ ".hlsli", {} }, // .{ ".html", {} }, // .{ ".htm", {} }, // .{ ".html.hl", {} }, // .{ ".inc", {} }, // .{ ".st", {} }, // .{ ".xht", {} }, // .{ ".xhtml", {} }, // .{ ".mustache", {} }, // .{ ".jinja", {} }, // .{ ".eex", {} }, // .{ ".erb", {} }, // .{ ".erb.deface", {} }, // .{ ".phtml", {} }, // .{ ".http", {} }, // .{ ".hh", {} }, // .{ ".php", {} }, // .{ ".haml", {} }, // .{ ".haml.deface", {} }, // .{ ".handlebars", {} }, // .{ ".hbs", {} }, // .{ ".hb", {} }, // .{ ".hs", {} }, // .{ ".hsc", {} }, // .{ ".hx", {} }, // .{ ".hxsl", {} }, // .{ ".hy", {} }, // .{ ".bf", {} }, // .{ ".pro", {} }, // .{ ".dlm", {} }, // .{ ".ipf", {} }, // .{ ".ini", {} }, // .{ ".cfg", {} }, // .{ ".prefs", {} }, // .{ ".pro", {} }, // .{ ".properties", {} }, // .{ ".irclog", {} }, // .{ ".weechatlog", {} }, // .{ ".idr", {} }, // .{ ".lidr", {} }, // .{ ".ni", {} }, // .{ ".i7x", {} }, // .{ ".iss", {} }, // .{ ".io", {} }, // .{ ".ik", {} }, // .{ ".thy", {} }, // .{ ".ijs", {} }, // .{ ".flex", {} }, // .{ ".jflex", {} }, // .{ ".json", {} }, // .{ ".geojson", {} }, // .{ ".lock", {} }, // .{ ".topojson", {} }, // .{ ".json5", {} }, // .{ ".jsonld", {} }, // .{ ".jq", {} }, // .{ ".jsx", {} }, // .{ ".jade", {} }, // .{ ".j", {} }, // .{ ".java", {} }, // .{ ".jsp", {} }, // .{ ".js", {} }, // .{ "._js", {} }, // .{ ".bones", {} }, // .{ ".es", {} }, // .{ ".es6", {} }, // .{ ".frag", {} }, // .{ ".gs", {} }, // .{ ".jake", {} }, // .{ ".jsb", {} }, // .{ ".jscad", {} }, // .{ ".jsfl", {} }, // .{ ".jsm", {} }, // .{ ".jss", {} }, // .{ ".njs", {} }, // .{ ".pac", {} }, // .{ ".sjs", {} }, // .{ ".ssjs", {} }, // .{ ".sublime-build", {} }, // .{ ".sublime-commands", {} }, // .{ ".sublime-completions", {} }, // .{ ".sublime-keymap", {} }, // .{ ".sublime-macro", {} }, // .{ ".sublime-menu", {} }, // .{ ".sublime-mousemap", {} }, // .{ ".sublime-project", {} }, // .{ ".sublime-settings", {} }, // .{ ".sublime-theme", {} }, // .{ ".sublime-workspace", {} }, // .{ ".sublime_metrics", {} }, // .{ ".sublime_session", {} }, // .{ ".xsjs", {} }, // .{ ".xsjslib", {} }, // .{ ".jl", {} }, // .{ ".ipynb", {} }, // .{ ".krl", {} }, // .{ ".sch", {} }, // .{ ".brd", {} }, // .{ ".kicad_pcb", {} }, // .{ ".kit", {} }, // .{ ".kt", {} }, // .{ ".ktm", {} }, // .{ ".kts", {} }, // .{ ".lfe", {} }, // .{ ".ll", {} }, // .{ ".lol", {} }, // .{ ".lsl", {} }, // .{ ".lslp", {} }, // .{ ".lvproj", {} }, // .{ ".lasso", {} }, // .{ ".las", {} }, // .{ ".lasso8", {} }, // .{ ".lasso9", {} }, // .{ ".ldml", {} }, // .{ ".latte", {} }, // .{ ".lean", {} }, // .{ ".hlean", {} }, // .{ ".less", {} }, // .{ ".l", {} }, // .{ ".lex", {} }, // .{ ".ly", {} }, // .{ ".ily", {} }, // .{ ".b", {} }, // .{ ".m", {} }, // .{ ".ld", {} }, // .{ ".lds", {} }, // .{ ".mod", {} }, // .{ ".liquid", {} }, // .{ ".lagda", {} }, // .{ ".litcoffee", {} }, // .{ ".lhs", {} }, // .{ ".ls", {} }, // .{ "._ls", {} }, // .{ ".xm", {} }, // .{ ".x", {} }, // .{ ".xi", {} }, // .{ ".lgt", {} }, // .{ ".logtalk", {} }, // .{ ".lookml", {} }, // .{ ".ls", {} }, // .{ ".lua", {} }, // .{ ".fcgi", {} }, // .{ ".nse", {} }, // .{ ".pd_lua", {} }, // .{ ".rbxs", {} }, // .{ ".wlua", {} }, // .{ ".mumps", {} }, // .{ ".m", {} }, // .{ ".m4", {} }, // .{ ".m4", {} }, // .{ ".ms", {} }, // .{ ".mcr", {} }, // .{ ".mtml", {} }, // .{ ".muf", {} }, // .{ ".m", {} }, // .{ ".mak", {} }, // .{ ".d", {} }, // .{ ".mk", {} }, // .{ ".mkfile", {} }, // .{ ".mako", {} }, // .{ ".mao", {} }, // .{ ".md", {} }, // .{ ".markdown", {} }, // .{ ".mkd", {} }, // .{ ".mkdn", {} }, // .{ ".mkdown", {} }, // .{ ".ron", {} }, // .{ ".mask", {} }, // .{ ".mathematica", {} }, // .{ ".cdf", {} }, // .{ ".m", {} }, // .{ ".ma", {} }, // .{ ".mt", {} }, // .{ ".nb", {} }, // .{ ".nbp", {} }, // .{ ".wl", {} }, // .{ ".wlt", {} }, // .{ ".matlab", {} }, // .{ ".m", {} }, // .{ ".maxpat", {} }, // .{ ".maxhelp", {} }, // .{ ".maxproj", {} }, // .{ ".mxt", {} }, // .{ ".pat", {} }, // .{ ".mediawiki", {} }, // .{ ".wiki", {} }, // .{ ".m", {} }, // .{ ".moo", {} }, // .{ ".metal", {} }, // .{ ".minid", {} }, // .{ ".druby", {} }, // .{ ".duby", {} }, // .{ ".mir", {} }, // .{ ".mirah", {} }, // .{ ".mo", {} }, // .{ ".mod", {} }, // .{ ".mms", {} }, // .{ ".mmk", {} }, // .{ ".monkey", {} }, // .{ ".moo", {} }, // .{ ".moon", {} }, // .{ ".myt", {} }, // .{ ".ncl", {} }, // .{ ".nl", {} }, // .{ ".nsi", {} }, // .{ ".nsh", {} }, // .{ ".n", {} }, // .{ ".axs", {} }, // .{ ".axi", {} }, // .{ ".axs.erb", {} }, // .{ ".axi.erb", {} }, // .{ ".nlogo", {} }, // .{ ".nl", {} }, // .{ ".lisp", {} }, // .{ ".lsp", {} }, // .{ ".nginxconf", {} }, // .{ ".vhost", {} }, // .{ ".nim", {} }, // .{ ".nimrod", {} }, // .{ ".ninja", {} }, // .{ ".nit", {} }, // .{ ".nix", {} }, // .{ ".nu", {} }, // .{ ".numpy", {} }, // .{ ".numpyw", {} }, // .{ ".numsc", {} }, // .{ ".ml", {} }, // .{ ".eliom", {} }, // .{ ".eliomi", {} }, // .{ ".ml4", {} }, // .{ ".mli", {} }, // .{ ".mll", {} }, // .{ ".mly", {} }, // .{ ".objdump", {} }, // .{ ".m", {} }, // .{ ".h", {} }, // .{ ".mm", {} }, // .{ ".j", {} }, // .{ ".sj", {} }, // .{ ".omgrofl", {} }, // .{ ".opa", {} }, // .{ ".opal", {} }, // .{ ".cl", {} }, // .{ ".opencl", {} }, // .{ ".p", {} }, // .{ ".cls", {} }, // .{ ".scad", {} }, // .{ ".org", {} }, // .{ ".ox", {} }, // .{ ".oxh", {} }, // .{ ".oxo", {} }, // .{ ".oxygene", {} }, // .{ ".oz", {} }, // .{ ".pwn", {} }, // .{ ".inc", {} }, // .{ ".php", {} }, // .{ ".aw", {} }, // .{ ".ctp", {} }, // .{ ".fcgi", {} }, // .{ ".inc", {} }, // .{ ".php3", {} }, // .{ ".php4", {} }, // .{ ".php5", {} }, // .{ ".phps", {} }, // .{ ".phpt", {} }, // .{ ".pls", {} }, // .{ ".pck", {} }, // .{ ".pkb", {} }, // .{ ".pks", {} }, // .{ ".plb", {} }, // .{ ".plsql", {} }, // .{ ".sql", {} }, // .{ ".sql", {} }, // .{ ".pov", {} }, // .{ ".inc", {} }, // .{ ".pan", {} }, // .{ ".psc", {} }, // .{ ".parrot", {} }, // .{ ".pasm", {} }, // .{ ".pir", {} }, // .{ ".pas", {} }, // .{ ".dfm", {} }, // .{ ".dpr", {} }, // .{ ".inc", {} }, // .{ ".lpr", {} }, // .{ ".pp", {} }, // .{ ".pl", {} }, // .{ ".al", {} }, // .{ ".cgi", {} }, // .{ ".fcgi", {} }, // .{ ".perl", {} }, // .{ ".ph", {} }, // .{ ".plx", {} }, // .{ ".pm", {} }, // .{ ".pod", {} }, // .{ ".psgi", {} }, // .{ ".t", {} }, // .{ ".6pl", {} }, // .{ ".6pm", {} }, // .{ ".nqp", {} }, // .{ ".p6", {} }, // .{ ".p6l", {} }, // .{ ".p6m", {} }, // .{ ".pl", {} }, // .{ ".pl6", {} }, // .{ ".pm", {} }, // .{ ".pm6", {} }, // .{ ".t", {} }, // .{ ".pkl", {} }, // .{ ".l", {} }, // .{ ".pig", {} }, // .{ ".pike", {} }, // .{ ".pmod", {} }, // .{ ".pod", {} }, // .{ ".pogo", {} }, // .{ ".pony", {} }, // .{ ".ps", {} }, // .{ ".eps", {} }, // .{ ".ps1", {} }, // .{ ".psd1", {} }, // .{ ".psm1", {} }, // .{ ".pde", {} }, // .{ ".pl", {} }, // .{ ".pro", {} }, // .{ ".prolog", {} }, // .{ ".yap", {} }, // .{ ".spin", {} }, // .{ ".proto", {} }, // .{ ".asc", {} }, // .{ ".pub", {} }, // .{ ".pp", {} }, // .{ ".pd", {} }, // .{ ".pb", {} }, // .{ ".pbi", {} }, // .{ ".purs", {} }, // .{ ".py", {} }, // .{ ".bzl", {} }, // .{ ".cgi", {} }, // .{ ".fcgi", {} }, // .{ ".gyp", {} }, // .{ ".lmi", {} }, // .{ ".pyde", {} }, // .{ ".pyp", {} }, // .{ ".pyt", {} }, // .{ ".pyw", {} }, // .{ ".rpy", {} }, // .{ ".tac", {} }, // .{ ".wsgi", {} }, // .{ ".xpy", {} }, // .{ ".pytb", {} }, // .{ ".qml", {} }, // .{ ".qbs", {} }, // .{ ".pro", {} }, // .{ ".pri", {} }, // .{ ".r", {} }, // .{ ".rd", {} }, // .{ ".rsx", {} }, // .{ ".raml", {} }, // .{ ".rdoc", {} }, // .{ ".rbbas", {} }, // .{ ".rbfrm", {} }, // .{ ".rbmnu", {} }, // .{ ".rbres", {} }, // .{ ".rbtbar", {} }, // .{ ".rbuistate", {} }, // .{ ".rhtml", {} }, // .{ ".rmd", {} }, // .{ ".rkt", {} }, // .{ ".rktd", {} }, // .{ ".rktl", {} }, // .{ ".scrbl", {} }, // .{ ".rl", {} }, // .{ ".raw", {} }, // .{ ".reb", {} }, // .{ ".r", {} }, // .{ ".r2", {} }, // .{ ".r3", {} }, // .{ ".rebol", {} }, // .{ ".red", {} }, // .{ ".reds", {} }, // .{ ".cw", {} }, // .{ ".rpy", {} }, // .{ ".rs", {} }, // .{ ".rsh", {} }, // .{ ".robot", {} }, // .{ ".rg", {} }, // .{ ".rb", {} }, // .{ ".builder", {} }, // .{ ".fcgi", {} }, // .{ ".gemspec", {} }, // .{ ".god", {} }, // .{ ".irbrc", {} }, // .{ ".jbuilder", {} }, // .{ ".mspec", {} }, // .{ ".pluginspec", {} }, // .{ ".podspec", {} }, // .{ ".rabl", {} }, // .{ ".rake", {} }, // .{ ".rbuild", {} }, // .{ ".rbw", {} }, // .{ ".rbx", {} }, // .{ ".ru", {} }, // .{ ".ruby", {} }, // .{ ".thor", {} }, // .{ ".watchr", {} }, // .{ ".rs", {} }, // .{ ".rs.in", {} }, // .{ ".sas", {} }, // .{ ".scss", {} }, // .{ ".smt2", {} }, // .{ ".smt", {} }, // .{ ".sparql", {} }, // .{ ".rq", {} }, // .{ ".sqf", {} }, // .{ ".hqf", {} }, // .{ ".sql", {} }, // .{ ".cql", {} }, // .{ ".ddl", {} }, // .{ ".inc", {} }, // .{ ".prc", {} }, // .{ ".tab", {} }, // .{ ".udf", {} }, // .{ ".viw", {} }, // .{ ".sql", {} }, // .{ ".db2", {} }, // .{ ".ston", {} }, // .{ ".svg", {} }, // .{ ".sage", {} }, // .{ ".sagews", {} }, // .{ ".sls", {} }, // .{ ".sass", {} }, // .{ ".scala", {} }, // .{ ".sbt", {} }, // .{ ".sc", {} }, // .{ ".scaml", {} }, // .{ ".scm", {} }, // .{ ".sld", {} }, // .{ ".sls", {} }, // .{ ".sps", {} }, // .{ ".ss", {} }, // .{ ".sci", {} }, // .{ ".sce", {} }, // .{ ".tst", {} }, // .{ ".self", {} }, // .{ ".sh", {} }, // .{ ".bash", {} }, // .{ ".bats", {} }, // .{ ".cgi", {} }, // .{ ".command", {} }, // .{ ".fcgi", {} }, // .{ ".ksh", {} }, // .{ ".sh.in", {} }, // .{ ".tmux", {} }, // .{ ".tool", {} }, // .{ ".zsh", {} }, // .{ ".sh-session", {} }, // .{ ".shen", {} }, // .{ ".sl", {} }, // .{ ".slim", {} }, // .{ ".smali", {} }, // .{ ".st", {} }, // .{ ".cs", {} }, // .{ ".tpl", {} }, // .{ ".sp", {} }, // .{ ".inc", {} }, // .{ ".sma", {} }, // .{ ".nut", {} }, // .{ ".stan", {} }, // .{ ".ML", {} }, // .{ ".fun", {} }, // .{ ".sig", {} }, // .{ ".sml", {} }, // .{ ".do", {} }, // .{ ".ado", {} }, // .{ ".doh", {} }, // .{ ".ihlp", {} }, // .{ ".mata", {} }, // .{ ".matah", {} }, // .{ ".sthlp", {} }, // .{ ".styl", {} }, // .{ ".sc", {} }, // .{ ".scd", {} }, // .{ ".swift", {} }, // .{ ".sv", {} }, // .{ ".svh", {} }, // .{ ".vh", {} }, // .{ ".toml", {} }, // .{ ".txl", {} }, // .{ ".tcl", {} }, // .{ ".adp", {} }, // .{ ".tm", {} }, // .{ ".tcsh", {} }, // .{ ".csh", {} }, // .{ ".tex", {} }, // .{ ".aux", {} }, // .{ ".bbx", {} }, // .{ ".bib", {} }, // .{ ".cbx", {} }, // .{ ".cls", {} }, // .{ ".dtx", {} }, // .{ ".ins", {} }, // .{ ".lbx", {} }, // .{ ".ltx", {} }, // .{ ".mkii", {} }, // .{ ".mkiv", {} }, // .{ ".mkvi", {} }, // .{ ".sty", {} }, // .{ ".toc", {} }, // .{ ".tea", {} }, // .{ ".t", {} }, // .{ ".txt", {} }, // .{ ".fr", {} }, // .{ ".nb", {} }, // .{ ".ncl", {} }, // .{ ".no", {} }, // .{ ".textile", {} }, // .{ ".thrift", {} }, // .{ ".t", {} }, // .{ ".tu", {} }, // .{ ".ttl", {} }, // .{ ".twig", {} }, // .{ ".ts", {} }, // .{ ".tsx", {} }, // .{ ".upc", {} }, // .{ ".anim", {} }, // .{ ".asset", {} }, // .{ ".mat", {} }, // .{ ".meta", {} }, // .{ ".prefab", {} }, // .{ ".unity", {} }, // .{ ".uno", {} }, // .{ ".uc", {} }, // .{ ".ur", {} }, // .{ ".urs", {} }, // .{ ".vcl", {} }, // .{ ".vhdl", {} }, // .{ ".vhd", {} }, // .{ ".vhf", {} }, // .{ ".vhi", {} }, // .{ ".vho", {} }, // .{ ".vhs", {} }, // .{ ".vht", {} }, // .{ ".vhw", {} }, // .{ ".vala", {} }, // .{ ".vapi", {} }, // .{ ".v", {} }, // .{ ".veo", {} }, // .{ ".vim", {} }, // .{ ".vb", {} }, // .{ ".bas", {} }, // .{ ".cls", {} }, // .{ ".frm", {} }, // .{ ".frx", {} }, // .{ ".vba", {} }, // .{ ".vbhtml", {} }, // .{ ".vbs", {} }, // .{ ".volt", {} }, // .{ ".vue", {} }, // .{ ".owl", {} }, // .{ ".webidl", {} }, // .{ ".x10", {} }, // .{ ".xc", {} }, // .{ ".xml", {} }, // .{ ".ant", {} }, // .{ ".axml", {} }, // .{ ".ccxml", {} }, // .{ ".clixml", {} }, // .{ ".cproject", {} }, // .{ ".csl", {} }, // .{ ".csproj", {} }, // .{ ".ct", {} }, // .{ ".dita", {} }, // .{ ".ditamap", {} }, // .{ ".ditaval", {} }, // .{ ".dll.config", {} }, // .{ ".dotsettings", {} }, // .{ ".filters", {} }, // .{ ".fsproj", {} }, // .{ ".fxml", {} }, // .{ ".glade", {} }, // .{ ".gml", {} }, // .{ ".grxml", {} }, // .{ ".iml", {} }, // .{ ".ivy", {} }, // .{ ".jelly", {} }, // .{ ".jsproj", {} }, // .{ ".kml", {} }, // .{ ".launch", {} }, // .{ ".mdpolicy", {} }, // .{ ".mm", {} }, // .{ ".mod", {} }, // .{ ".mxml", {} }, // .{ ".nproj", {} }, // .{ ".nuspec", {} }, // .{ ".odd", {} }, // .{ ".osm", {} }, // .{ ".plist", {} }, // .{ ".pluginspec", {} }, // .{ ".props", {} }, // .{ ".ps1xml", {} }, // .{ ".psc1", {} }, // .{ ".pt", {} }, // .{ ".rdf", {} }, // .{ ".rss", {} }, // .{ ".scxml", {} }, // .{ ".srdf", {} }, // .{ ".storyboard", {} }, // .{ ".stTheme", {} }, // .{ ".sublime-snippet", {} }, // .{ ".targets", {} }, // .{ ".tmCommand", {} }, // .{ ".tml", {} }, // .{ ".tmLanguage", {} }, // .{ ".tmPreferences", {} }, // .{ ".tmSnippet", {} }, // .{ ".tmTheme", {} }, // .{ ".ts", {} }, // .{ ".tsx", {} }, // .{ ".ui", {} }, // .{ ".urdf", {} }, // .{ ".ux", {} }, // .{ ".vbproj", {} }, // .{ ".vcxproj", {} }, // .{ ".vssettings", {} }, // .{ ".vxml", {} }, // .{ ".wsdl", {} }, // .{ ".wsf", {} }, // .{ ".wxi", {} }, // .{ ".wxl", {} }, // .{ ".wxs", {} }, // .{ ".x3d", {} }, // .{ ".xacro", {} }, // .{ ".xaml", {} }, // .{ ".xib", {} }, // .{ ".xlf", {} }, // .{ ".xliff", {} }, // .{ ".xmi", {} }, // .{ ".xml.dist", {} }, // .{ ".xproj", {} }, // .{ ".xsd", {} }, // .{ ".xul", {} }, // .{ ".zcml", {} }, // .{ ".xsp-config", {} }, // .{ ".xsp.metadata", {} }, // .{ ".xpl", {} }, // .{ ".xproc", {} }, // .{ ".xquery", {} }, // .{ ".xq", {} }, // .{ ".xql", {} }, // .{ ".xqm", {} }, // .{ ".xqy", {} }, // .{ ".xs", {} }, // .{ ".xslt", {} }, // .{ ".xsl", {} }, // .{ ".xojo_code", {} }, // .{ ".xojo_menu", {} }, // .{ ".xojo_report", {} }, // .{ ".xojo_script", {} }, // .{ ".xojo_toolbar", {} }, // .{ ".xojo_window", {} }, // .{ ".xtend", {} }, // .{ ".yml", {} }, // .{ ".reek", {} }, // .{ ".rviz", {} }, // .{ ".sublime-syntax", {} }, // .{ ".syntax", {} }, // .{ ".yaml", {} }, // .{ ".yaml-tmlanguage", {} }, // .{ ".yang", {} }, // .{ ".y", {} }, // .{ ".yacc", {} }, // .{ ".yy", {} }, // .{ ".zep", {} }, // .{ ".zimpl", {} }, // .{ ".zmpl", {} }, // .{ ".zpl", {} }, // .{ ".desktop", {} }, // .{ ".desktop.in", {} }, // .{ ".ec", {} }, // .{ ".eh", {} }, // .{ ".edn", {} }, // .{ ".fish", {} }, // .{ ".mu", {} }, // .{ ".nc", {} }, // .{ ".ooc", {} }, // .{ ".rst", {} }, // .{ ".rest", {} }, // .{ ".rest.txt", {} }, // .{ ".rst.txt", {} }, // .{ ".wisp", {} }, // .{ ".prg", {} }, // .{ ".ch", {} }, // .{ ".prw", {} }, // });
0
repos/resfs
repos/resfs/src/root.zig
const std = @import("std"); const log = std.log.scoped(.resfs); const filetype_map = @import("filetype_map.zig"); test { _ = xdg_dirs; } pub const xdg_dirs = @import("xdg_dirs.zig"); pub const sep = std.fs.path.sep_str; const root = @import("root"); const override = if (@hasDecl(root, "resfs_dirs")) root.resfs_dirs else struct {}; /// A list of paths to directories that resfs refers to when /// looking up resources. Every path is obtained from joining `ResFs`'s root_path and /// any path relative to `assets_path`. pub const dirs = struct { /// Root path to all the resources that are managed by the library. pub const assets_path: []const u8 = if (@hasDecl(override, "assets_path")) override.assets_path else "assets"; pub const bin_path: []const u8 = if (@hasDecl(override, "bin_path")) override.bin_path else assets_path ++ sep ++ "bin"; /// Path to audio resources. Must be inside the `assets_path`. pub const audio_path = if (@hasDecl(override, "audio_path")) override.audio_path else assets_path ++ sep ++ "audio"; /// Path to sound effects. Should logically be inside `audio_path`. pub const sfx_path = if (@hasDecl(override, "sfx_path")) override.sfx_path else audio_path ++ sep ++ "sfx"; /// Path to music files. Should logically be inside `audio_path`. pub const music_path = if (@hasDecl(override, "music_path")) override.music_path else audio_path ++ sep ++ "music"; /// Path to video files. pub const videos_path = if (@hasDecl(override, "videos_path")) override.videos_path else assets_path ++ sep ++ "videos"; /// Path to image files. pub const images_path = if (@hasDecl(override, "images_path")) override.images_path else assets_path ++ sep ++ "images"; /// Path to textures. Logically should be inside `images_path`. pub const textures_path = if (@hasDecl(override, "textures_path")) override.textures_path else images_path ++ sep ++ "textures"; /// Path to sprites. Logically should be inside `images_path`. pub const sprites_path = if (@hasDecl(override, "sprites_path")) override.sprites_path else images_path ++ sep ++ "sprites"; /// Path to 3D models (.obj, .fbx, etc.). pub const models_path = if (@hasDecl(override, "models_path")) override.models_path else assets_path ++ sep ++ "models"; /// Path to scripts (any text file). pub const scripts_path = if (@hasDecl(override, "scripts_path")) override.scripts_path else assets_path ++ sep ++ "scripts"; /// Path to misc resources. pub const misc_path = if (@hasDecl(override, "misc_path")) override.misc_path else assets_path ++ sep ++ "misc"; }; const ResFs = @This(); pub const ResourceType = enum { unknown, asset, bin, audio, sfx, music, image, video, texture, sprite, model, script, misc, pub fn fromText(s: []const u8) ResourceType { return inline for (@typeInfo(ResourceType).Enum.fields) |f| if (std.mem.eql(u8, s, f.name)) @as(ResourceType, @enumFromInt(f.value)); } pub fn fromExtension(s: []const u8) ResourceType { const ext = std.fs.path.extension(s); if (filetype_map.image_extensions.has(ext)) return .image; if (filetype_map.video_extensions.has(ext)) return .video; if (filetype_map.audio_extensions.has(ext)) return .audio; // if (filetype_map.code_extensions.has(ext)) // return .script; // // if (filetype_map.model_extensions.has(ext)) // return .model; return .asset; } pub fn getPath(self: ResourceType) ?[]const u8 { return switch (self) { .asset => dirs.assets_path, .audio => dirs.audio_path, .sfx => dirs.sfx_path, .music => dirs.music_path, .image => dirs.images_path, .video => dirs.videos_path, .texture => dirs.textures_path, .sprite => dirs.sprites_path, .model => dirs.models_path, .script => dirs.scripts_path, .misc => dirs.misc, .bin => dirs.bin_path, else => null, }; } }; arena: std.heap.ArenaAllocator, root_path: []const u8, root_handle: ?std.fs.Dir = null, pub fn init(allocator: std.mem.Allocator, cwd: bool) !ResFs { var arena = std.heap.ArenaAllocator.init(allocator); var buf: [std.fs.MAX_PATH_BYTES]u8 = [_]u8{0} ** std.fs.MAX_PATH_BYTES; const path = if (!cwd) try std.fs.selfExeDirPathAlloc(arena.allocator()) else blk: { const bytes = try std.os.getcwd(&buf); break :blk try allocator.dupe(u8, bytes); }; return .{ .arena = arena, .root_path = path, .root_handle = try std.fs.cwd().openDir(path), }; } pub fn deinit(self: *ResFs) void { self.arena.deinit(); self.root_handle.?.close(); self.* = undefined; } pub fn expandUri(self: *ResFs, uri: []const u8) ![]const u8 { const p_uri = try std.Uri.parse(uri); const r_path = ResourceType.fromText(p_uri.scheme).getPath() orelse return error.UnknownResourceType; return std.fs.path.join(self.arena, &[_][]const u8{ self.root_path, r_path, p_uri.path }); } pub fn expandUriAndOpen(self: *ResFs, uri: []const u8, open_flags: std.fs.File.OpenFlags) !std.fs.Dir { return std.fs.cwd().openFile(try self.expandUri(uri), open_flags); } pub const getAssetPath = expandUri; pub const getAsset = expandUriAndOpen; test "fromExtension" { var t = try std.time.Timer.start(); try std.testing.expect(ResourceType.fromExtension("py") == .asset); std.debug.print("\n\ntook {d}ms", .{std.time.ns_per_ms / t.lap()}); }
0
repos/resfs
repos/resfs/src/xdg_dirs.zig
//! This file contains functions and types for working with Linux desktop directories, //! according to the XDG Basedir Specification. const std = @import("std"); /// Desktop directories according to /// [XDG Basedir Specification](https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html) pub const XdgDirType = enum { /// User-specific data files user_data, /// User-specific configuration data user_config, /// User-specific state data user_state, /// User-specific cache user_cache, /// User-specific runtime files user_runtime, /// Set of preference ordered data file dirs data, /// Set of preference ordered configuration dirs config, /// Returns the name of an environment variable corresponding to `self` pub fn getEnvVarName(comptime self: XdgDirType) []const u8 { return switch (self) { .user_data => "XDG_DATA_HOME", .user_config => "XDG_CONFIG_HOME", .user_state => "XDG_STATE_HOME", .user_cache => "XDG_CACHE_HOME", .user_runtime => "XDG_RUNTIME_DIR", .data => "XDG_DATA_DIRS", .config => "XDG_CONFIG_DIRS", }; } /// Returns a default XDG directory that is used when the corresponding /// environment variable is empty or not set as stated in XDG specification. pub fn getDefaultPath(comptime self: XdgDirType) []const u8 { return switch (self) { .user_data => ".local/share", .user_config => ".config", .user_state => ".local/state", .user_cache => ".cache", .user_runtime => "/run/user", .data => "usr/local/share:/usr/share", .config => "/etc/xdg", }; } }; fn getUidString(allocator: std.mem.Allocator) []const u8 { const uid = std.os.linux.getuid(); return std.fmt.allocPrint(allocator, "{d}", .{uid}) catch unreachable; } /// Returns a default runtime directory according to the XDG Basedir Specification. /// Caller owns the memory. pub fn getXdgRuntimeDirDefault(allocator: std.mem.Allocator) []const u8 { const runtime_path = comptime XdgDirType.getDefaultPath(.user_runtime); const uid = getUidString(allocator); return std.fs.path.join(allocator, &[_][]const u8{ runtime_path, uid }); } /// Returns an environment-defined path corresponding to `kind`, orelse returns /// a default for `kind`. Retunrs an error if the path stored in the environment variable /// is not absolute. pub fn getXdgDir(kind: XdgDirType) ![]const u8 { const path = std.os.getenv(kind.getEnvVarName()) orelse kind.getDefaultPath(); if (!std.fs.path.isAbsolute(path)) return error.XdgPathMustBeAbsolute; return path; } /// Opens an XDG directory and returns the handle. pub fn openXdgDir(kind: XdgDirType) !std.fs.Dir { return std.fs.openDirAbsolute(try getXdgDir(kind)); }
0
repos
repos/unordered/.appveyor.yml
# Copyright 2016, 2017 Peter Dimov # Copyright 2017 - 2019 James E. King III # Copyright 2019 - 2021 Alexander Grund # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at http://boost.org/LICENSE_1_0.txt) version: 1.0.{build}-{branch} shallow_clone: true branches: only: - master - develop - /bugfix\/.*/ - /feature\/.*/ - /fix\/.*/ - /pr\/.*/ matrix: fast_finish: false # Adding MAYFAIL to any matrix job allows it to fail but the build stays green: allow_failures: - MAYFAIL: true environment: global: B2_CI_VERSION: 1 GIT_FETCH_JOBS: 4 B2_ADDRESS_MODEL: 32,64 B2_VARIANT: debug,release matrix: - FLAVOR: Visual Studio 2015 APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2015 B2_TOOLSET: msvc-14.0 - FLAVOR: Visual Studio 2017, C++14 APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 B2_CXXSTD: 14 B2_TOOLSET: msvc-14.1 - FLAVOR: Visual Studio 2017, C++17 APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 B2_CXXSTD: 17 B2_TOOLSET: msvc-14.1 - FLAVOR: Visual Studio 2017, C++latest APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 B2_CXXSTD: latest B2_TOOLSET: msvc-14.1 - FLAVOR: cygwin (32-bit, C++11) APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 ADDPATH: C:\cygwin\bin; B2_ADDRESS_MODEL: 32 B2_CXXSTD: 11 B2_TOOLSET: gcc - FLAVOR: cygwin (32-bit, C++14) APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 ADDPATH: C:\cygwin\bin; B2_ADDRESS_MODEL: 32 B2_CXXSTD: 14 B2_TOOLSET: gcc - FLAVOR: cygwin (32-bit, C++1z) APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 ADDPATH: C:\cygwin\bin; B2_ADDRESS_MODEL: 32 B2_CXXSTD: 1z B2_TOOLSET: gcc - FLAVOR: cygwin (64-bit, latest, C++11) APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2022 ADDPATH: C:\cygwin64\bin; B2_ADDRESS_MODEL: 64 B2_CXXSTD: 11 B2_TOOLSET: gcc B2_FLAGS: "include=libs/unordered/test/unordered include=libs/unordered/test/exception" B2_VARIANT: release - FLAVOR: cygwin (64-bit, latest, C++14) APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2022 ADDPATH: C:\cygwin64\bin; B2_ADDRESS_MODEL: 64 B2_CXXSTD: 14 B2_TOOLSET: gcc B2_FLAGS: "include=libs/unordered/test/unordered include=libs/unordered/test/exception" B2_VARIANT: release - FLAVOR: cygwin (64-bit, latest, C++1z) APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2022 ADDPATH: C:\cygwin64\bin; B2_ADDRESS_MODEL: 64 B2_CXXSTD: 1z B2_TOOLSET: gcc B2_FLAGS: "include=libs/unordered/test/unordered include=libs/unordered/test/exception" B2_VARIANT: release - FLAVOR: mingw-w64, 32 bit, C++11 APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 ADDPATH: C:\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\bin; B2_CXXSTD: 11 B2_TOOLSET: gcc B2_ADDRESS_MODEL: 32 - FLAVOR: mingw-w64, 32 bit, C++14 APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 ADDPATH: C:\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\bin; B2_CXXSTD: 14 B2_TOOLSET: gcc B2_ADDRESS_MODEL: 32 - FLAVOR: mingw-w64, 32 bit, C++17 APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 ADDPATH: C:\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\bin; B2_CXXSTD: 17 B2_TOOLSET: gcc B2_ADDRESS_MODEL: 32 - FLAVOR: mingw-w64, 32 bit, C++2a APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 ADDPATH: C:\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\bin; B2_CXXSTD: 2a B2_TOOLSET: gcc B2_ADDRESS_MODEL: 32 - FLAVOR: mingw-w64, 64 bit, C++11 APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 ADDPATH: C:\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\bin; B2_CXXSTD: 11 B2_TOOLSET: gcc B2_ADDRESS_MODEL: 64 - FLAVOR: mingw-w64, 64 bit, C++14 APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 ADDPATH: C:\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\bin; B2_CXXSTD: 14 B2_TOOLSET: gcc B2_ADDRESS_MODEL: 64 - FLAVOR: mingw-w64, 64 bit, C++17 APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 ADDPATH: C:\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\bin; B2_CXXSTD: 17 B2_TOOLSET: gcc B2_ADDRESS_MODEL: 64 - FLAVOR: mingw-w64, 64 bit, C++2a APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 ADDPATH: C:\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\bin; B2_CXXSTD: 2a B2_TOOLSET: gcc B2_ADDRESS_MODEL: 64 #- FLAVOR: CodeCov (VS 2019) # APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 # B2_CXXFLAGS: -permissive- # B2_CXXSTD: 14 # B2_TOOLSET: msvc-14.2 # COVERAGE: true install: - git clone --depth 1 https://github.com/boostorg/boost-ci.git C:\boost-ci-cloned # Copy ci folder if not testing Boost.CI - if NOT "%APPVEYOR_PROJECT_NAME%" == "boost-ci" xcopy /s /e /q /i /y C:\boost-ci-cloned\ci .\ci - rmdir /s /q C:\boost-ci-cloned - ci\appveyor\install.bat build: off test_script: ci\build.bat for: # CodeCov coverage build - matrix: only: [COVERAGE: true] test_script: [ps: ci\codecov.ps1]
0
repos
repos/unordered/CMakeLists.txt
# Generated by `boostdep --cmake unordered` # Copyright 2020, 2021 Peter Dimov # Distributed under the Boost Software License, Version 1.0. # https://www.boost.org/LICENSE_1_0.txt cmake_minimum_required(VERSION 3.8...3.20) project(boost_unordered VERSION "${BOOST_SUPERPROJECT_VERSION}" LANGUAGES CXX) add_library(boost_unordered INTERFACE) add_library(Boost::unordered ALIAS boost_unordered) target_include_directories(boost_unordered INTERFACE include) target_link_libraries(boost_unordered INTERFACE Boost::assert Boost::config Boost::container_hash Boost::core Boost::mp11 Boost::predef Boost::throw_exception ) target_compile_features(boost_unordered INTERFACE cxx_std_11) if(BUILD_TESTING AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/test/CMakeLists.txt") add_subdirectory(test) endif()
0
repos
repos/unordered/.codecov.yml
# Copyright 2019 - 2021 Alexander Grund # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at http://boost.org/LICENSE_1_0.txt) # # Sample codecov configuration file. Edit as required codecov: max_report_age: off require_ci_to_pass: yes notify: # Increase this if you have multiple coverage collection jobs after_n_builds: 1 wait_for_ci: yes # Change how pull request comments look comment: layout: "reach,diff,flags,files,footer" # Ignore specific files or folders. Glob patterns are supported. # See https://docs.codecov.com/docs/ignoring-paths ignore: - extra/**/* # - test/**/*
0
repos
repos/unordered/README.md
# Boost.Unordered [![Branch](https://img.shields.io/badge/branch-master-brightgreen.svg)](https://github.com/boostorg/unordered/tree/master) [![CI](https://github.com/boostorg/unordered/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/boostorg/unordered/actions/workflows/ci.yml) [![Drone status](https://img.shields.io/drone/build/boostorg/unordered/master?server=https%3A%2F%2Fdrone.cpp.al&logo=drone&logoColor=%23CCCCCC&label=CI)](https://drone.cpp.al/boostorg/unordered) [![Build status](https://img.shields.io/appveyor/build/cppalliance/unordered/master?logo=appveyor&label=CI)](https://ci.appveyor.com/project/cppalliance/unordered/branch/master) [![codecov](https://codecov.io/gh/boostorg/unordered/branch/master/graph/badge.svg)](https://codecov.io/gh/boostorg/unordered/branch/master) [![Deps](https://img.shields.io/badge/deps-master-brightgreen.svg)](https://pdimov.github.io/boostdep-report/master/unordered.html) [![Documentation](https://img.shields.io/badge/docs-master-brightgreen.svg)](https://www.boost.org/doc/libs/master/libs/unordered/doc/html/unordered.html) [![Enter the Matrix](https://img.shields.io/badge/matrix-master-brightgreen.svg)](http://www.boost.org/development/tests/master/developer/unordered.html)<br/> [![Branch](https://img.shields.io/badge/branch-develop-brightgreen.svg)](https://github.com/boostorg/unordered/tree/develop) [![CI](https://github.com/boostorg/unordered/actions/workflows/ci.yml/badge.svg?branch=develop)](https://github.com/boostorg/unordered/actions/workflows/ci.yml) [![Drone status](https://img.shields.io/drone/build/boostorg/unordered/develop?server=https%3A%2F%2Fdrone.cpp.al&logo=drone&logoColor=%23CCCCCC&label=CI)](https://drone.cpp.al/boostorg/unordered) [![Build status](https://img.shields.io/appveyor/build/cppalliance/unordered/master?logo=appveyor&label=CI)](https://ci.appveyor.com/project/cppalliance/unordered/branch/develop) [![codecov](https://codecov.io/gh/boostorg/unordered/branch/develop/graph/badge.svg)](https://codecov.io/gh/boostorg/unordered/branch/develop) [![Deps](https://img.shields.io/badge/deps-develop-brightgreen.svg)](https://pdimov.github.io/boostdep-report/develop/unordered.html) [![Documentation](https://img.shields.io/badge/docs-develop-brightgreen.svg)](https://www.boost.org/doc/libs/develop/libs/unordered/doc/html/unordered.html) [![Enter the Matrix](https://img.shields.io/badge/matrix-develop-brightgreen.svg)](http://www.boost.org/development/tests/develop/developer/unordered.html)<br/> [![BSL 1.0](https://img.shields.io/badge/license-BSL_1.0-blue.svg)](https://www.boost.org/users/license.html) <img alt="C++11 required" src="https://img.shields.io/badge/standard-C%2b%2b11-blue.svg"> <img alt="Header-only library" src="https://img.shields.io/badge/build-header--only-blue.svg"> Boost.Unordered offers a catalog of hash containers with different standards compliance levels, performances and intented usage scenarios: **`boost::unordered_set` `boost::unordered_map` `boost::unordered_multiset` `boost::unordered_multimap`** <ul>Fully conformant implementations of <code>std::unordered_[multi](set|map)</code>, but faster and up to the latest revisions of the standard even if you're working in an older version of C++ (heterogeneous lookup, <code>try_emplace</code>, <code>contains</code>, etc.)</ul> **`boost::unordered_flat_set` `boost::unordered_flat_map`** <ul>The fastest of the lot. Based on open addressing, these containers slightly deviate from the standard in exchange for top performance.</ul> **`boost::unordered_node_set` `boost::unordered_node_map`** <ul>Variations of <code>boost::unordered_flat_(set|map)</code> providing pointer stability.</ul> **`boost::concurrent_flat_set` `boost::concurrent_flat_map`** <ul>High performance for multithreaded scenarios. Introducing a new non-standard, iterator-free API.</ul> ## Learn about Boost.Unordered * [Online documentation](https://boost.org/libs/unordered) * [Some benchmarks](https://github.com/boostorg/boost_unordered_benchmarks) * Technical articles on Boost.Unordered internal design: * [Advancing the state of the art for `std::unordered_map` implementations](https://bannalia.blogspot.com/2022/06/advancing-state-of-art-for.html) * [Inside `boost::unordered_flat_map`](https://bannalia.blogspot.com/2022/11/inside-boostunorderedflatmap.html) * [Inside `boost::concurrent_flat_map`](https://bannalia.blogspot.com/2023/07/inside-boostconcurrentflatmap.html) * [Bulk visitation in `boost::concurrent_flat_map`](https://bannalia.blogspot.com/2023/10/bulk-visitation-in-boostconcurrentflatm.html) ## Get the library Boost.Unordered can be installed in a number of ways: * [Download Boost](https://www.boost.org/users/download/) and you're ready to go (this is a header-only library requiring no building). * Using Conan 2: In case you don't have it yet, add an entry for Boost in your `conanfile.txt` (the example requires at least Boost 1.83): ``` [requires] boost/[>=1.83.0] ``` <ul>If you're not using any compiled Boost library, the following will skip building altogether:</ul> ``` [options] boost:header_only=True ``` * Using vcpkg: Execute the command ``` vcpkg install boost-unordered ``` * Using CMake: [Boost CMake support infrastructure](https://github.com/boostorg/cmake) allows you to use CMake directly to download, build and consume all of Boost or some specific libraries. ## Support * Join the **#boost-unordered** discussion group at [cpplang.slack.com](https://cpplang.slack.com/) ([ask for an invite](https://cppalliance.org/slack/) if you’re not a member of this workspace yet) * Ask in the [Boost Users mailing list](https://lists.boost.org/mailman/listinfo.cgi/boost-users) (add the `[unordered]` tag at the beginning of the subject line) * [File an issue](https://github.com/boostorg/unordered/issues) ## Contribute * [Pull requests](https://github.com/boostorg/unordered/pulls) against **develop** branch are most welcome. Note that by submitting patches you agree to license your modifications under the [Boost Software License, Version 1.0](http://www.boost.org/LICENSE_1_0.txt).
0
repos
repos/unordered/GitRepoStep.zig
//! Publish Date: 2023_03_19 //! This file is hosted at github.com/marler8997/zig-build-repos and is meant to be copied //! to projects that use it. const std = @import("std"); const GitRepoStep = @This(); pub const ShaCheck = enum { none, warn, err, pub fn reportFail(self: ShaCheck, comptime fmt: []const u8, args: anytype) void { switch (self) { .none => unreachable, .warn => std.log.warn(fmt, args), .err => { std.log.err(fmt, args); std.os.exit(0xff); }, } } }; step: std.Build.Step, url: []const u8, name: []const u8, branch: ?[]const u8 = null, sha: []const u8, path: []const u8, sha_check: ShaCheck = .warn, fetch_enabled: bool, var cached_default_fetch_option: ?bool = null; pub fn defaultFetchOption(b: *std.Build) bool { if (cached_default_fetch_option) |_| {} else { cached_default_fetch_option = if (b.option(bool, "fetch", "automatically fetch network resources")) |o| o else false; } return cached_default_fetch_option.?; } pub fn create(b: *std.Build, opt: struct { url: []const u8, branch: ?[]const u8 = null, sha: []const u8, path: ?[]const u8 = null, sha_check: ShaCheck = .warn, fetch_enabled: ?bool = null, first_ret_addr: ?usize = null, }) *GitRepoStep { const result = b.allocator.create(GitRepoStep) catch @panic("memory"); const name = std.fs.path.basename(opt.url); result.* = GitRepoStep{ .step = std.Build.Step.init(.{ .id = .custom, .name = b.fmt("clone git repository '{s}'", .{name}), .owner = b, .makeFn = make, .first_ret_addr = opt.first_ret_addr orelse @returnAddress(), .max_rss = 0, }), .url = opt.url, .name = name, .branch = opt.branch, .sha = opt.sha, .path = if (opt.path) |p| b.allocator.dupe(u8, p) catch @panic("OOM") else b.pathFromRoot(b.pathJoin(&.{ "dep", name })), .sha_check = opt.sha_check, .fetch_enabled = if (opt.fetch_enabled) |fe| fe else defaultFetchOption(b), }; return result; } // TODO: this should be included in std.build, it helps find bugs in build files fn hasDependency(step: *const std.Build.Step, dep_candidate: *const std.Build.Step) bool { for (step.dependencies.items) |dep| { // TODO: should probably use step.loop_flag to prevent infinite recursion // when a circular reference is encountered, or maybe keep track of // the steps encounterd with a hash set if (dep == dep_candidate or hasDependency(dep, dep_candidate)) return true; } return false; } fn make(step: *std.Build.Step, prog_node: *std.Progress.Node) !void { _ = prog_node; const self = @fieldParentPtr(GitRepoStep, "step", step); std.fs.accessAbsolute(self.path, .{}) catch { const branch_args = if (self.branch) |b| &[2][]const u8{ " -b ", b } else &[2][]const u8{ "", "" }; if (!self.fetch_enabled) { std.debug.print("Error: git repository '{s}' does not exist\n", .{self.path}); std.debug.print(" Use -Dfetch to download it automatically, or run the following to clone it:\n", .{}); std.debug.print(" git clone {s}{s}{s} {s} && git -C {3s} checkout {s} -b fordep\n", .{ self.url, branch_args[0], branch_args[1], self.path, self.sha, }); std.os.exit(1); } { var args = std.ArrayList([]const u8).init(self.step.owner.allocator); defer args.deinit(); try args.append("git"); try args.append("clone"); try args.append(self.url); // TODO: clone it to a temporary location in case of failure // also, remove that temporary location before running try args.append(self.path); if (self.branch) |branch| { try args.append("-b"); try args.append(branch); } try run(self.step.owner, args.items); } try run(self.step.owner, &[_][]const u8{ "git", "-C", self.path, "checkout", self.sha, "-b", "fordep", }); }; try self.checkSha(); } fn checkSha(self: GitRepoStep) !void { if (self.sha_check == .none) return; const result: union(enum) { failed: anyerror, output: []const u8 } = blk: { const result = std.ChildProcess.run(.{ .allocator = self.step.owner.allocator, .argv = &[_][]const u8{ "git", "-C", self.path, "rev-parse", "HEAD", }, .cwd = self.step.owner.build_root.path, .env_map = self.step.owner.env_map, }) catch |e| break :blk .{ .failed = e }; try std.io.getStdErr().writer().writeAll(result.stderr); switch (result.term) { .Exited => |code| { if (code == 0) break :blk .{ .output = result.stdout }; break :blk .{ .failed = error.GitProcessNonZeroExit }; }, .Signal => break :blk .{ .failed = error.GitProcessFailedWithSignal }, .Stopped => break :blk .{ .failed = error.GitProcessWasStopped }, .Unknown => break :blk .{ .failed = error.GitProcessFailed }, } }; switch (result) { .failed => |err| { return self.sha_check.reportFail("failed to retreive sha for repository '{s}': {s}", .{ self.name, @errorName(err) }); }, .output => |output| { if (!std.mem.eql(u8, std.mem.trimRight(u8, output, "\n\r"), self.sha)) { return self.sha_check.reportFail("repository '{s}' sha does not match\nexpected: {s}\nactual : {s}\n", .{ self.name, self.sha, output }); } }, } } fn run(builder: *std.Build, argv: []const []const u8) !void { { var msg = std.ArrayList(u8).init(builder.allocator); defer msg.deinit(); const writer = msg.writer(); var prefix: []const u8 = ""; for (argv) |arg| { try writer.print("{s}\"{s}\"", .{ prefix, arg }); prefix = " "; } std.log.info("[RUN] {s}", .{msg.items}); } var child = std.ChildProcess.init(argv, builder.allocator); child.stdin_behavior = .Ignore; child.stdout_behavior = .Inherit; child.stderr_behavior = .Inherit; child.cwd = builder.build_root.path; child.env_map = builder.env_map; try child.spawn(); const result = try child.wait(); switch (result) { .Exited => |code| if (code != 0) { std.log.err("git clone failed with exit code {}", .{code}); std.os.exit(0xff); }, else => { std.log.err("git clone failed with: {}", .{result}); std.os.exit(0xff); }, } } // Get's the repository path and also verifies that the step requesting the path // is dependent on this step. pub fn getPath(self: *const GitRepoStep, who_wants_to_know: *const std.Build.Step) []const u8 { if (!hasDependency(who_wants_to_know, &self.step)) @panic("a step called GitRepoStep.getPath but has not added it as a dependency"); return self.path; }
0
repos
repos/unordered/build.zig
const std = @import("std"); const GitRepoStep = @import("GitRepoStep.zig"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const tests = b.option(bool, "Tests", "Build tests [default: false]") orelse false; const boost = boostLibraries(b); const lib = b.addStaticLibrary(.{ .name = "unordered", .target = target, .optimize = optimize, }); lib.addIncludePath(.{ .path = "include" }); for (boost.root_module.include_dirs.items) |include| { lib.root_module.include_dirs.append(b.allocator, include) catch {}; } // zig-pkg bypass for header-only lib.addCSourceFile(.{ .file = .{ .path = "test/empty.cc" }, .flags = cxxFlags }); if (lib.rootModuleTarget().abi == .msvc) lib.linkLibC() else lib.linkLibCpp(); lib.installHeadersDirectory("include", ""); lib.step.dependOn(&boost.step); b.installArtifact(lib); if (tests) { buildTest(b, .{ .path = "examples/case_insensitive_test.cpp", .lib = lib, }); buildTest(b, .{ .path = "benchmark/string.cpp", .lib = lib, }); buildTest(b, .{ .path = "benchmark/string_view.cpp", .lib = lib, }); buildTest(b, .{ .path = "benchmark/uuid.cpp", .lib = lib, }); buildTest(b, .{ .path = "benchmark/uint32.cpp", .lib = lib, }); buildTest(b, .{ .path = "benchmark/uint64.cpp", .lib = lib, }); buildTest(b, .{ .path = "benchmark/word_size.cpp", .lib = lib, }); buildTest(b, .{ .path = "benchmark/word_count.cpp", .lib = lib, }); } } const cxxFlags: []const []const u8 = &.{ "-Wall", "-Wextra", "-std=c++20", }; fn buildTest(b: *std.Build, info: BuildInfo) void { const test_exe = b.addExecutable(.{ .name = info.filename(), .optimize = info.lib.root_module.optimize orelse .Debug, .target = info.lib.root_module.resolved_target orelse b.host, }); for (info.lib.root_module.include_dirs.items) |include| { test_exe.root_module.include_dirs.append(b.allocator, include) catch {}; } test_exe.step.dependOn(&info.lib.step); test_exe.addIncludePath(.{ .path = "test" }); test_exe.addIncludePath(.{ .path = "examples" }); test_exe.addCSourceFile(.{ .file = .{ .path = info.path }, .flags = cxxFlags }); // test_exe.linkLibrary(info.lib); if (test_exe.rootModuleTarget().abi == .msvc) test_exe.linkLibC() else test_exe.linkLibCpp(); b.installArtifact(test_exe); const run_cmd = b.addRunArtifact(test_exe); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { run_cmd.addArgs(args); } const run_step = b.step( b.fmt("{s}", .{info.filename()}), b.fmt("Run the {s} test", .{info.filename()}), ); run_step.dependOn(&run_cmd.step); } const BuildInfo = struct { lib: *std.Build.Step.Compile, path: []const u8, fn filename(self: BuildInfo) []const u8 { var split = std.mem.splitSequence(u8, std.fs.path.basename(self.path), "."); return split.first(); } }; fn boostLibraries(b: *std.Build) *std.Build.Step.Compile { const lib = b.addStaticLibrary(.{ .name = "boost", .target = b.host, .optimize = .ReleaseFast, }); const boostCore = GitRepoStep.create(b, .{ .url = "https://github.com/boostorg/core.git", .branch = "develop", .sha = "ba6360e8edcc053c226e924af86996c79494c796", .fetch_enabled = true, }); const boostAlg = GitRepoStep.create(b, .{ .url = "https://github.com/boostorg/algorithm.git", .branch = "develop", .sha = "faac048d59948b1990c0a8772a050d8e47279343", .fetch_enabled = true, }); const boostConfig = GitRepoStep.create(b, .{ .url = "https://github.com/boostorg/config.git", .branch = "develop", .sha = "ccff36321ff514de097a2c27a74235bfe6d9a115", .fetch_enabled = true, }); const boostAssert = GitRepoStep.create(b, .{ .url = "https://github.com/boostorg/assert.git", .branch = "develop", .sha = "5227f10a99442da67415e9649be2b4d9df53b61e", .fetch_enabled = true, }); const boostTraits = GitRepoStep.create(b, .{ .url = "https://github.com/boostorg/type_traits.git", .branch = "develop", .sha = "821c53c0b45529dca508fadc7d018fb1bb6ece21", .fetch_enabled = true, }); const boostMP11 = GitRepoStep.create(b, .{ .url = "https://github.com/boostorg/mp11.git", .branch = "develop", .sha = "ef7608b463298b881bc82eae4f45a4385ed74fca", .fetch_enabled = true, }); const boostRange = GitRepoStep.create(b, .{ .url = "https://github.com/boostorg/range.git", .branch = "develop", .sha = "3920ef2e7ad91354224010ea27f9e0c8116ffe7d", .fetch_enabled = true, }); const boostFunctional = GitRepoStep.create(b, .{ .url = "https://github.com/boostorg/functional.git", .branch = "develop", .sha = "6a573e4b8333ee63ee62ce95558c3667348db233", .fetch_enabled = true, }); const boostPreprocessor = GitRepoStep.create(b, .{ .url = "https://github.com/boostorg/preprocessor.git", .branch = "develop", .sha = "667e87b3392db338a919cbe0213979713aca52e3", .fetch_enabled = true, }); const boostHash = GitRepoStep.create(b, .{ .url = "https://github.com/boostorg/container_hash.git", .branch = "develop", .sha = "48a306dcf236ae460d9ba55648d449ed7bea1dee", .fetch_enabled = true, }); const boostDescribe = GitRepoStep.create(b, .{ .url = "https://github.com/boostorg/describe.git", .branch = "develop", .sha = "c89e4dd3db81eb4f2867b2bc965d161f51cc316c", .fetch_enabled = true, }); const boostMpl = GitRepoStep.create(b, .{ .url = "https://github.com/boostorg/mpl.git", .branch = "develop", .sha = "b440c45c2810acbddc917db057f2e5194da1a199", .fetch_enabled = true, }); const boostIterator = GitRepoStep.create(b, .{ .url = "https://github.com/boostorg/iterator.git", .branch = "develop", .sha = "80bb1ac9e401d0d679718e29bef2f2aaf0123fcb", .fetch_enabled = true, }); const boostStaticAssert = GitRepoStep.create(b, .{ .url = "https://github.com/boostorg/static_assert.git", .branch = "develop", .sha = "45eec41c293bc5cd36ec3ed83671f70bc1aadc9f", .fetch_enabled = true, }); const boostMove = GitRepoStep.create(b, .{ .url = "https://github.com/boostorg/move.git", .branch = "develop", .sha = "60f782350aa7c64e06ac6d2a6914ff6f6ff35ce1", .fetch_enabled = true, }); const boostDetail = GitRepoStep.create(b, .{ .url = "https://github.com/boostorg/detail.git", .branch = "develop", .sha = "845567f026b6e7606b237c92aa8337a1457b672b", .fetch_enabled = true, }); const boostThrow = GitRepoStep.create(b, .{ .url = "https://github.com/boostorg/throw_exception.git", .branch = "develop", .sha = "23dd41e920ecd91237500ac6428f7d392a7a875c", .fetch_enabled = true, }); const boostTuple = GitRepoStep.create(b, .{ .url = "https://github.com/boostorg/tuple.git", .branch = "develop", .sha = "453e061434be75ddd9e4bc578114a4ad9ce0f706", .fetch_enabled = true, }); const boostPredef = GitRepoStep.create(b, .{ .url = "https://github.com/boostorg/predef.git", .branch = "develop", .sha = "614546d6fac1e68cd3511d3289736f31d5aed1eb", .fetch_enabled = true, }); const boostCCheck = GitRepoStep.create(b, .{ .url = "https://github.com/boostorg/concept_check.git", .branch = "develop", .sha = "37c9bddf0bdefaaae0ca5852c1a153d9fc43f278", .fetch_enabled = true, }); const boostUtil = GitRepoStep.create(b, .{ .url = "https://github.com/boostorg/utility.git", .branch = "develop", .sha = "a95a4f6580c65be5861cf4c40dbf9ed64a344ee6", .fetch_enabled = true, }); const boostEndian = GitRepoStep.create(b, .{ .url = "https://github.com/boostorg/endian.git", .branch = "develop", .sha = "56bd7c23aeafe6410b73d2ca69684611eb69eec2", .fetch_enabled = true, }); const boostRegex = GitRepoStep.create(b, .{ .url = "https://github.com/boostorg/regex.git", .branch = "develop", .sha = "237e69caf65906d0313c9b852541b07fa84a99c1", .fetch_enabled = true, }); lib.addCSourceFile(.{ .file = .{ .path = "test/empty.cc" }, .flags = cxxFlags }); lib.addIncludePath(.{ .path = b.pathJoin(&.{ boostCore.path, "include/" }) }); lib.addIncludePath(.{ .path = b.pathJoin(&.{ boostAlg.path, "include/" }) }); lib.addIncludePath(.{ .path = b.pathJoin(&.{ boostConfig.path, "include/" }) }); lib.addIncludePath(.{ .path = b.pathJoin(&.{ boostAssert.path, "include/" }) }); lib.addIncludePath(.{ .path = b.pathJoin(&.{ boostFunctional.path, "include/" }) }); lib.addIncludePath(.{ .path = b.pathJoin(&.{ boostMP11.path, "include/" }) }); lib.addIncludePath(.{ .path = b.pathJoin(&.{ boostTraits.path, "include/" }) }); lib.addIncludePath(.{ .path = b.pathJoin(&.{ boostRange.path, "include/" }) }); lib.addIncludePath(.{ .path = b.pathJoin(&.{ boostPreprocessor.path, "include/" }) }); lib.addIncludePath(.{ .path = b.pathJoin(&.{ boostHash.path, "include/" }) }); lib.addIncludePath(.{ .path = b.pathJoin(&.{ boostDescribe.path, "include/" }) }); lib.addIncludePath(.{ .path = b.pathJoin(&.{ boostMpl.path, "include/" }) }); lib.addIncludePath(.{ .path = b.pathJoin(&.{ boostStaticAssert.path, "include/" }) }); lib.addIncludePath(.{ .path = b.pathJoin(&.{ boostIterator.path, "include/" }) }); lib.addIncludePath(.{ .path = b.pathJoin(&.{ boostMove.path, "include/" }) }); lib.addIncludePath(.{ .path = b.pathJoin(&.{ boostDetail.path, "include/" }) }); lib.addIncludePath(.{ .path = b.pathJoin(&.{ boostThrow.path, "include/" }) }); lib.addIncludePath(.{ .path = b.pathJoin(&.{ boostTuple.path, "include/" }) }); lib.addIncludePath(.{ .path = b.pathJoin(&.{ boostPredef.path, "include/" }) }); lib.addIncludePath(.{ .path = b.pathJoin(&.{ boostCCheck.path, "include/" }) }); lib.addIncludePath(.{ .path = b.pathJoin(&.{ boostUtil.path, "include/" }) }); lib.addIncludePath(.{ .path = b.pathJoin(&.{ boostRegex.path, "include/" }) }); lib.addIncludePath(.{ .path = b.pathJoin(&.{ boostEndian.path, "include/" }) }); lib.step.dependOn(&boostCore.step); boostCore.step.dependOn(&boostTraits.step); boostCore.step.dependOn(&boostAssert.step); boostCore.step.dependOn(&boostMP11.step); boostCore.step.dependOn(&boostAlg.step); boostCore.step.dependOn(&boostConfig.step); boostCore.step.dependOn(&boostFunctional.step); boostCore.step.dependOn(&boostRange.step); boostCore.step.dependOn(&boostPreprocessor.step); boostCore.step.dependOn(&boostHash.step); boostCore.step.dependOn(&boostDescribe.step); boostCore.step.dependOn(&boostMpl.step); boostCore.step.dependOn(&boostIterator.step); boostCore.step.dependOn(&boostStaticAssert.step); boostCore.step.dependOn(&boostMove.step); boostCore.step.dependOn(&boostDetail.step); boostCore.step.dependOn(&boostThrow.step); boostCore.step.dependOn(&boostTuple.step); boostCore.step.dependOn(&boostPredef.step); boostCore.step.dependOn(&boostCCheck.step); boostCore.step.dependOn(&boostUtil.step); boostCore.step.dependOn(&boostRegex.step); boostCore.step.dependOn(&boostEndian.step); return lib; }
0
repos
repos/unordered/index.html
<!-- Copyright 2005-2007 Daniel James. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) --> <html> <head> <meta http-equiv="refresh" content="0; URL=doc/html/unordered.html"> </head> <body> Automatic redirection failed, please go to <a href="doc/html/unordered.html">doc/html/unordered.html</a> </body> </html>
0
repos
repos/unordered/.travis.yml
# Copyright (C) 2016 Daniel James. # Distributed under the Boost Software License, Version 1.0. (See accompanying # file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) # Use Trusty to get a reasonably recent version of Boost. sudo: required dist: trusty language: c++ addons: apt: packages: - libxml2-utils - g++-multilib matrix: include: - compiler: gcc env: | label="gcc C++03/11"; user_config="using gcc : : g++-4.8 --coverage -fsanitize=address ;" enable_coverage=1 CXXSTD=03,11 - compiler: gcc env: | label="gcc 32 bit C++11"; user_config="using gcc : : g++-4.8 -m32 -fsanitize=address ;" CXXSTD=11 - compiler: clang env: | label="clang C++11/17"; user_config="using clang : : clang++ -fsanitize=address ;" CXXSTD=11,17 # sanitized=address not available for 32-bit clang on travis. - compiler: clang env: | label="clang 32 bit"; user_config="using clang : : clang++ -m32 ;" CXXSTD=03 before_install: - if [ -n $enable_coverage ]; then pip install --user cpp-coveralls; fi before_script: - export BOOST_VERSION=1.67.0 - export BOOST_FILENAME=boost_1_67_0 - export BOOST_ROOT=${HOME}/boost - cd ${TRAVIS_BUILD_DIR} - touch Jamroot.jam - cd $HOME - echo $user_config > ~/user-config.jam - cat ~/user-config.jam - | # Pick snapshot to use if [ "$TRAVIS_EVENT_TYPE" == "cron" ] then if [ "$TRAVIS_BRANCH" == "master" ] then snapshot=master else snapshot=develop fi else #snapshot=stable snapshot=master fi # Download and extract snapshot echo "Downloading ${download_url}" mkdir $HOME/download cd $HOME/download python ${TRAVIS_BUILD_DIR}/ci/download-boost-snapshot.py $snapshot mv * ${BOOST_ROOT} - rm -r ${BOOST_ROOT}/boost/unordered - cd ${BOOST_ROOT}/tools/build - mkdir ${HOME}/opt - bash bootstrap.sh - ./b2 install --prefix=$HOME/opt after_success: if [ -n $enable_coverage ]; then coveralls -r ${TRAVIS_BUILD_DIR} -b ${TRAVIS_BUILD_DIR}/test --gcov-options '\-lp' --include include/boost/unordered/ ; fi script: - cd ${TRAVIS_BUILD_DIR}/test - ${HOME}/opt/bin/b2 -j 3 cxxstd=$CXXSTD -q include=${BOOST_ROOT} include=${TRAVIS_BUILD_DIR}/include - xmllint --noout ${TRAVIS_BUILD_DIR}/doc/ref.xml
0
repos/unordered/include
repos/unordered/include/boost/unordered_map.hpp
// Copyright (C) 2003-2004 Jeremy B. Maitin-Shepard. // Copyright (C) 2005-2008 Daniel James. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/unordered for documentation #ifndef BOOST_UNORDERED_MAP_HPP_INCLUDED #define BOOST_UNORDERED_MAP_HPP_INCLUDED #include <boost/config.hpp> #if defined(BOOST_HAS_PRAGMA_ONCE) #pragma once #endif #include <boost/unordered/unordered_map.hpp> #endif // BOOST_UNORDERED_MAP_HPP_INCLUDED
0
repos/unordered/include
repos/unordered/include/boost/unordered_set.hpp
// Copyright (C) 2003-2004 Jeremy B. Maitin-Shepard. // Copyright (C) 2005-2008 Daniel James. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/unordered for documentation #ifndef BOOST_UNORDERED_SET_HPP_INCLUDED #define BOOST_UNORDERED_SET_HPP_INCLUDED #include <boost/config.hpp> #if defined(BOOST_HAS_PRAGMA_ONCE) #pragma once #endif #include <boost/unordered/unordered_set.hpp> #endif // BOOST_UNORDERED_SET_HPP_INCLUDED
0
repos/unordered/include/boost
repos/unordered/include/boost/unordered/concurrent_flat_map.hpp
/* Fast open-addressing concurrent hashmap. * * Copyright 2023 Christian Mazakas. * Copyright 2023 Joaquin M Lopez Munoz. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * * See https://www.boost.org/libs/unordered for library home page. */ #ifndef BOOST_UNORDERED_CONCURRENT_FLAT_MAP_HPP #define BOOST_UNORDERED_CONCURRENT_FLAT_MAP_HPP #include <boost/unordered/concurrent_flat_map_fwd.hpp> #include <boost/unordered/detail/concurrent_static_asserts.hpp> #include <boost/unordered/detail/foa/concurrent_table.hpp> #include <boost/unordered/detail/foa/flat_map_types.hpp> #include <boost/unordered/detail/type_traits.hpp> #include <boost/unordered/unordered_flat_map_fwd.hpp> #include <boost/container_hash/hash.hpp> #include <boost/core/allocator_access.hpp> #include <boost/core/serialization.hpp> #include <type_traits> namespace boost { namespace unordered { template <class Key, class T, class Hash, class Pred, class Allocator> class concurrent_flat_map { private: template <class Key2, class T2, class Hash2, class Pred2, class Allocator2> friend class concurrent_flat_map; template <class Key2, class T2, class Hash2, class Pred2, class Allocator2> friend class unordered_flat_map; using type_policy = detail::foa::flat_map_types<Key, T>; using table_type = detail::foa::concurrent_table<type_policy, Hash, Pred, Allocator>; table_type table_; template <class K, class V, class H, class KE, class A> bool friend operator==(concurrent_flat_map<K, V, H, KE, A> const& lhs, concurrent_flat_map<K, V, H, KE, A> const& rhs); template <class K, class V, class H, class KE, class A, class Predicate> friend typename concurrent_flat_map<K, V, H, KE, A>::size_type erase_if( concurrent_flat_map<K, V, H, KE, A>& set, Predicate pred); template<class Archive, class K, class V, class H, class KE, class A> friend void serialize( Archive& ar, concurrent_flat_map<K, V, H, KE, A>& c, unsigned int version); public: using key_type = Key; using mapped_type = T; using value_type = typename type_policy::value_type; using init_type = typename type_policy::init_type; using size_type = std::size_t; using difference_type = std::ptrdiff_t; using hasher = typename boost::unordered::detail::type_identity<Hash>::type; using key_equal = typename boost::unordered::detail::type_identity<Pred>::type; using allocator_type = typename boost::unordered::detail::type_identity<Allocator>::type; using reference = value_type&; using const_reference = value_type const&; using pointer = typename boost::allocator_pointer<allocator_type>::type; using const_pointer = typename boost::allocator_const_pointer<allocator_type>::type; static constexpr size_type bulk_visit_size = table_type::bulk_visit_size; concurrent_flat_map() : concurrent_flat_map(detail::foa::default_bucket_count) { } explicit concurrent_flat_map(size_type n, const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type()) : table_(n, hf, eql, a) { } template <class InputIterator> concurrent_flat_map(InputIterator f, InputIterator l, size_type n = detail::foa::default_bucket_count, const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type()) : table_(n, hf, eql, a) { this->insert(f, l); } concurrent_flat_map(concurrent_flat_map const& rhs) : table_(rhs.table_, boost::allocator_select_on_container_copy_construction( rhs.get_allocator())) { } concurrent_flat_map(concurrent_flat_map&& rhs) : table_(std::move(rhs.table_)) { } template <class InputIterator> concurrent_flat_map( InputIterator f, InputIterator l, allocator_type const& a) : concurrent_flat_map(f, l, 0, hasher(), key_equal(), a) { } explicit concurrent_flat_map(allocator_type const& a) : table_(detail::foa::default_bucket_count, hasher(), key_equal(), a) { } concurrent_flat_map( concurrent_flat_map const& rhs, allocator_type const& a) : table_(rhs.table_, a) { } concurrent_flat_map(concurrent_flat_map&& rhs, allocator_type const& a) : table_(std::move(rhs.table_), a) { } concurrent_flat_map(std::initializer_list<value_type> il, size_type n = detail::foa::default_bucket_count, const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type()) : concurrent_flat_map(n, hf, eql, a) { this->insert(il.begin(), il.end()); } concurrent_flat_map(size_type n, const allocator_type& a) : concurrent_flat_map(n, hasher(), key_equal(), a) { } concurrent_flat_map( size_type n, const hasher& hf, const allocator_type& a) : concurrent_flat_map(n, hf, key_equal(), a) { } template <typename InputIterator> concurrent_flat_map( InputIterator f, InputIterator l, size_type n, const allocator_type& a) : concurrent_flat_map(f, l, n, hasher(), key_equal(), a) { } template <typename InputIterator> concurrent_flat_map(InputIterator f, InputIterator l, size_type n, const hasher& hf, const allocator_type& a) : concurrent_flat_map(f, l, n, hf, key_equal(), a) { } concurrent_flat_map( std::initializer_list<value_type> il, const allocator_type& a) : concurrent_flat_map( il, detail::foa::default_bucket_count, hasher(), key_equal(), a) { } concurrent_flat_map(std::initializer_list<value_type> il, size_type n, const allocator_type& a) : concurrent_flat_map(il, n, hasher(), key_equal(), a) { } concurrent_flat_map(std::initializer_list<value_type> il, size_type n, const hasher& hf, const allocator_type& a) : concurrent_flat_map(il, n, hf, key_equal(), a) { } concurrent_flat_map( unordered_flat_map<Key, T, Hash, Pred, Allocator>&& other) : table_(std::move(other.table_)) { } ~concurrent_flat_map() = default; concurrent_flat_map& operator=(concurrent_flat_map const& rhs) { table_ = rhs.table_; return *this; } concurrent_flat_map& operator=(concurrent_flat_map&& rhs) noexcept( noexcept(std::declval<table_type&>() = std::declval<table_type&&>())) { table_ = std::move(rhs.table_); return *this; } concurrent_flat_map& operator=(std::initializer_list<value_type> ilist) { table_ = ilist; return *this; } /// Capacity /// size_type size() const noexcept { return table_.size(); } size_type max_size() const noexcept { return table_.max_size(); } BOOST_ATTRIBUTE_NODISCARD bool empty() const noexcept { return size() == 0; } template <class F> BOOST_FORCEINLINE size_type visit(key_type const& k, F f) { BOOST_UNORDERED_STATIC_ASSERT_INVOCABLE(F) return table_.visit(k, f); } template <class F> BOOST_FORCEINLINE size_type visit(key_type const& k, F f) const { BOOST_UNORDERED_STATIC_ASSERT_CONST_INVOCABLE(F) return table_.visit(k, f); } template <class F> BOOST_FORCEINLINE size_type cvisit(key_type const& k, F f) const { BOOST_UNORDERED_STATIC_ASSERT_CONST_INVOCABLE(F) return table_.visit(k, f); } template <class K, class F> BOOST_FORCEINLINE typename std::enable_if< detail::are_transparent<K, hasher, key_equal>::value, size_type>::type visit(K&& k, F f) { BOOST_UNORDERED_STATIC_ASSERT_INVOCABLE(F) return table_.visit(std::forward<K>(k), f); } template <class K, class F> BOOST_FORCEINLINE typename std::enable_if< detail::are_transparent<K, hasher, key_equal>::value, size_type>::type visit(K&& k, F f) const { BOOST_UNORDERED_STATIC_ASSERT_CONST_INVOCABLE(F) return table_.visit(std::forward<K>(k), f); } template <class K, class F> BOOST_FORCEINLINE typename std::enable_if< detail::are_transparent<K, hasher, key_equal>::value, size_type>::type cvisit(K&& k, F f) const { BOOST_UNORDERED_STATIC_ASSERT_CONST_INVOCABLE(F) return table_.visit(std::forward<K>(k), f); } template<class FwdIterator, class F> BOOST_FORCEINLINE size_t visit(FwdIterator first, FwdIterator last, F f) { BOOST_UNORDERED_STATIC_ASSERT_BULK_VISIT_ITERATOR(FwdIterator) BOOST_UNORDERED_STATIC_ASSERT_INVOCABLE(F) return table_.visit(first, last, f); } template<class FwdIterator, class F> BOOST_FORCEINLINE size_t visit(FwdIterator first, FwdIterator last, F f) const { BOOST_UNORDERED_STATIC_ASSERT_BULK_VISIT_ITERATOR(FwdIterator) BOOST_UNORDERED_STATIC_ASSERT_CONST_INVOCABLE(F) return table_.visit(first, last, f); } template<class FwdIterator, class F> BOOST_FORCEINLINE size_t cvisit(FwdIterator first, FwdIterator last, F f) const { BOOST_UNORDERED_STATIC_ASSERT_BULK_VISIT_ITERATOR(FwdIterator) BOOST_UNORDERED_STATIC_ASSERT_CONST_INVOCABLE(F) return table_.visit(first, last, f); } template <class F> size_type visit_all(F f) { BOOST_UNORDERED_STATIC_ASSERT_INVOCABLE(F) return table_.visit_all(f); } template <class F> size_type visit_all(F f) const { BOOST_UNORDERED_STATIC_ASSERT_CONST_INVOCABLE(F) return table_.visit_all(f); } template <class F> size_type cvisit_all(F f) const { BOOST_UNORDERED_STATIC_ASSERT_CONST_INVOCABLE(F) return table_.cvisit_all(f); } #if defined(BOOST_UNORDERED_PARALLEL_ALGORITHMS) template <class ExecPolicy, class F> typename std::enable_if<detail::is_execution_policy<ExecPolicy>::value, void>::type visit_all(ExecPolicy&& p, F f) { BOOST_UNORDERED_STATIC_ASSERT_INVOCABLE(F) BOOST_UNORDERED_STATIC_ASSERT_EXEC_POLICY(ExecPolicy) table_.visit_all(p, f); } template <class ExecPolicy, class F> typename std::enable_if<detail::is_execution_policy<ExecPolicy>::value, void>::type visit_all(ExecPolicy&& p, F f) const { BOOST_UNORDERED_STATIC_ASSERT_CONST_INVOCABLE(F) BOOST_UNORDERED_STATIC_ASSERT_EXEC_POLICY(ExecPolicy) table_.visit_all(p, f); } template <class ExecPolicy, class F> typename std::enable_if<detail::is_execution_policy<ExecPolicy>::value, void>::type cvisit_all(ExecPolicy&& p, F f) const { BOOST_UNORDERED_STATIC_ASSERT_CONST_INVOCABLE(F) BOOST_UNORDERED_STATIC_ASSERT_EXEC_POLICY(ExecPolicy) table_.cvisit_all(p, f); } #endif template <class F> bool visit_while(F f) { BOOST_UNORDERED_STATIC_ASSERT_INVOCABLE(F) return table_.visit_while(f); } template <class F> bool visit_while(F f) const { BOOST_UNORDERED_STATIC_ASSERT_CONST_INVOCABLE(F) return table_.visit_while(f); } template <class F> bool cvisit_while(F f) const { BOOST_UNORDERED_STATIC_ASSERT_CONST_INVOCABLE(F) return table_.cvisit_while(f); } #if defined(BOOST_UNORDERED_PARALLEL_ALGORITHMS) template <class ExecPolicy, class F> typename std::enable_if<detail::is_execution_policy<ExecPolicy>::value, bool>::type visit_while(ExecPolicy&& p, F f) { BOOST_UNORDERED_STATIC_ASSERT_INVOCABLE(F) BOOST_UNORDERED_STATIC_ASSERT_EXEC_POLICY(ExecPolicy) return table_.visit_while(p, f); } template <class ExecPolicy, class F> typename std::enable_if<detail::is_execution_policy<ExecPolicy>::value, bool>::type visit_while(ExecPolicy&& p, F f) const { BOOST_UNORDERED_STATIC_ASSERT_CONST_INVOCABLE(F) BOOST_UNORDERED_STATIC_ASSERT_EXEC_POLICY(ExecPolicy) return table_.visit_while(p, f); } template <class ExecPolicy, class F> typename std::enable_if<detail::is_execution_policy<ExecPolicy>::value, bool>::type cvisit_while(ExecPolicy&& p, F f) const { BOOST_UNORDERED_STATIC_ASSERT_CONST_INVOCABLE(F) BOOST_UNORDERED_STATIC_ASSERT_EXEC_POLICY(ExecPolicy) return table_.cvisit_while(p, f); } #endif /// Modifiers /// template <class Ty> BOOST_FORCEINLINE auto insert(Ty&& value) -> decltype(table_.insert(std::forward<Ty>(value))) { return table_.insert(std::forward<Ty>(value)); } BOOST_FORCEINLINE bool insert(init_type&& obj) { return table_.insert(std::move(obj)); } template <class InputIterator> void insert(InputIterator begin, InputIterator end) { for (auto pos = begin; pos != end; ++pos) { table_.emplace(*pos); } } void insert(std::initializer_list<value_type> ilist) { this->insert(ilist.begin(), ilist.end()); } template <class M> BOOST_FORCEINLINE bool insert_or_assign(key_type const& k, M&& obj) { return table_.try_emplace_or_visit(k, std::forward<M>(obj), [&](value_type& m) { m.second = std::forward<M>(obj); }); } template <class M> BOOST_FORCEINLINE bool insert_or_assign(key_type&& k, M&& obj) { return table_.try_emplace_or_visit(std::move(k), std::forward<M>(obj), [&](value_type& m) { m.second = std::forward<M>(obj); }); } template <class K, class M> BOOST_FORCEINLINE typename std::enable_if< detail::are_transparent<K, hasher, key_equal>::value, bool>::type insert_or_assign(K&& k, M&& obj) { return table_.try_emplace_or_visit(std::forward<K>(k), std::forward<M>(obj), [&](value_type& m) { m.second = std::forward<M>(obj); }); } template <class Ty, class F> BOOST_FORCEINLINE auto insert_or_visit(Ty&& value, F f) -> decltype(table_.insert_or_visit(std::forward<Ty>(value), f)) { BOOST_UNORDERED_STATIC_ASSERT_INVOCABLE(F) return table_.insert_or_visit(std::forward<Ty>(value), f); } template <class F> BOOST_FORCEINLINE bool insert_or_visit(init_type&& obj, F f) { BOOST_UNORDERED_STATIC_ASSERT_INVOCABLE(F) return table_.insert_or_visit(std::move(obj), f); } template <class InputIterator, class F> void insert_or_visit(InputIterator first, InputIterator last, F f) { BOOST_UNORDERED_STATIC_ASSERT_INVOCABLE(F) for (; first != last; ++first) { table_.emplace_or_visit(*first, f); } } template <class F> void insert_or_visit(std::initializer_list<value_type> ilist, F f) { BOOST_UNORDERED_STATIC_ASSERT_INVOCABLE(F) this->insert_or_visit(ilist.begin(), ilist.end(), f); } template <class Ty, class F> BOOST_FORCEINLINE auto insert_or_cvisit(Ty&& value, F f) -> decltype(table_.insert_or_cvisit(std::forward<Ty>(value), f)) { BOOST_UNORDERED_STATIC_ASSERT_CONST_INVOCABLE(F) return table_.insert_or_cvisit(std::forward<Ty>(value), f); } template <class F> BOOST_FORCEINLINE bool insert_or_cvisit(init_type&& obj, F f) { BOOST_UNORDERED_STATIC_ASSERT_CONST_INVOCABLE(F) return table_.insert_or_cvisit(std::move(obj), f); } template <class InputIterator, class F> void insert_or_cvisit(InputIterator first, InputIterator last, F f) { BOOST_UNORDERED_STATIC_ASSERT_CONST_INVOCABLE(F) for (; first != last; ++first) { table_.emplace_or_cvisit(*first, f); } } template <class F> void insert_or_cvisit(std::initializer_list<value_type> ilist, F f) { BOOST_UNORDERED_STATIC_ASSERT_CONST_INVOCABLE(F) this->insert_or_cvisit(ilist.begin(), ilist.end(), f); } template <class... Args> BOOST_FORCEINLINE bool emplace(Args&&... args) { return table_.emplace(std::forward<Args>(args)...); } template <class Arg, class... Args> BOOST_FORCEINLINE bool emplace_or_visit(Arg&& arg, Args&&... args) { BOOST_UNORDERED_STATIC_ASSERT_LAST_ARG_INVOCABLE(Arg, Args...) return table_.emplace_or_visit( std::forward<Arg>(arg), std::forward<Args>(args)...); } template <class Arg, class... Args> BOOST_FORCEINLINE bool emplace_or_cvisit(Arg&& arg, Args&&... args) { BOOST_UNORDERED_STATIC_ASSERT_LAST_ARG_CONST_INVOCABLE(Arg, Args...) return table_.emplace_or_cvisit( std::forward<Arg>(arg), std::forward<Args>(args)...); } template <class... Args> BOOST_FORCEINLINE bool try_emplace(key_type const& k, Args&&... args) { return table_.try_emplace(k, std::forward<Args>(args)...); } template <class... Args> BOOST_FORCEINLINE bool try_emplace(key_type&& k, Args&&... args) { return table_.try_emplace(std::move(k), std::forward<Args>(args)...); } template <class K, class... Args> BOOST_FORCEINLINE typename std::enable_if< detail::are_transparent<K, hasher, key_equal>::value, bool>::type try_emplace(K&& k, Args&&... args) { return table_.try_emplace( std::forward<K>(k), std::forward<Args>(args)...); } template <class Arg, class... Args> BOOST_FORCEINLINE bool try_emplace_or_visit( key_type const& k, Arg&& arg, Args&&... args) { BOOST_UNORDERED_STATIC_ASSERT_LAST_ARG_INVOCABLE(Arg, Args...) return table_.try_emplace_or_visit( k, std::forward<Arg>(arg), std::forward<Args>(args)...); } template <class Arg, class... Args> BOOST_FORCEINLINE bool try_emplace_or_cvisit( key_type const& k, Arg&& arg, Args&&... args) { BOOST_UNORDERED_STATIC_ASSERT_LAST_ARG_CONST_INVOCABLE(Arg, Args...) return table_.try_emplace_or_cvisit( k, std::forward<Arg>(arg), std::forward<Args>(args)...); } template <class Arg, class... Args> BOOST_FORCEINLINE bool try_emplace_or_visit( key_type&& k, Arg&& arg, Args&&... args) { BOOST_UNORDERED_STATIC_ASSERT_LAST_ARG_INVOCABLE(Arg, Args...) return table_.try_emplace_or_visit( std::move(k), std::forward<Arg>(arg), std::forward<Args>(args)...); } template <class Arg, class... Args> BOOST_FORCEINLINE bool try_emplace_or_cvisit( key_type&& k, Arg&& arg, Args&&... args) { BOOST_UNORDERED_STATIC_ASSERT_LAST_ARG_CONST_INVOCABLE(Arg, Args...) return table_.try_emplace_or_cvisit( std::move(k), std::forward<Arg>(arg), std::forward<Args>(args)...); } template <class K, class Arg, class... Args> BOOST_FORCEINLINE bool try_emplace_or_visit( K&& k, Arg&& arg, Args&&... args) { BOOST_UNORDERED_STATIC_ASSERT_LAST_ARG_INVOCABLE(Arg, Args...) return table_.try_emplace_or_visit(std::forward<K>(k), std::forward<Arg>(arg), std::forward<Args>(args)...); } template <class K, class Arg, class... Args> BOOST_FORCEINLINE bool try_emplace_or_cvisit( K&& k, Arg&& arg, Args&&... args) { BOOST_UNORDERED_STATIC_ASSERT_LAST_ARG_CONST_INVOCABLE(Arg, Args...) return table_.try_emplace_or_cvisit(std::forward<K>(k), std::forward<Arg>(arg), std::forward<Args>(args)...); } BOOST_FORCEINLINE size_type erase(key_type const& k) { return table_.erase(k); } template <class K> BOOST_FORCEINLINE typename std::enable_if< detail::are_transparent<K, hasher, key_equal>::value, size_type>::type erase(K&& k) { return table_.erase(std::forward<K>(k)); } template <class F> BOOST_FORCEINLINE size_type erase_if(key_type const& k, F f) { return table_.erase_if(k, f); } template <class K, class F> BOOST_FORCEINLINE typename std::enable_if< detail::are_transparent<K, hasher, key_equal>::value && !detail::is_execution_policy<K>::value, size_type>::type erase_if(K&& k, F f) { return table_.erase_if(std::forward<K>(k), f); } #if defined(BOOST_UNORDERED_PARALLEL_ALGORITHMS) template <class ExecPolicy, class F> typename std::enable_if<detail::is_execution_policy<ExecPolicy>::value, void>::type erase_if(ExecPolicy&& p, F f) { BOOST_UNORDERED_STATIC_ASSERT_EXEC_POLICY(ExecPolicy) table_.erase_if(p, f); } #endif template <class F> size_type erase_if(F f) { return table_.erase_if(f); } void swap(concurrent_flat_map& other) noexcept( boost::allocator_is_always_equal<Allocator>::type::value || boost::allocator_propagate_on_container_swap<Allocator>::type::value) { return table_.swap(other.table_); } void clear() noexcept { table_.clear(); } template <typename H2, typename P2> size_type merge(concurrent_flat_map<Key, T, H2, P2, Allocator>& x) { BOOST_ASSERT(get_allocator() == x.get_allocator()); return table_.merge(x.table_); } template <typename H2, typename P2> size_type merge(concurrent_flat_map<Key, T, H2, P2, Allocator>&& x) { return merge(x); } BOOST_FORCEINLINE size_type count(key_type const& k) const { return table_.count(k); } template <class K> BOOST_FORCEINLINE typename std::enable_if< detail::are_transparent<K, hasher, key_equal>::value, size_type>::type count(K const& k) { return table_.count(k); } BOOST_FORCEINLINE bool contains(key_type const& k) const { return table_.contains(k); } template <class K> BOOST_FORCEINLINE typename std::enable_if< detail::are_transparent<K, hasher, key_equal>::value, bool>::type contains(K const& k) const { return table_.contains(k); } /// Hash Policy /// size_type bucket_count() const noexcept { return table_.capacity(); } float load_factor() const noexcept { return table_.load_factor(); } float max_load_factor() const noexcept { return table_.max_load_factor(); } void max_load_factor(float) {} size_type max_load() const noexcept { return table_.max_load(); } void rehash(size_type n) { table_.rehash(n); } void reserve(size_type n) { table_.reserve(n); } /// Observers /// allocator_type get_allocator() const noexcept { return table_.get_allocator(); } hasher hash_function() const { return table_.hash_function(); } key_equal key_eq() const { return table_.key_eq(); } }; template <class Key, class T, class Hash, class KeyEqual, class Allocator> bool operator==( concurrent_flat_map<Key, T, Hash, KeyEqual, Allocator> const& lhs, concurrent_flat_map<Key, T, Hash, KeyEqual, Allocator> const& rhs) { return lhs.table_ == rhs.table_; } template <class Key, class T, class Hash, class KeyEqual, class Allocator> bool operator!=( concurrent_flat_map<Key, T, Hash, KeyEqual, Allocator> const& lhs, concurrent_flat_map<Key, T, Hash, KeyEqual, Allocator> const& rhs) { return !(lhs == rhs); } template <class Key, class T, class Hash, class Pred, class Alloc> void swap(concurrent_flat_map<Key, T, Hash, Pred, Alloc>& x, concurrent_flat_map<Key, T, Hash, Pred, Alloc>& y) noexcept(noexcept(x.swap(y))) { x.swap(y); } template <class K, class T, class H, class P, class A, class Predicate> typename concurrent_flat_map<K, T, H, P, A>::size_type erase_if( concurrent_flat_map<K, T, H, P, A>& c, Predicate pred) { return c.table_.erase_if(pred); } template<class Archive, class K, class V, class H, class KE, class A> void serialize( Archive& ar, concurrent_flat_map<K, V, H, KE, A>& c, unsigned int) { ar & core::make_nvp("table",c.table_); } #if BOOST_UNORDERED_TEMPLATE_DEDUCTION_GUIDES template <class InputIterator, class Hash = boost::hash<boost::unordered::detail::iter_key_t<InputIterator> >, class Pred = std::equal_to<boost::unordered::detail::iter_key_t<InputIterator> >, class Allocator = std::allocator< boost::unordered::detail::iter_to_alloc_t<InputIterator> >, class = std::enable_if_t<detail::is_input_iterator_v<InputIterator> >, class = std::enable_if_t<detail::is_hash_v<Hash> >, class = std::enable_if_t<detail::is_pred_v<Pred> >, class = std::enable_if_t<detail::is_allocator_v<Allocator> > > concurrent_flat_map(InputIterator, InputIterator, std::size_t = boost::unordered::detail::foa::default_bucket_count, Hash = Hash(), Pred = Pred(), Allocator = Allocator()) -> concurrent_flat_map< boost::unordered::detail::iter_key_t<InputIterator>, boost::unordered::detail::iter_val_t<InputIterator>, Hash, Pred, Allocator>; template <class Key, class T, class Hash = boost::hash<std::remove_const_t<Key> >, class Pred = std::equal_to<std::remove_const_t<Key> >, class Allocator = std::allocator<std::pair<const Key, T> >, class = std::enable_if_t<detail::is_hash_v<Hash> >, class = std::enable_if_t<detail::is_pred_v<Pred> >, class = std::enable_if_t<detail::is_allocator_v<Allocator> > > concurrent_flat_map(std::initializer_list<std::pair<Key, T> >, std::size_t = boost::unordered::detail::foa::default_bucket_count, Hash = Hash(), Pred = Pred(), Allocator = Allocator()) -> concurrent_flat_map<std::remove_const_t<Key>, T, Hash, Pred, Allocator>; template <class InputIterator, class Allocator, class = std::enable_if_t<detail::is_input_iterator_v<InputIterator> >, class = std::enable_if_t<detail::is_allocator_v<Allocator> > > concurrent_flat_map(InputIterator, InputIterator, std::size_t, Allocator) -> concurrent_flat_map< boost::unordered::detail::iter_key_t<InputIterator>, boost::unordered::detail::iter_val_t<InputIterator>, boost::hash<boost::unordered::detail::iter_key_t<InputIterator> >, std::equal_to<boost::unordered::detail::iter_key_t<InputIterator> >, Allocator>; template <class InputIterator, class Allocator, class = std::enable_if_t<detail::is_input_iterator_v<InputIterator> >, class = std::enable_if_t<detail::is_allocator_v<Allocator> > > concurrent_flat_map(InputIterator, InputIterator, Allocator) -> concurrent_flat_map< boost::unordered::detail::iter_key_t<InputIterator>, boost::unordered::detail::iter_val_t<InputIterator>, boost::hash<boost::unordered::detail::iter_key_t<InputIterator> >, std::equal_to<boost::unordered::detail::iter_key_t<InputIterator> >, Allocator>; template <class InputIterator, class Hash, class Allocator, class = std::enable_if_t<detail::is_hash_v<Hash> >, class = std::enable_if_t<detail::is_input_iterator_v<InputIterator> >, class = std::enable_if_t<detail::is_allocator_v<Allocator> > > concurrent_flat_map( InputIterator, InputIterator, std::size_t, Hash, Allocator) -> concurrent_flat_map< boost::unordered::detail::iter_key_t<InputIterator>, boost::unordered::detail::iter_val_t<InputIterator>, Hash, std::equal_to<boost::unordered::detail::iter_key_t<InputIterator> >, Allocator>; template <class Key, class T, class Allocator, class = std::enable_if_t<detail::is_allocator_v<Allocator> > > concurrent_flat_map(std::initializer_list<std::pair<Key, T> >, std::size_t, Allocator) -> concurrent_flat_map<std::remove_const_t<Key>, T, boost::hash<std::remove_const_t<Key> >, std::equal_to<std::remove_const_t<Key> >, Allocator>; template <class Key, class T, class Allocator, class = std::enable_if_t<detail::is_allocator_v<Allocator> > > concurrent_flat_map(std::initializer_list<std::pair<Key, T> >, Allocator) -> concurrent_flat_map<std::remove_const_t<Key>, T, boost::hash<std::remove_const_t<Key> >, std::equal_to<std::remove_const_t<Key> >, Allocator>; template <class Key, class T, class Hash, class Allocator, class = std::enable_if_t<detail::is_hash_v<Hash> >, class = std::enable_if_t<detail::is_allocator_v<Allocator> > > concurrent_flat_map(std::initializer_list<std::pair<Key, T> >, std::size_t, Hash, Allocator) -> concurrent_flat_map<std::remove_const_t<Key>, T, Hash, std::equal_to<std::remove_const_t<Key> >, Allocator>; #endif } // namespace unordered } // namespace boost #endif // BOOST_UNORDERED_CONCURRENT_FLAT_MAP_HPP
0
repos/unordered/include/boost
repos/unordered/include/boost/unordered/hash_traits.hpp
/* Hash function characterization. * * Copyright 2022 Joaquin M Lopez Munoz. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * * See https://www.boost.org/libs/unordered for library home page. */ #ifndef BOOST_UNORDERED_HASH_TRAITS_HPP #define BOOST_UNORDERED_HASH_TRAITS_HPP #include <boost/unordered/detail/type_traits.hpp> namespace boost{ namespace unordered{ namespace detail{ template<typename Hash,typename=void> struct hash_is_avalanching_impl: std::false_type{}; template<typename Hash> struct hash_is_avalanching_impl<Hash, boost::unordered::detail::void_t<typename Hash::is_avalanching> >: std::true_type{}; } /* namespace detail */ /* Each trait can be partially specialized by users for concrete hash functions * when actual characterization differs from default. */ /* hash_is_avalanching<Hash>::value is true when the type Hash::is_avalanching * is present, false otherwise. */ template<typename Hash> struct hash_is_avalanching: detail::hash_is_avalanching_impl<Hash>::type{}; } /* namespace unordered */ } /* namespace boost */ #endif
0
repos/unordered/include/boost
repos/unordered/include/boost/unordered/unordered_set_fwd.hpp
// Copyright (C) 2008-2011 Daniel James. // Copyright (C) 2022 Christian Mazakas // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_UNORDERED_SET_FWD_HPP_INCLUDED #define BOOST_UNORDERED_SET_FWD_HPP_INCLUDED #include <boost/config.hpp> #if defined(BOOST_HAS_PRAGMA_ONCE) #pragma once #endif #include <boost/container_hash/hash_fwd.hpp> #include <functional> #include <memory> namespace boost { namespace unordered { template <class T, class H = boost::hash<T>, class P = std::equal_to<T>, class A = std::allocator<T> > class unordered_set; template <class T, class H, class P, class A> inline bool operator==( unordered_set<T, H, P, A> const&, unordered_set<T, H, P, A> const&); template <class T, class H, class P, class A> inline bool operator!=( unordered_set<T, H, P, A> const&, unordered_set<T, H, P, A> const&); template <class T, class H, class P, class A> inline void swap(unordered_set<T, H, P, A>& m1, unordered_set<T, H, P, A>& m2) noexcept(noexcept(m1.swap(m2))); template <class K, class H, class P, class A, class Predicate> typename unordered_set<K, H, P, A>::size_type erase_if( unordered_set<K, H, P, A>& c, Predicate pred); template <class T, class H = boost::hash<T>, class P = std::equal_to<T>, class A = std::allocator<T> > class unordered_multiset; template <class T, class H, class P, class A> inline bool operator==(unordered_multiset<T, H, P, A> const&, unordered_multiset<T, H, P, A> const&); template <class T, class H, class P, class A> inline bool operator!=(unordered_multiset<T, H, P, A> const&, unordered_multiset<T, H, P, A> const&); template <class T, class H, class P, class A> inline void swap(unordered_multiset<T, H, P, A>& m1, unordered_multiset<T, H, P, A>& m2) noexcept(noexcept(m1.swap(m2))); template <class K, class H, class P, class A, class Predicate> typename unordered_multiset<K, H, P, A>::size_type erase_if( unordered_multiset<K, H, P, A>& c, Predicate pred); template <class N, class T, class A> class node_handle_set; template <class Iter, class NodeType> struct insert_return_type_set; } // namespace unordered using boost::unordered::unordered_multiset; using boost::unordered::unordered_set; } // namespace boost #endif
0
repos/unordered/include/boost
repos/unordered/include/boost/unordered/unordered_map.hpp
// Copyright (C) 2003-2004 Jeremy B. Maitin-Shepard. // Copyright (C) 2005-2011 Daniel James. // Copyright (C) 2022-2023 Christian Mazakas // Copyright (C) 2024 Joaquin M Lopez Munoz. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/unordered for documentation #ifndef BOOST_UNORDERED_UNORDERED_MAP_HPP_INCLUDED #define BOOST_UNORDERED_UNORDERED_MAP_HPP_INCLUDED #include <boost/config.hpp> #if defined(BOOST_HAS_PRAGMA_ONCE) #pragma once #endif #include <boost/unordered/detail/map.hpp> #include <boost/unordered/detail/serialize_fca_container.hpp> #include <boost/unordered/detail/throw_exception.hpp> #include <boost/unordered/detail/type_traits.hpp> #include <boost/container_hash/hash.hpp> #include <initializer_list> #if defined(BOOST_MSVC) #pragma warning(push) // conditional expression is constant #pragma warning(disable : 4127) #if BOOST_MSVC >= 1400 // the inline specifier cannot be used when a friend declaration refers to a // specialization of a function template #pragma warning(disable : 4396) #endif #endif namespace boost { namespace unordered { template <class K, class T, class H, class P, class A> class unordered_map { template <typename, typename, typename, typename, typename> friend class unordered_multimap; public: typedef K key_type; typedef T mapped_type; typedef std::pair<const K, T> value_type; typedef typename boost::unordered::detail::type_identity<H>::type hasher; typedef typename boost::unordered::detail::type_identity<P>::type key_equal; typedef typename boost::unordered::detail::type_identity<A>::type allocator_type; private: typedef boost::unordered::detail::map<A, K, T, H, P> types; typedef typename types::value_allocator_traits value_allocator_traits; typedef typename types::table table; public: typedef typename value_allocator_traits::pointer pointer; typedef typename value_allocator_traits::const_pointer const_pointer; typedef value_type& reference; typedef value_type const& const_reference; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; typedef typename table::iterator iterator; typedef typename table::c_iterator const_iterator; typedef typename table::l_iterator local_iterator; typedef typename table::cl_iterator const_local_iterator; typedef typename types::node_type node_type; typedef typename types::insert_return_type insert_return_type; private: table table_; public: // constructors unordered_map(); explicit unordered_map(size_type, const hasher& = hasher(), const key_equal& = key_equal(), const allocator_type& = allocator_type()); template <class InputIt> unordered_map(InputIt, InputIt, size_type = boost::unordered::detail::default_bucket_count, const hasher& = hasher(), const key_equal& = key_equal(), const allocator_type& = allocator_type()); unordered_map(unordered_map const&); unordered_map(unordered_map&& other) noexcept(table::nothrow_move_constructible) : table_(other.table_, boost::unordered::detail::move_tag()) { // The move is done in table_ } explicit unordered_map(allocator_type const&); unordered_map(unordered_map const&, allocator_type const&); unordered_map(unordered_map&&, allocator_type const&); unordered_map(std::initializer_list<value_type>, size_type = boost::unordered::detail::default_bucket_count, const hasher& = hasher(), const key_equal& l = key_equal(), const allocator_type& = allocator_type()); explicit unordered_map(size_type, const allocator_type&); explicit unordered_map(size_type, const hasher&, const allocator_type&); template <class InputIterator> unordered_map(InputIterator, InputIterator, const allocator_type&); template <class InputIt> unordered_map(InputIt, InputIt, size_type, const allocator_type&); template <class InputIt> unordered_map( InputIt, InputIt, size_type, const hasher&, const allocator_type&); unordered_map(std::initializer_list<value_type>, const allocator_type&); unordered_map( std::initializer_list<value_type>, size_type, const allocator_type&); unordered_map(std::initializer_list<value_type>, size_type, const hasher&, const allocator_type&); // Destructor ~unordered_map() noexcept; // Assign unordered_map& operator=(unordered_map const& x) { table_.assign(x.table_, std::true_type()); return *this; } unordered_map& operator=(unordered_map&& x) noexcept(value_allocator_traits::is_always_equal::value&& std::is_nothrow_move_assignable<H>::value&& std::is_nothrow_move_assignable<P>::value) { table_.move_assign(x.table_, std::true_type()); return *this; } unordered_map& operator=(std::initializer_list<value_type>); allocator_type get_allocator() const noexcept { return allocator_type(table_.node_alloc()); } // // iterators iterator begin() noexcept { return table_.begin(); } const_iterator begin() const noexcept { return const_iterator(table_.begin()); } iterator end() noexcept { return iterator(); } const_iterator end() const noexcept { return const_iterator(); } const_iterator cbegin() const noexcept { return const_iterator(table_.begin()); } const_iterator cend() const noexcept { return const_iterator(); } // size and capacity BOOST_ATTRIBUTE_NODISCARD bool empty() const noexcept { return table_.size_ == 0; } size_type size() const noexcept { return table_.size_; } size_type max_size() const noexcept; // emplace template <class... Args> std::pair<iterator, bool> emplace(Args&&... args) { return table_.emplace_unique( table::extractor::extract(std::forward<Args>(args)...), std::forward<Args>(args)...); } template <class... Args> iterator emplace_hint(const_iterator hint, Args&&... args) { return table_.emplace_hint_unique(hint, table::extractor::extract(std::forward<Args>(args)...), std::forward<Args>(args)...); } std::pair<iterator, bool> insert(value_type const& x) { return this->emplace(x); } std::pair<iterator, bool> insert(value_type&& x) { return this->emplace(std::move(x)); } template <class P2> typename boost::enable_if<std::is_constructible<value_type, P2&&>, std::pair<iterator, bool> >::type insert(P2&& obj) { return this->emplace(std::forward<P2>(obj)); } iterator insert(const_iterator hint, value_type const& x) { return this->emplace_hint(hint, x); } iterator insert(const_iterator hint, value_type&& x) { return this->emplace_hint(hint, std::move(x)); } template <class P2> typename boost::enable_if<std::is_constructible<value_type, P2&&>, iterator>::type insert(const_iterator hint, P2&& obj) { return this->emplace_hint(hint, std::forward<P2>(obj)); } template <class InputIt> void insert(InputIt, InputIt); void insert(std::initializer_list<value_type>); // extract node_type extract(const_iterator position) { return node_type( table_.extract_by_iterator_unique(position), allocator_type(table_.node_alloc())); } node_type extract(const key_type& k) { return node_type( table_.extract_by_key_impl(k), allocator_type(table_.node_alloc())); } template <class Key> typename boost::enable_if_c< detail::transparent_non_iterable<Key, unordered_map>::value, node_type>::type extract(Key&& k) { return node_type( table_.extract_by_key_impl(std::forward<Key>(k)), allocator_type(table_.node_alloc())); } insert_return_type insert(node_type&& np) { insert_return_type result; table_.move_insert_node_type_unique((node_type&)np, result); return result; } iterator insert(const_iterator hint, node_type&& np) { return table_.move_insert_node_type_with_hint_unique(hint, np); } template <class... Args> std::pair<iterator, bool> try_emplace(key_type const& k, Args&&... args) { return table_.try_emplace_unique(k, std::forward<Args>(args)...); } template <class... Args> std::pair<iterator, bool> try_emplace(key_type&& k, Args&&... args) { return table_.try_emplace_unique( std::move(k), std::forward<Args>(args)...); } template <class Key, class... Args> typename boost::enable_if_c< detail::transparent_non_iterable<Key, unordered_map>::value, std::pair<iterator, bool> >::type try_emplace(Key&& k, Args&&... args) { return table_.try_emplace_unique( std::forward<Key>(k), std::forward<Args>(args)...); } template <class... Args> iterator try_emplace( const_iterator hint, key_type const& k, Args&&... args) { return table_.try_emplace_hint_unique( hint, k, std::forward<Args>(args)...); } template <class... Args> iterator try_emplace(const_iterator hint, key_type&& k, Args&&... args) { return table_.try_emplace_hint_unique( hint, std::move(k), std::forward<Args>(args)...); } template <class Key, class... Args> typename boost::enable_if_c< detail::transparent_non_iterable<Key, unordered_map>::value, iterator>::type try_emplace(const_iterator hint, Key&& k, Args&&... args) { return table_.try_emplace_hint_unique( hint, std::forward<Key>(k), std::forward<Args>(args)...); } template <class M> std::pair<iterator, bool> insert_or_assign(key_type const& k, M&& obj) { return table_.insert_or_assign_unique(k, std::forward<M>(obj)); } template <class M> std::pair<iterator, bool> insert_or_assign(key_type&& k, M&& obj) { return table_.insert_or_assign_unique( std::move(k), std::forward<M>(obj)); } template <class Key, class M> typename boost::enable_if_c<detail::are_transparent<Key, H, P>::value, std::pair<iterator, bool> >::type insert_or_assign(Key&& k, M&& obj) { return table_.insert_or_assign_unique( std::forward<Key>(k), std::forward<M>(obj)); } template <class M> iterator insert_or_assign(const_iterator, key_type const& k, M&& obj) { return table_.insert_or_assign_unique(k, std::forward<M>(obj)).first; } template <class M> iterator insert_or_assign(const_iterator, key_type&& k, M&& obj) { return table_ .insert_or_assign_unique(std::move(k), std::forward<M>(obj)) .first; } template <class Key, class M> typename boost::enable_if_c<detail::are_transparent<Key, H, P>::value, iterator>::type insert_or_assign(const_iterator, Key&& k, M&& obj) { return table_ .insert_or_assign_unique(std::forward<Key>(k), std::forward<M>(obj)) .first; } iterator erase(iterator); iterator erase(const_iterator); size_type erase(const key_type&); iterator erase(const_iterator, const_iterator); template <class Key> typename boost::enable_if_c< detail::transparent_non_iterable<Key, unordered_map>::value, size_type>::type erase(Key&& k) { return table_.erase_key_unique_impl(std::forward<Key>(k)); } BOOST_UNORDERED_DEPRECATED("Use erase instead") void quick_erase(const_iterator it) { erase(it); } BOOST_UNORDERED_DEPRECATED("Use erase instead") void erase_return_void(const_iterator it) { erase(it); } void swap(unordered_map&) noexcept(value_allocator_traits::is_always_equal::value&& boost::unordered::detail::is_nothrow_swappable<H>::value&& boost::unordered::detail::is_nothrow_swappable<P>::value); void clear() noexcept { table_.clear_impl(); } template <typename H2, typename P2> void merge(boost::unordered_map<K, T, H2, P2, A>& source); template <typename H2, typename P2> void merge(boost::unordered_map<K, T, H2, P2, A>&& source); template <typename H2, typename P2> void merge(boost::unordered_multimap<K, T, H2, P2, A>& source); template <typename H2, typename P2> void merge(boost::unordered_multimap<K, T, H2, P2, A>&& source); // observers hasher hash_function() const; key_equal key_eq() const; // lookup iterator find(const key_type&); const_iterator find(const key_type&) const; template <class Key> typename boost::enable_if_c<detail::are_transparent<Key, H, P>::value, iterator>::type find(const Key& key) { return table_.find(key); } template <class Key> typename boost::enable_if_c<detail::are_transparent<Key, H, P>::value, const_iterator>::type find(const Key& key) const { return const_iterator(table_.find(key)); } template <class CompatibleKey, class CompatibleHash, class CompatiblePredicate> iterator find(CompatibleKey const&, CompatibleHash const&, CompatiblePredicate const&); template <class CompatibleKey, class CompatibleHash, class CompatiblePredicate> const_iterator find(CompatibleKey const&, CompatibleHash const&, CompatiblePredicate const&) const; bool contains(const key_type& k) const { return table_.find(k) != this->end(); } template <class Key> typename boost::enable_if_c<detail::are_transparent<Key, H, P>::value, bool>::type contains(const Key& k) const { return table_.find(k) != this->end(); } size_type count(const key_type&) const; template <class Key> typename boost::enable_if_c<detail::are_transparent<Key, H, P>::value, size_type>::type count(const Key& k) const { return (table_.find(k) != this->end() ? 1 : 0); } std::pair<iterator, iterator> equal_range(const key_type&); std::pair<const_iterator, const_iterator> equal_range( const key_type&) const; template <class Key> typename boost::enable_if_c<detail::are_transparent<Key, H, P>::value, std::pair<iterator, iterator> >::type equal_range(const Key& key) { iterator first = table_.find(key); iterator last = first; if (last != this->end()) { ++last; } return std::make_pair(first, last); } template <class Key> typename boost::enable_if_c<detail::are_transparent<Key, H, P>::value, std::pair<const_iterator, const_iterator> >::type equal_range(const Key& key) const { iterator first = table_.find(key); iterator last = first; if (last != this->end()) { ++last; } return std::make_pair(first, last); } mapped_type& operator[](const key_type&); mapped_type& operator[](key_type&&); template <class Key> typename boost::enable_if_c<detail::are_transparent<Key, H, P>::value, mapped_type&>::type operator[](Key&& k); mapped_type& at(const key_type&); mapped_type const& at(const key_type&) const; template <class Key> typename boost::enable_if_c<detail::are_transparent<Key, H, P>::value, mapped_type&>::type at(Key&& k); template <class Key> typename boost::enable_if_c<detail::are_transparent<Key, H, P>::value, mapped_type const&>::type at(Key&& k) const; // bucket interface size_type bucket_count() const noexcept { return table_.bucket_count(); } size_type max_bucket_count() const noexcept { return table_.max_bucket_count(); } size_type bucket_size(size_type) const; size_type bucket(const key_type& k) const { return table_.hash_to_bucket(table_.hash(k)); } template <class Key> typename boost::enable_if_c<detail::are_transparent<Key, H, P>::value, size_type>::type bucket(Key&& k) const { return table_.hash_to_bucket(table_.hash(std::forward<Key>(k))); } local_iterator begin(size_type n) { return table_.begin(n); } const_local_iterator begin(size_type n) const { return const_local_iterator(table_.begin(n)); } local_iterator end(size_type) { return local_iterator(); } const_local_iterator end(size_type) const { return const_local_iterator(); } const_local_iterator cbegin(size_type n) const { return const_local_iterator(table_.begin(n)); } const_local_iterator cend(size_type) const { return const_local_iterator(); } // hash policy float load_factor() const noexcept; float max_load_factor() const noexcept { return table_.mlf_; } void max_load_factor(float) noexcept; void rehash(size_type); void reserve(size_type); #if !BOOST_WORKAROUND(BOOST_BORLANDC, < 0x0582) friend bool operator== <K, T, H, P, A>(unordered_map const&, unordered_map const&); friend bool operator!= <K, T, H, P, A>(unordered_map const&, unordered_map const&); #endif }; // class template unordered_map template <class Archive, class K, class T, class H, class P, class A> void serialize( Archive& ar, unordered_map<K, T, H, P, A>& m, unsigned int version) { detail::serialize_fca_container(ar, m, version); } #if BOOST_UNORDERED_TEMPLATE_DEDUCTION_GUIDES template <class InputIterator, class Hash = boost::hash<boost::unordered::detail::iter_key_t<InputIterator> >, class Pred = std::equal_to<boost::unordered::detail::iter_key_t<InputIterator> >, class Allocator = std::allocator< boost::unordered::detail::iter_to_alloc_t<InputIterator> >, class = std::enable_if_t<detail::is_input_iterator_v<InputIterator> >, class = std::enable_if_t<detail::is_hash_v<Hash> >, class = std::enable_if_t<detail::is_pred_v<Pred> >, class = std::enable_if_t<detail::is_allocator_v<Allocator> > > unordered_map(InputIterator, InputIterator, std::size_t = boost::unordered::detail::default_bucket_count, Hash = Hash(), Pred = Pred(), Allocator = Allocator()) -> unordered_map<boost::unordered::detail::iter_key_t<InputIterator>, boost::unordered::detail::iter_val_t<InputIterator>, Hash, Pred, Allocator>; template <class Key, class T, class Hash = boost::hash<std::remove_const_t<Key> >, class Pred = std::equal_to<std::remove_const_t<Key> >, class Allocator = std::allocator<std::pair<const Key, T> >, class = std::enable_if_t<detail::is_hash_v<Hash> >, class = std::enable_if_t<detail::is_pred_v<Pred> >, class = std::enable_if_t<detail::is_allocator_v<Allocator> > > unordered_map(std::initializer_list<std::pair<Key, T> >, std::size_t = boost::unordered::detail::default_bucket_count, Hash = Hash(), Pred = Pred(), Allocator = Allocator()) -> unordered_map<std::remove_const_t<Key>, T, Hash, Pred, Allocator>; template <class InputIterator, class Allocator, class = std::enable_if_t<detail::is_input_iterator_v<InputIterator> >, class = std::enable_if_t<detail::is_allocator_v<Allocator> > > unordered_map(InputIterator, InputIterator, std::size_t, Allocator) -> unordered_map<boost::unordered::detail::iter_key_t<InputIterator>, boost::unordered::detail::iter_val_t<InputIterator>, boost::hash<boost::unordered::detail::iter_key_t<InputIterator> >, std::equal_to<boost::unordered::detail::iter_key_t<InputIterator> >, Allocator>; template <class InputIterator, class Allocator, class = std::enable_if_t<detail::is_input_iterator_v<InputIterator> >, class = std::enable_if_t<detail::is_allocator_v<Allocator> > > unordered_map(InputIterator, InputIterator, Allocator) -> unordered_map<boost::unordered::detail::iter_key_t<InputIterator>, boost::unordered::detail::iter_val_t<InputIterator>, boost::hash<boost::unordered::detail::iter_key_t<InputIterator> >, std::equal_to<boost::unordered::detail::iter_key_t<InputIterator> >, Allocator>; template <class InputIterator, class Hash, class Allocator, class = std::enable_if_t<detail::is_hash_v<Hash> >, class = std::enable_if_t<detail::is_input_iterator_v<InputIterator> >, class = std::enable_if_t<detail::is_allocator_v<Allocator> > > unordered_map(InputIterator, InputIterator, std::size_t, Hash, Allocator) -> unordered_map<boost::unordered::detail::iter_key_t<InputIterator>, boost::unordered::detail::iter_val_t<InputIterator>, Hash, std::equal_to<boost::unordered::detail::iter_key_t<InputIterator> >, Allocator>; template <class Key, class T, class Allocator, class = std::enable_if_t<detail::is_allocator_v<Allocator> > > unordered_map(std::initializer_list<std::pair<Key, T> >, std::size_t, Allocator) -> unordered_map<std::remove_const_t<Key>, T, boost::hash<std::remove_const_t<Key> >, std::equal_to<std::remove_const_t<Key> >, Allocator>; template <class Key, class T, class Allocator, class = std::enable_if_t<detail::is_allocator_v<Allocator> > > unordered_map(std::initializer_list<std::pair<Key, T> >, Allocator) -> unordered_map<std::remove_const_t<Key>, T, boost::hash<std::remove_const_t<Key> >, std::equal_to<std::remove_const_t<Key> >, Allocator>; template <class Key, class T, class Hash, class Allocator, class = std::enable_if_t<detail::is_hash_v<Hash> >, class = std::enable_if_t<detail::is_allocator_v<Allocator> > > unordered_map(std::initializer_list<std::pair<Key, T> >, std::size_t, Hash, Allocator) -> unordered_map<std::remove_const_t<Key>, T, Hash, std::equal_to<std::remove_const_t<Key> >, Allocator>; #endif template <class K, class T, class H, class P, class A> class unordered_multimap { template <typename, typename, typename, typename, typename> friend class unordered_map; public: typedef K key_type; typedef T mapped_type; typedef std::pair<const K, T> value_type; typedef typename boost::unordered::detail::type_identity<H>::type hasher; typedef typename boost::unordered::detail::type_identity<P>::type key_equal; typedef typename boost::unordered::detail::type_identity<A>::type allocator_type; private: typedef boost::unordered::detail::map<A, K, T, H, P> types; typedef typename types::value_allocator_traits value_allocator_traits; typedef typename types::table table; public: typedef typename value_allocator_traits::pointer pointer; typedef typename value_allocator_traits::const_pointer const_pointer; typedef value_type& reference; typedef value_type const& const_reference; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; typedef typename table::iterator iterator; typedef typename table::c_iterator const_iterator; typedef typename table::l_iterator local_iterator; typedef typename table::cl_iterator const_local_iterator; typedef typename types::node_type node_type; private: table table_; public: // constructors unordered_multimap(); explicit unordered_multimap(size_type, const hasher& = hasher(), const key_equal& = key_equal(), const allocator_type& = allocator_type()); template <class InputIt> unordered_multimap(InputIt, InputIt, size_type = boost::unordered::detail::default_bucket_count, const hasher& = hasher(), const key_equal& = key_equal(), const allocator_type& = allocator_type()); unordered_multimap(unordered_multimap const&); unordered_multimap(unordered_multimap&& other) noexcept(table::nothrow_move_constructible) : table_(other.table_, boost::unordered::detail::move_tag()) { // The move is done in table_ } explicit unordered_multimap(allocator_type const&); unordered_multimap(unordered_multimap const&, allocator_type const&); unordered_multimap(unordered_multimap&&, allocator_type const&); unordered_multimap(std::initializer_list<value_type>, size_type = boost::unordered::detail::default_bucket_count, const hasher& = hasher(), const key_equal& l = key_equal(), const allocator_type& = allocator_type()); explicit unordered_multimap(size_type, const allocator_type&); explicit unordered_multimap( size_type, const hasher&, const allocator_type&); template <class InputIterator> unordered_multimap(InputIterator, InputIterator, const allocator_type&); template <class InputIt> unordered_multimap(InputIt, InputIt, size_type, const allocator_type&); template <class InputIt> unordered_multimap( InputIt, InputIt, size_type, const hasher&, const allocator_type&); unordered_multimap( std::initializer_list<value_type>, const allocator_type&); unordered_multimap( std::initializer_list<value_type>, size_type, const allocator_type&); unordered_multimap(std::initializer_list<value_type>, size_type, const hasher&, const allocator_type&); // Destructor ~unordered_multimap() noexcept; // Assign unordered_multimap& operator=(unordered_multimap const& x) { table_.assign(x.table_, std::false_type()); return *this; } unordered_multimap& operator=(unordered_multimap&& x) noexcept(value_allocator_traits::is_always_equal::value&& std::is_nothrow_move_assignable<H>::value&& std::is_nothrow_move_assignable<P>::value) { table_.move_assign(x.table_, std::false_type()); return *this; } unordered_multimap& operator=(std::initializer_list<value_type>); allocator_type get_allocator() const noexcept { return allocator_type(table_.node_alloc()); } // iterators iterator begin() noexcept { return iterator(table_.begin()); } const_iterator begin() const noexcept { return const_iterator(table_.begin()); } iterator end() noexcept { return iterator(); } const_iterator end() const noexcept { return const_iterator(); } const_iterator cbegin() const noexcept { return const_iterator(table_.begin()); } const_iterator cend() const noexcept { return const_iterator(); } // size and capacity BOOST_ATTRIBUTE_NODISCARD bool empty() const noexcept { return table_.size_ == 0; } size_type size() const noexcept { return table_.size_; } size_type max_size() const noexcept; // emplace template <class... Args> iterator emplace(Args&&... args) { return iterator(table_.emplace_equiv( boost::unordered::detail::func::construct_node_from_args( table_.node_alloc(), std::forward<Args>(args)...))); } template <class... Args> iterator emplace_hint(const_iterator hint, Args&&... args) { return iterator(table_.emplace_hint_equiv( hint, boost::unordered::detail::func::construct_node_from_args( table_.node_alloc(), std::forward<Args>(args)...))); } iterator insert(value_type const& x) { return this->emplace(x); } iterator insert(value_type&& x) { return this->emplace(std::move(x)); } template <class P2> typename boost::enable_if<std::is_constructible<value_type, P2&&>, iterator>::type insert(P2&& obj) { return this->emplace(std::forward<P2>(obj)); } iterator insert(const_iterator hint, value_type const& x) { return this->emplace_hint(hint, x); } iterator insert(const_iterator hint, value_type&& x) { return this->emplace_hint(hint, std::move(x)); } template <class P2> typename boost::enable_if<std::is_constructible<value_type, P2&&>, iterator>::type insert(const_iterator hint, P2&& obj) { return this->emplace_hint(hint, std::forward<P2>(obj)); } template <class InputIt> void insert(InputIt, InputIt); void insert(std::initializer_list<value_type>); // extract node_type extract(const_iterator position) { return node_type( table_.extract_by_iterator_equiv(position), table_.node_alloc()); } node_type extract(const key_type& k) { return node_type(table_.extract_by_key_impl(k), table_.node_alloc()); } template <class Key> typename boost::enable_if_c< detail::transparent_non_iterable<Key, unordered_multimap>::value, node_type>::type extract(const Key& k) { return node_type(table_.extract_by_key_impl(k), table_.node_alloc()); } iterator insert(node_type&& np) { return table_.move_insert_node_type_equiv(np); } iterator insert(const_iterator hint, node_type&& np) { return table_.move_insert_node_type_with_hint_equiv(hint, np); } iterator erase(iterator); iterator erase(const_iterator); size_type erase(const key_type&); iterator erase(const_iterator, const_iterator); template <class Key> typename boost::enable_if_c< detail::transparent_non_iterable<Key, unordered_multimap>::value, size_type>::type erase(Key&& k) { return table_.erase_key_equiv_impl(std::forward<Key>(k)); } BOOST_UNORDERED_DEPRECATED("Use erase instead") void quick_erase(const_iterator it) { erase(it); } BOOST_UNORDERED_DEPRECATED("Use erase instead") void erase_return_void(const_iterator it) { erase(it); } void swap(unordered_multimap&) noexcept(value_allocator_traits::is_always_equal::value&& boost::unordered::detail::is_nothrow_swappable<H>::value&& boost::unordered::detail::is_nothrow_swappable<P>::value); void clear() noexcept { table_.clear_impl(); } template <typename H2, typename P2> void merge(boost::unordered_multimap<K, T, H2, P2, A>& source); template <typename H2, typename P2> void merge(boost::unordered_multimap<K, T, H2, P2, A>&& source); template <typename H2, typename P2> void merge(boost::unordered_map<K, T, H2, P2, A>& source); template <typename H2, typename P2> void merge(boost::unordered_map<K, T, H2, P2, A>&& source); // observers hasher hash_function() const; key_equal key_eq() const; // lookup iterator find(const key_type&); const_iterator find(const key_type&) const; template <class Key> typename boost::enable_if_c<detail::are_transparent<Key, H, P>::value, iterator>::type find(const Key& key) { return table_.find(key); } template <class Key> typename boost::enable_if_c<detail::are_transparent<Key, H, P>::value, const_iterator>::type find(const Key& key) const { return const_iterator(table_.find(key)); } template <class CompatibleKey, class CompatibleHash, class CompatiblePredicate> iterator find(CompatibleKey const&, CompatibleHash const&, CompatiblePredicate const&); template <class CompatibleKey, class CompatibleHash, class CompatiblePredicate> const_iterator find(CompatibleKey const&, CompatibleHash const&, CompatiblePredicate const&) const; bool contains(key_type const& k) const { return table_.find(k) != this->end(); } template <class Key> typename boost::enable_if_c<detail::are_transparent<Key, H, P>::value, bool>::type contains(const Key& k) const { return table_.find(k) != this->end(); } size_type count(const key_type&) const; template <class Key> typename boost::enable_if_c<detail::are_transparent<Key, H, P>::value, size_type>::type count(const Key& k) const { return table_.group_count(k); } std::pair<iterator, iterator> equal_range(const key_type&); std::pair<const_iterator, const_iterator> equal_range( const key_type&) const; template <class Key> typename boost::enable_if_c<detail::are_transparent<Key, H, P>::value, std::pair<iterator, iterator> >::type equal_range(const Key& key) { iterator p = table_.find(key); return std::make_pair(p, table_.next_group(key, p)); } template <class Key> typename boost::enable_if_c<detail::are_transparent<Key, H, P>::value, std::pair<const_iterator, const_iterator> >::type equal_range(const Key& key) const { iterator p = table_.find(key); return std::make_pair( const_iterator(p), const_iterator(table_.next_group(key, p))); } // bucket interface size_type bucket_count() const noexcept { return table_.bucket_count(); } size_type max_bucket_count() const noexcept { return table_.max_bucket_count(); } size_type bucket_size(size_type) const; size_type bucket(const key_type& k) const { return table_.hash_to_bucket(table_.hash(k)); } template <class Key> typename boost::enable_if_c<detail::are_transparent<Key, H, P>::value, size_type>::type bucket(Key&& k) const { return table_.hash_to_bucket(table_.hash(std::forward<Key>(k))); } local_iterator begin(size_type n) { return local_iterator(table_.begin(n)); } const_local_iterator begin(size_type n) const { return const_local_iterator(table_.begin(n)); } local_iterator end(size_type) { return local_iterator(); } const_local_iterator end(size_type) const { return const_local_iterator(); } const_local_iterator cbegin(size_type n) const { return const_local_iterator(table_.begin(n)); } const_local_iterator cend(size_type) const { return const_local_iterator(); } // hash policy float load_factor() const noexcept; float max_load_factor() const noexcept { return table_.mlf_; } void max_load_factor(float) noexcept; void rehash(size_type); void reserve(size_type); #if !BOOST_WORKAROUND(BOOST_BORLANDC, < 0x0582) friend bool operator== <K, T, H, P, A>(unordered_multimap const&, unordered_multimap const&); friend bool operator!= <K, T, H, P, A>(unordered_multimap const&, unordered_multimap const&); #endif }; // class template unordered_multimap template <class Archive, class K, class T, class H, class P, class A> void serialize( Archive& ar, unordered_multimap<K, T, H, P, A>& m, unsigned int version) { detail::serialize_fca_container(ar, m, version); } #if BOOST_UNORDERED_TEMPLATE_DEDUCTION_GUIDES template <class InputIterator, class Hash = boost::hash<boost::unordered::detail::iter_key_t<InputIterator> >, class Pred = std::equal_to<boost::unordered::detail::iter_key_t<InputIterator> >, class Allocator = std::allocator< boost::unordered::detail::iter_to_alloc_t<InputIterator> >, class = std::enable_if_t<detail::is_input_iterator_v<InputIterator> >, class = std::enable_if_t<detail::is_hash_v<Hash> >, class = std::enable_if_t<detail::is_pred_v<Pred> >, class = std::enable_if_t<detail::is_allocator_v<Allocator> > > unordered_multimap(InputIterator, InputIterator, std::size_t = boost::unordered::detail::default_bucket_count, Hash = Hash(), Pred = Pred(), Allocator = Allocator()) -> unordered_multimap<boost::unordered::detail::iter_key_t<InputIterator>, boost::unordered::detail::iter_val_t<InputIterator>, Hash, Pred, Allocator>; template <class Key, class T, class Hash = boost::hash<std::remove_const_t<Key> >, class Pred = std::equal_to<std::remove_const_t<Key> >, class Allocator = std::allocator<std::pair<const Key, T> >, class = std::enable_if_t<detail::is_hash_v<Hash> >, class = std::enable_if_t<detail::is_pred_v<Pred> >, class = std::enable_if_t<detail::is_allocator_v<Allocator> > > unordered_multimap(std::initializer_list<std::pair<Key, T> >, std::size_t = boost::unordered::detail::default_bucket_count, Hash = Hash(), Pred = Pred(), Allocator = Allocator()) -> unordered_multimap<std::remove_const_t<Key>, T, Hash, Pred, Allocator>; template <class InputIterator, class Allocator, class = std::enable_if_t<detail::is_input_iterator_v<InputIterator> >, class = std::enable_if_t<detail::is_allocator_v<Allocator> > > unordered_multimap(InputIterator, InputIterator, std::size_t, Allocator) -> unordered_multimap<boost::unordered::detail::iter_key_t<InputIterator>, boost::unordered::detail::iter_val_t<InputIterator>, boost::hash<boost::unordered::detail::iter_key_t<InputIterator> >, std::equal_to<boost::unordered::detail::iter_key_t<InputIterator> >, Allocator>; template <class InputIterator, class Allocator, class = std::enable_if_t<detail::is_input_iterator_v<InputIterator> >, class = std::enable_if_t<detail::is_allocator_v<Allocator> > > unordered_multimap(InputIterator, InputIterator, Allocator) -> unordered_multimap<boost::unordered::detail::iter_key_t<InputIterator>, boost::unordered::detail::iter_val_t<InputIterator>, boost::hash<boost::unordered::detail::iter_key_t<InputIterator> >, std::equal_to<boost::unordered::detail::iter_key_t<InputIterator> >, Allocator>; template <class InputIterator, class Hash, class Allocator, class = std::enable_if_t<detail::is_hash_v<Hash> >, class = std::enable_if_t<detail::is_input_iterator_v<InputIterator> >, class = std::enable_if_t<detail::is_allocator_v<Allocator> > > unordered_multimap( InputIterator, InputIterator, std::size_t, Hash, Allocator) -> unordered_multimap<boost::unordered::detail::iter_key_t<InputIterator>, boost::unordered::detail::iter_val_t<InputIterator>, Hash, std::equal_to<boost::unordered::detail::iter_key_t<InputIterator> >, Allocator>; template <class Key, class T, class Allocator, class = std::enable_if_t<detail::is_allocator_v<Allocator> > > unordered_multimap(std::initializer_list<std::pair<Key, T> >, std::size_t, Allocator) -> unordered_multimap<std::remove_const_t<Key>, T, boost::hash<std::remove_const_t<Key> >, std::equal_to<std::remove_const_t<Key> >, Allocator>; template <class Key, class T, class Allocator, class = std::enable_if_t<detail::is_allocator_v<Allocator> > > unordered_multimap(std::initializer_list<std::pair<Key, T> >, Allocator) -> unordered_multimap<std::remove_const_t<Key>, T, boost::hash<std::remove_const_t<Key> >, std::equal_to<std::remove_const_t<Key> >, Allocator>; template <class Key, class T, class Hash, class Allocator, class = std::enable_if_t<detail::is_hash_v<Hash> >, class = std::enable_if_t<detail::is_allocator_v<Allocator> > > unordered_multimap(std::initializer_list<std::pair<Key, T> >, std::size_t, Hash, Allocator) -> unordered_multimap<std::remove_const_t<Key>, T, Hash, std::equal_to<std::remove_const_t<Key> >, Allocator>; #endif //////////////////////////////////////////////////////////////////////////// template <class K, class T, class H, class P, class A> unordered_map<K, T, H, P, A>::unordered_map() { } template <class K, class T, class H, class P, class A> unordered_map<K, T, H, P, A>::unordered_map(size_type n, const hasher& hf, const key_equal& eql, const allocator_type& a) : table_(n, hf, eql, a) { } template <class K, class T, class H, class P, class A> template <class InputIt> unordered_map<K, T, H, P, A>::unordered_map(InputIt f, InputIt l, size_type n, const hasher& hf, const key_equal& eql, const allocator_type& a) : table_(boost::unordered::detail::initial_size(f, l, n), hf, eql, a) { this->insert(f, l); } template <class K, class T, class H, class P, class A> unordered_map<K, T, H, P, A>::unordered_map(unordered_map const& other) : table_(other.table_, unordered_map::value_allocator_traits:: select_on_container_copy_construction(other.get_allocator())) { if (other.size()) { table_.copy_buckets(other.table_, std::true_type()); } } template <class K, class T, class H, class P, class A> unordered_map<K, T, H, P, A>::unordered_map(allocator_type const& a) : table_(boost::unordered::detail::default_bucket_count, hasher(), key_equal(), a) { } template <class K, class T, class H, class P, class A> unordered_map<K, T, H, P, A>::unordered_map( unordered_map const& other, allocator_type const& a) : table_(other.table_, a) { if (other.table_.size_) { table_.copy_buckets(other.table_, std::true_type()); } } template <class K, class T, class H, class P, class A> unordered_map<K, T, H, P, A>::unordered_map( unordered_map&& other, allocator_type const& a) : table_(other.table_, a, boost::unordered::detail::move_tag()) { table_.move_construct_buckets(other.table_); } template <class K, class T, class H, class P, class A> unordered_map<K, T, H, P, A>::unordered_map( std::initializer_list<value_type> list, size_type n, const hasher& hf, const key_equal& eql, const allocator_type& a) : table_( boost::unordered::detail::initial_size(list.begin(), list.end(), n), hf, eql, a) { this->insert(list.begin(), list.end()); } template <class K, class T, class H, class P, class A> unordered_map<K, T, H, P, A>::unordered_map( size_type n, const allocator_type& a) : table_(n, hasher(), key_equal(), a) { } template <class K, class T, class H, class P, class A> unordered_map<K, T, H, P, A>::unordered_map( size_type n, const hasher& hf, const allocator_type& a) : table_(n, hf, key_equal(), a) { } template <class K, class T, class H, class P, class A> template <class InputIterator> unordered_map<K, T, H, P, A>::unordered_map( InputIterator f, InputIterator l, const allocator_type& a) : table_(boost::unordered::detail::initial_size( f, l, detail::default_bucket_count), hasher(), key_equal(), a) { this->insert(f, l); } template <class K, class T, class H, class P, class A> template <class InputIt> unordered_map<K, T, H, P, A>::unordered_map( InputIt f, InputIt l, size_type n, const allocator_type& a) : table_(boost::unordered::detail::initial_size(f, l, n), hasher(), key_equal(), a) { this->insert(f, l); } template <class K, class T, class H, class P, class A> template <class InputIt> unordered_map<K, T, H, P, A>::unordered_map(InputIt f, InputIt l, size_type n, const hasher& hf, const allocator_type& a) : table_( boost::unordered::detail::initial_size(f, l, n), hf, key_equal(), a) { this->insert(f, l); } template <class K, class T, class H, class P, class A> unordered_map<K, T, H, P, A>::unordered_map( std::initializer_list<value_type> list, const allocator_type& a) : table_(boost::unordered::detail::initial_size( list.begin(), list.end(), detail::default_bucket_count), hasher(), key_equal(), a) { this->insert(list.begin(), list.end()); } template <class K, class T, class H, class P, class A> unordered_map<K, T, H, P, A>::unordered_map( std::initializer_list<value_type> list, size_type n, const allocator_type& a) : table_( boost::unordered::detail::initial_size(list.begin(), list.end(), n), hasher(), key_equal(), a) { this->insert(list.begin(), list.end()); } template <class K, class T, class H, class P, class A> unordered_map<K, T, H, P, A>::unordered_map( std::initializer_list<value_type> list, size_type n, const hasher& hf, const allocator_type& a) : table_( boost::unordered::detail::initial_size(list.begin(), list.end(), n), hf, key_equal(), a) { this->insert(list.begin(), list.end()); } template <class K, class T, class H, class P, class A> unordered_map<K, T, H, P, A>::~unordered_map() noexcept { } template <class K, class T, class H, class P, class A> unordered_map<K, T, H, P, A>& unordered_map<K, T, H, P, A>::operator=( std::initializer_list<value_type> list) { this->clear(); this->insert(list.begin(), list.end()); return *this; } // size and capacity template <class K, class T, class H, class P, class A> std::size_t unordered_map<K, T, H, P, A>::max_size() const noexcept { using namespace std; // size <= mlf_ * count return boost::unordered::detail::double_to_size( ceil(static_cast<double>(table_.mlf_) * static_cast<double>(table_.max_bucket_count()))) - 1; } // modifiers template <class K, class T, class H, class P, class A> template <class InputIt> void unordered_map<K, T, H, P, A>::insert(InputIt first, InputIt last) { if (first != last) { table_.insert_range_unique( table::extractor::extract(*first), first, last); } } template <class K, class T, class H, class P, class A> void unordered_map<K, T, H, P, A>::insert( std::initializer_list<value_type> list) { this->insert(list.begin(), list.end()); } template <class K, class T, class H, class P, class A> typename unordered_map<K, T, H, P, A>::iterator unordered_map<K, T, H, P, A>::erase(iterator position) { return table_.erase_node(position); } template <class K, class T, class H, class P, class A> typename unordered_map<K, T, H, P, A>::iterator unordered_map<K, T, H, P, A>::erase(const_iterator position) { return table_.erase_node(position); } template <class K, class T, class H, class P, class A> typename unordered_map<K, T, H, P, A>::size_type unordered_map<K, T, H, P, A>::erase(const key_type& k) { return table_.erase_key_unique_impl(k); } template <class K, class T, class H, class P, class A> typename unordered_map<K, T, H, P, A>::iterator unordered_map<K, T, H, P, A>::erase( const_iterator first, const_iterator last) { return table_.erase_nodes_range(first, last); } template <class K, class T, class H, class P, class A> void unordered_map<K, T, H, P, A>::swap(unordered_map& other) noexcept(value_allocator_traits::is_always_equal::value&& boost::unordered::detail::is_nothrow_swappable<H>::value&& boost::unordered::detail::is_nothrow_swappable<P>::value) { table_.swap(other.table_); } template <class K, class T, class H, class P, class A> template <typename H2, typename P2> void unordered_map<K, T, H, P, A>::merge( boost::unordered_map<K, T, H2, P2, A>& source) { table_.merge_unique(source.table_); } template <class K, class T, class H, class P, class A> template <typename H2, typename P2> void unordered_map<K, T, H, P, A>::merge( boost::unordered_map<K, T, H2, P2, A>&& source) { table_.merge_unique(source.table_); } template <class K, class T, class H, class P, class A> template <typename H2, typename P2> void unordered_map<K, T, H, P, A>::merge( boost::unordered_multimap<K, T, H2, P2, A>& source) { table_.merge_unique(source.table_); } template <class K, class T, class H, class P, class A> template <typename H2, typename P2> void unordered_map<K, T, H, P, A>::merge( boost::unordered_multimap<K, T, H2, P2, A>&& source) { table_.merge_unique(source.table_); } // observers template <class K, class T, class H, class P, class A> typename unordered_map<K, T, H, P, A>::hasher unordered_map<K, T, H, P, A>::hash_function() const { return table_.hash_function(); } template <class K, class T, class H, class P, class A> typename unordered_map<K, T, H, P, A>::key_equal unordered_map<K, T, H, P, A>::key_eq() const { return table_.key_eq(); } // lookup template <class K, class T, class H, class P, class A> typename unordered_map<K, T, H, P, A>::iterator unordered_map<K, T, H, P, A>::find(const key_type& k) { return iterator(table_.find(k)); } template <class K, class T, class H, class P, class A> typename unordered_map<K, T, H, P, A>::const_iterator unordered_map<K, T, H, P, A>::find(const key_type& k) const { return const_iterator(table_.find(k)); } template <class K, class T, class H, class P, class A> template <class CompatibleKey, class CompatibleHash, class CompatiblePredicate> typename unordered_map<K, T, H, P, A>::iterator unordered_map<K, T, H, P, A>::find(CompatibleKey const& k, CompatibleHash const& hash, CompatiblePredicate const& eq) { return table_.transparent_find(k, hash, eq); } template <class K, class T, class H, class P, class A> template <class CompatibleKey, class CompatibleHash, class CompatiblePredicate> typename unordered_map<K, T, H, P, A>::const_iterator unordered_map<K, T, H, P, A>::find(CompatibleKey const& k, CompatibleHash const& hash, CompatiblePredicate const& eq) const { return table_.transparent_find(k, hash, eq); } template <class K, class T, class H, class P, class A> typename unordered_map<K, T, H, P, A>::size_type unordered_map<K, T, H, P, A>::count(const key_type& k) const { return table_.find_node(k) ? 1 : 0; } template <class K, class T, class H, class P, class A> std::pair<typename unordered_map<K, T, H, P, A>::iterator, typename unordered_map<K, T, H, P, A>::iterator> unordered_map<K, T, H, P, A>::equal_range(const key_type& k) { iterator first = table_.find(k); iterator second = first; if (second != this->end()) { ++second; } return std::make_pair(first, second); } template <class K, class T, class H, class P, class A> std::pair<typename unordered_map<K, T, H, P, A>::const_iterator, typename unordered_map<K, T, H, P, A>::const_iterator> unordered_map<K, T, H, P, A>::equal_range(const key_type& k) const { iterator first = table_.find(k); iterator second = first; if (second != this->end()) { ++second; } return std::make_pair(const_iterator(first), const_iterator(second)); } template <class K, class T, class H, class P, class A> typename unordered_map<K, T, H, P, A>::mapped_type& unordered_map<K, T, H, P, A>::operator[](const key_type& k) { return table_.try_emplace_unique(k).first->second; } template <class K, class T, class H, class P, class A> typename unordered_map<K, T, H, P, A>::mapped_type& unordered_map<K, T, H, P, A>::operator[](key_type&& k) { return table_.try_emplace_unique(std::move(k)).first->second; } template <class K, class T, class H, class P, class A> template <class Key> typename boost::enable_if_c<detail::are_transparent<Key, H, P>::value, typename unordered_map<K, T, H, P, A>::mapped_type&>::type unordered_map<K, T, H, P, A>::operator[](Key&& k) { return table_.try_emplace_unique(std::forward<Key>(k)).first->second; } template <class K, class T, class H, class P, class A> typename unordered_map<K, T, H, P, A>::mapped_type& unordered_map<K, T, H, P, A>::at(const key_type& k) { typedef typename table::node_pointer node_pointer; if (table_.size_) { node_pointer p = table_.find_node(k); if (p) return p->value().second; } boost::unordered::detail::throw_out_of_range( "Unable to find key in unordered_map."); } template <class K, class T, class H, class P, class A> typename unordered_map<K, T, H, P, A>::mapped_type const& unordered_map<K, T, H, P, A>::at(const key_type& k) const { typedef typename table::node_pointer node_pointer; if (table_.size_) { node_pointer p = table_.find_node(k); if (p) return p->value().second; } boost::unordered::detail::throw_out_of_range( "Unable to find key in unordered_map."); } template <class K, class T, class H, class P, class A> template <class Key> typename boost::enable_if_c<detail::are_transparent<Key, H, P>::value, typename unordered_map<K, T, H, P, A>::mapped_type&>::type unordered_map<K, T, H, P, A>::at(Key&& k) { typedef typename table::node_pointer node_pointer; if (table_.size_) { node_pointer p = table_.find_node(std::forward<Key>(k)); if (p) return p->value().second; } boost::unordered::detail::throw_out_of_range( "Unable to find key in unordered_map."); } template <class K, class T, class H, class P, class A> template <class Key> typename boost::enable_if_c<detail::are_transparent<Key, H, P>::value, typename unordered_map<K, T, H, P, A>::mapped_type const&>::type unordered_map<K, T, H, P, A>::at(Key&& k) const { typedef typename table::node_pointer node_pointer; if (table_.size_) { node_pointer p = table_.find_node(std::forward<Key>(k)); if (p) return p->value().second; } boost::unordered::detail::throw_out_of_range( "Unable to find key in unordered_map."); } template <class K, class T, class H, class P, class A> typename unordered_map<K, T, H, P, A>::size_type unordered_map<K, T, H, P, A>::bucket_size(size_type n) const { return table_.bucket_size(n); } // hash policy template <class K, class T, class H, class P, class A> float unordered_map<K, T, H, P, A>::load_factor() const noexcept { if (table_.size_ == 0) { return 0.0f; } BOOST_ASSERT(table_.bucket_count() != 0); return static_cast<float>(table_.size_) / static_cast<float>(table_.bucket_count()); } template <class K, class T, class H, class P, class A> void unordered_map<K, T, H, P, A>::max_load_factor(float m) noexcept { table_.max_load_factor(m); } template <class K, class T, class H, class P, class A> void unordered_map<K, T, H, P, A>::rehash(size_type n) { table_.rehash(n); } template <class K, class T, class H, class P, class A> void unordered_map<K, T, H, P, A>::reserve(size_type n) { table_.reserve(n); } template <class K, class T, class H, class P, class A> inline bool operator==(unordered_map<K, T, H, P, A> const& m1, unordered_map<K, T, H, P, A> const& m2) { #if BOOST_WORKAROUND(BOOST_CODEGEARC, BOOST_TESTED_AT(0x0613)) struct dummy { unordered_map<K, T, H, P, A> x; }; #endif return m1.table_.equals_unique(m2.table_); } template <class K, class T, class H, class P, class A> inline bool operator!=(unordered_map<K, T, H, P, A> const& m1, unordered_map<K, T, H, P, A> const& m2) { #if BOOST_WORKAROUND(BOOST_CODEGEARC, BOOST_TESTED_AT(0x0613)) struct dummy { unordered_map<K, T, H, P, A> x; }; #endif return !m1.table_.equals_unique(m2.table_); } template <class K, class T, class H, class P, class A> inline void swap(unordered_map<K, T, H, P, A>& m1, unordered_map<K, T, H, P, A>& m2) noexcept(noexcept(m1.swap(m2))) { #if BOOST_WORKAROUND(BOOST_CODEGEARC, BOOST_TESTED_AT(0x0613)) struct dummy { unordered_map<K, T, H, P, A> x; }; #endif m1.swap(m2); } template <class K, class T, class H, class P, class A, class Predicate> typename unordered_map<K, T, H, P, A>::size_type erase_if( unordered_map<K, T, H, P, A>& c, Predicate pred) { return detail::erase_if(c, pred); } //////////////////////////////////////////////////////////////////////////// template <class K, class T, class H, class P, class A> unordered_multimap<K, T, H, P, A>::unordered_multimap() { } template <class K, class T, class H, class P, class A> unordered_multimap<K, T, H, P, A>::unordered_multimap(size_type n, const hasher& hf, const key_equal& eql, const allocator_type& a) : table_(n, hf, eql, a) { } template <class K, class T, class H, class P, class A> template <class InputIt> unordered_multimap<K, T, H, P, A>::unordered_multimap(InputIt f, InputIt l, size_type n, const hasher& hf, const key_equal& eql, const allocator_type& a) : table_(boost::unordered::detail::initial_size(f, l, n), hf, eql, a) { this->insert(f, l); } template <class K, class T, class H, class P, class A> unordered_multimap<K, T, H, P, A>::unordered_multimap( unordered_multimap const& other) : table_(other.table_, unordered_multimap::value_allocator_traits:: select_on_container_copy_construction(other.get_allocator())) { if (other.table_.size_) { table_.copy_buckets(other.table_, std::false_type()); } } template <class K, class T, class H, class P, class A> unordered_multimap<K, T, H, P, A>::unordered_multimap( allocator_type const& a) : table_(boost::unordered::detail::default_bucket_count, hasher(), key_equal(), a) { } template <class K, class T, class H, class P, class A> unordered_multimap<K, T, H, P, A>::unordered_multimap( unordered_multimap const& other, allocator_type const& a) : table_(other.table_, a) { if (other.table_.size_) { table_.copy_buckets(other.table_, std::false_type()); } } template <class K, class T, class H, class P, class A> unordered_multimap<K, T, H, P, A>::unordered_multimap( unordered_multimap&& other, allocator_type const& a) : table_(other.table_, a, boost::unordered::detail::move_tag()) { table_.move_construct_buckets(other.table_); } template <class K, class T, class H, class P, class A> unordered_multimap<K, T, H, P, A>::unordered_multimap( std::initializer_list<value_type> list, size_type n, const hasher& hf, const key_equal& eql, const allocator_type& a) : table_( boost::unordered::detail::initial_size(list.begin(), list.end(), n), hf, eql, a) { this->insert(list.begin(), list.end()); } template <class K, class T, class H, class P, class A> unordered_multimap<K, T, H, P, A>::unordered_multimap( size_type n, const allocator_type& a) : table_(n, hasher(), key_equal(), a) { } template <class K, class T, class H, class P, class A> unordered_multimap<K, T, H, P, A>::unordered_multimap( size_type n, const hasher& hf, const allocator_type& a) : table_(n, hf, key_equal(), a) { } template <class K, class T, class H, class P, class A> template <class InputIterator> unordered_multimap<K, T, H, P, A>::unordered_multimap( InputIterator f, InputIterator l, const allocator_type& a) : table_(boost::unordered::detail::initial_size( f, l, detail::default_bucket_count), hasher(), key_equal(), a) { this->insert(f, l); } template <class K, class T, class H, class P, class A> template <class InputIt> unordered_multimap<K, T, H, P, A>::unordered_multimap( InputIt f, InputIt l, size_type n, const allocator_type& a) : table_(boost::unordered::detail::initial_size(f, l, n), hasher(), key_equal(), a) { this->insert(f, l); } template <class K, class T, class H, class P, class A> template <class InputIt> unordered_multimap<K, T, H, P, A>::unordered_multimap(InputIt f, InputIt l, size_type n, const hasher& hf, const allocator_type& a) : table_( boost::unordered::detail::initial_size(f, l, n), hf, key_equal(), a) { this->insert(f, l); } template <class K, class T, class H, class P, class A> unordered_multimap<K, T, H, P, A>::unordered_multimap( std::initializer_list<value_type> list, const allocator_type& a) : table_(boost::unordered::detail::initial_size( list.begin(), list.end(), detail::default_bucket_count), hasher(), key_equal(), a) { this->insert(list.begin(), list.end()); } template <class K, class T, class H, class P, class A> unordered_multimap<K, T, H, P, A>::unordered_multimap( std::initializer_list<value_type> list, size_type n, const allocator_type& a) : table_( boost::unordered::detail::initial_size(list.begin(), list.end(), n), hasher(), key_equal(), a) { this->insert(list.begin(), list.end()); } template <class K, class T, class H, class P, class A> unordered_multimap<K, T, H, P, A>::unordered_multimap( std::initializer_list<value_type> list, size_type n, const hasher& hf, const allocator_type& a) : table_( boost::unordered::detail::initial_size(list.begin(), list.end(), n), hf, key_equal(), a) { this->insert(list.begin(), list.end()); } template <class K, class T, class H, class P, class A> unordered_multimap<K, T, H, P, A>::~unordered_multimap() noexcept { } template <class K, class T, class H, class P, class A> unordered_multimap<K, T, H, P, A>& unordered_multimap<K, T, H, P, A>::operator=( std::initializer_list<value_type> list) { this->clear(); this->insert(list.begin(), list.end()); return *this; } // size and capacity template <class K, class T, class H, class P, class A> std::size_t unordered_multimap<K, T, H, P, A>::max_size() const noexcept { using namespace std; // size <= mlf_ * count return boost::unordered::detail::double_to_size( ceil(static_cast<double>(table_.mlf_) * static_cast<double>(table_.max_bucket_count()))) - 1; } // modifiers template <class K, class T, class H, class P, class A> template <class InputIt> void unordered_multimap<K, T, H, P, A>::insert(InputIt first, InputIt last) { table_.insert_range_equiv(first, last); } template <class K, class T, class H, class P, class A> void unordered_multimap<K, T, H, P, A>::insert( std::initializer_list<value_type> list) { this->insert(list.begin(), list.end()); } template <class K, class T, class H, class P, class A> typename unordered_multimap<K, T, H, P, A>::iterator unordered_multimap<K, T, H, P, A>::erase(iterator position) { BOOST_ASSERT(position != this->end()); return table_.erase_node(position); } template <class K, class T, class H, class P, class A> typename unordered_multimap<K, T, H, P, A>::iterator unordered_multimap<K, T, H, P, A>::erase(const_iterator position) { BOOST_ASSERT(position != this->end()); return table_.erase_node(position); } template <class K, class T, class H, class P, class A> typename unordered_multimap<K, T, H, P, A>::size_type unordered_multimap<K, T, H, P, A>::erase(const key_type& k) { return table_.erase_key_equiv(k); } template <class K, class T, class H, class P, class A> typename unordered_multimap<K, T, H, P, A>::iterator unordered_multimap<K, T, H, P, A>::erase( const_iterator first, const_iterator last) { return table_.erase_nodes_range(first, last); } template <class K, class T, class H, class P, class A> void unordered_multimap<K, T, H, P, A>::swap(unordered_multimap& other) noexcept(value_allocator_traits::is_always_equal::value&& boost::unordered::detail::is_nothrow_swappable<H>::value&& boost::unordered::detail::is_nothrow_swappable<P>::value) { table_.swap(other.table_); } // observers template <class K, class T, class H, class P, class A> typename unordered_multimap<K, T, H, P, A>::hasher unordered_multimap<K, T, H, P, A>::hash_function() const { return table_.hash_function(); } template <class K, class T, class H, class P, class A> typename unordered_multimap<K, T, H, P, A>::key_equal unordered_multimap<K, T, H, P, A>::key_eq() const { return table_.key_eq(); } template <class K, class T, class H, class P, class A> template <typename H2, typename P2> void unordered_multimap<K, T, H, P, A>::merge( boost::unordered_multimap<K, T, H2, P2, A>& source) { while (!source.empty()) { insert(source.extract(source.begin())); } } template <class K, class T, class H, class P, class A> template <typename H2, typename P2> void unordered_multimap<K, T, H, P, A>::merge( boost::unordered_multimap<K, T, H2, P2, A>&& source) { while (!source.empty()) { insert(source.extract(source.begin())); } } template <class K, class T, class H, class P, class A> template <typename H2, typename P2> void unordered_multimap<K, T, H, P, A>::merge( boost::unordered_map<K, T, H2, P2, A>& source) { while (!source.empty()) { insert(source.extract(source.begin())); } } template <class K, class T, class H, class P, class A> template <typename H2, typename P2> void unordered_multimap<K, T, H, P, A>::merge( boost::unordered_map<K, T, H2, P2, A>&& source) { while (!source.empty()) { insert(source.extract(source.begin())); } } // lookup template <class K, class T, class H, class P, class A> typename unordered_multimap<K, T, H, P, A>::iterator unordered_multimap<K, T, H, P, A>::find(const key_type& k) { return iterator(table_.find(k)); } template <class K, class T, class H, class P, class A> typename unordered_multimap<K, T, H, P, A>::const_iterator unordered_multimap<K, T, H, P, A>::find(const key_type& k) const { return const_iterator(table_.find(k)); } template <class K, class T, class H, class P, class A> template <class CompatibleKey, class CompatibleHash, class CompatiblePredicate> typename unordered_multimap<K, T, H, P, A>::iterator unordered_multimap<K, T, H, P, A>::find(CompatibleKey const& k, CompatibleHash const& hash, CompatiblePredicate const& eq) { return table_.transparent_find(k, hash, eq); } template <class K, class T, class H, class P, class A> template <class CompatibleKey, class CompatibleHash, class CompatiblePredicate> typename unordered_multimap<K, T, H, P, A>::const_iterator unordered_multimap<K, T, H, P, A>::find(CompatibleKey const& k, CompatibleHash const& hash, CompatiblePredicate const& eq) const { return const_iterator( table_.find_node_impl(table::policy::apply_hash(hash, k), k, eq)); } template <class K, class T, class H, class P, class A> typename unordered_multimap<K, T, H, P, A>::size_type unordered_multimap<K, T, H, P, A>::count(const key_type& k) const { return table_.group_count(k); } template <class K, class T, class H, class P, class A> std::pair<typename unordered_multimap<K, T, H, P, A>::iterator, typename unordered_multimap<K, T, H, P, A>::iterator> unordered_multimap<K, T, H, P, A>::equal_range(const key_type& k) { iterator n = table_.find(k); return std::make_pair(n, (n == end() ? n : table_.next_group(k, n))); } template <class K, class T, class H, class P, class A> std::pair<typename unordered_multimap<K, T, H, P, A>::const_iterator, typename unordered_multimap<K, T, H, P, A>::const_iterator> unordered_multimap<K, T, H, P, A>::equal_range(const key_type& k) const { iterator n = table_.find(k); return std::make_pair(const_iterator(n), const_iterator(n == end() ? n : table_.next_group(k, n))); } template <class K, class T, class H, class P, class A> typename unordered_multimap<K, T, H, P, A>::size_type unordered_multimap<K, T, H, P, A>::bucket_size(size_type n) const { return table_.bucket_size(n); } // hash policy template <class K, class T, class H, class P, class A> float unordered_multimap<K, T, H, P, A>::load_factor() const noexcept { if (table_.size_ == 0) { return 0.0f; } BOOST_ASSERT(table_.bucket_count() != 0); return static_cast<float>(table_.size_) / static_cast<float>(table_.bucket_count()); } template <class K, class T, class H, class P, class A> void unordered_multimap<K, T, H, P, A>::max_load_factor(float m) noexcept { table_.max_load_factor(m); } template <class K, class T, class H, class P, class A> void unordered_multimap<K, T, H, P, A>::rehash(size_type n) { table_.rehash(n); } template <class K, class T, class H, class P, class A> void unordered_multimap<K, T, H, P, A>::reserve(size_type n) { table_.reserve(n); } template <class K, class T, class H, class P, class A> inline bool operator==(unordered_multimap<K, T, H, P, A> const& m1, unordered_multimap<K, T, H, P, A> const& m2) { #if BOOST_WORKAROUND(BOOST_CODEGEARC, BOOST_TESTED_AT(0x0613)) struct dummy { unordered_multimap<K, T, H, P, A> x; }; #endif return m1.table_.equals_equiv(m2.table_); } template <class K, class T, class H, class P, class A> inline bool operator!=(unordered_multimap<K, T, H, P, A> const& m1, unordered_multimap<K, T, H, P, A> const& m2) { #if BOOST_WORKAROUND(BOOST_CODEGEARC, BOOST_TESTED_AT(0x0613)) struct dummy { unordered_multimap<K, T, H, P, A> x; }; #endif return !m1.table_.equals_equiv(m2.table_); } template <class K, class T, class H, class P, class A> inline void swap(unordered_multimap<K, T, H, P, A>& m1, unordered_multimap<K, T, H, P, A>& m2) noexcept(noexcept(m1.swap(m2))) { #if BOOST_WORKAROUND(BOOST_CODEGEARC, BOOST_TESTED_AT(0x0613)) struct dummy { unordered_multimap<K, T, H, P, A> x; }; #endif m1.swap(m2); } template <class K, class T, class H, class P, class A, class Predicate> typename unordered_multimap<K, T, H, P, A>::size_type erase_if( unordered_multimap<K, T, H, P, A>& c, Predicate pred) { return detail::erase_if(c, pred); } template <typename N, class K, class T, class A> class node_handle_map { template <typename Types> friend struct ::boost::unordered::detail::table; template <class K2, class T2, class H2, class P2, class A2> friend class boost::unordered::unordered_map; template <class K2, class T2, class H2, class P2, class A2> friend class boost::unordered::unordered_multimap; typedef typename boost::allocator_rebind<A, std::pair<K const, T> >::type value_allocator; typedef N node; typedef typename boost::allocator_rebind<A, node>::type node_allocator; typedef typename boost::allocator_pointer<node_allocator>::type node_pointer; public: typedef K key_type; typedef T mapped_type; typedef A allocator_type; private: node_pointer ptr_; boost::unordered::detail::optional<value_allocator> alloc_; node_handle_map(node_pointer ptr, allocator_type const& a) : ptr_(ptr), alloc_(a) { } public: constexpr node_handle_map() noexcept : ptr_(), alloc_() {} node_handle_map(node_handle_map const&) = delete; node_handle_map& operator=(node_handle_map const&) = delete; ~node_handle_map() { if (ptr_) { node_allocator node_alloc(*alloc_); boost::unordered::detail::node_tmp<node_allocator> tmp( ptr_, node_alloc); } } node_handle_map(node_handle_map&& n) noexcept : ptr_(n.ptr_), alloc_(std::move(n.alloc_)) { n.ptr_ = node_pointer(); } node_handle_map& operator=(node_handle_map&& n) { BOOST_ASSERT(!alloc_.has_value() || boost::allocator_propagate_on_container_move_assignment< value_allocator>::type::value || (n.alloc_.has_value() && alloc_ == n.alloc_)); if (ptr_) { node_allocator node_alloc(*alloc_); boost::unordered::detail::node_tmp<node_allocator> tmp( ptr_, node_alloc); ptr_ = node_pointer(); } if (!alloc_.has_value() || boost::allocator_propagate_on_container_move_assignment< value_allocator>::type::value) { alloc_ = std::move(n.alloc_); } ptr_ = n.ptr_; n.ptr_ = node_pointer(); return *this; } key_type& key() const { return const_cast<key_type&>(ptr_->value().first); } mapped_type& mapped() const { return ptr_->value().second; } allocator_type get_allocator() const { return *alloc_; } explicit operator bool() const noexcept { return !this->operator!(); } bool operator!() const noexcept { return ptr_ ? 0 : 1; } BOOST_ATTRIBUTE_NODISCARD bool empty() const noexcept { return ptr_ ? 0 : 1; } void swap(node_handle_map& n) noexcept(boost::allocator_propagate_on_container_swap< value_allocator>::type::value || boost::allocator_is_always_equal<value_allocator>::type::value) { BOOST_ASSERT(!alloc_.has_value() || !n.alloc_.has_value() || boost::allocator_propagate_on_container_swap< value_allocator>::type::value || alloc_ == n.alloc_); if (boost::allocator_propagate_on_container_swap< value_allocator>::type::value || !alloc_.has_value() || !n.alloc_.has_value()) { boost::core::invoke_swap(alloc_, n.alloc_); } boost::core::invoke_swap(ptr_, n.ptr_); } }; template <class N, class K, class T, class A> void swap(node_handle_map<N, K, T, A>& x, node_handle_map<N, K, T, A>& y) noexcept(noexcept(x.swap(y))) { x.swap(y); } template <class Iter, class NodeType> struct insert_return_type_map { public: Iter position; bool inserted; NodeType node; insert_return_type_map() : position(), inserted(false), node() {} insert_return_type_map(insert_return_type_map const&) = delete; insert_return_type_map& operator=(insert_return_type_map const&) = delete; insert_return_type_map(insert_return_type_map&& x) noexcept : position(x.position), inserted(x.inserted), node(std::move(x.node)) { } insert_return_type_map& operator=(insert_return_type_map&& x) { inserted = x.inserted; position = x.position; node = std::move(x.node); return *this; } }; template <class Iter, class NodeType> void swap(insert_return_type_map<Iter, NodeType>& x, insert_return_type_map<Iter, NodeType>& y) { boost::core::invoke_swap(x.node, y.node); boost::core::invoke_swap(x.inserted, y.inserted); boost::core::invoke_swap(x.position, y.position); } } // namespace unordered namespace serialization { template <class K, class T, class H, class P, class A> struct version<boost::unordered_map<K, T, H, P, A> > { BOOST_STATIC_CONSTANT(int, value = 1); }; template <class K, class T, class H, class P, class A> struct version<boost::unordered_multimap<K, T, H, P, A> > { BOOST_STATIC_CONSTANT(int, value = 1); }; } // namespace serialization } // namespace boost #if defined(BOOST_MSVC) #pragma warning(pop) #endif #endif // BOOST_UNORDERED_UNORDERED_MAP_HPP_INCLUDED