• Stars
    star
    547
  • Rank 81,254 (Top 2 %)
  • Language
    Elixir
  • License
    Other
  • Created about 5 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

zig nifs in elixir

Zigler

Library test status:

Installation

Zigler is available in Hex, and the package can be installed by adding zigler to your list of dependencies in mix.exs:

def deps do
  [
    {:zigler, "~> 0.9.1", runtime: false}
  ]
end

Documentation

Docs can be found at https://hexdocs.pm/zigler.

Currently supported platforms

  • Linux

  • FreeBSD (tested, but not subjected to CI)

  • MacOS (I believe it works but is still officially untested)

  • Nerves cross-compilation is supported out of the box.

Zig Nifs made easy

Wouldn't it be nice if you could make NIFs as easily as you can use the asm keyword in C?

This is now possible, using the magic of Zig.

defmodule ExampleZig do
  use Zig
  ~Z"""
  /// nif: example_fun/2
  fn example_fun(value1: f64, value2: f64) bool {
    return value1 > value2;
  }
  """
end

test "example nifs" do
  assert ExampleZig.example_fun(0.8, -0.8)
  refute ExampleZig.example_fun(0.1, 0.4)
end

Zigler will do automatic type marshalling between Elixir code and Zig code. It will also convert trickier types into types you care about, for example:

defmodule ZigCollections do
  use Zig
  ~Z"""
  /// nif: string_count/1
  fn string_count(string: []u8) i64 {
    return @intCast(i64, string.len);
  }

  /// nif: list_sum/1
  fn list_sum(array: []f64) f64 {
    var sum: f64 = 0.0;
    for(array) | item | {
      sum += item;
    }
    return sum;
  }
  """
end

test "type marshalling" do
  assert 9 == ZigCollections.string_count("hello zig")
  assert 6.0 == ZigCollections.list_sum([1.0, 2.0, 3.0])
end

Memory allocation with zigler is easy! A standard BEAM allocator is provided for you, so any zig code you import will play nice with the BEAM.

defmodule Allocations do
  use Zig
  ~Z"""
  /// nif: double_atom/1
  fn double_atom(env: beam.env, string: []u8) beam.term {
    var double_string = beam.allocator.alloc(u8, string.len * 2) catch {
      return beam.raise_enomem(env);
    };

    defer beam.allocator.free(double_string);

    for (string) | char, i | {
      double_string[i] = char;
      double_string[i + string.len] = char;
    }

    return beam.make_atom(env, double_string);
  }
  """
end

test "allocations" do
  assert :foofoo == Allocations.double_atom("foo")
end

It is a goal for Zigler to make using it to bind C libraries easier than using C to bind C libraries. Here is an example:

defmodule BlasDynamic do
  use Zig,
    libs: ["/usr/lib/x86_64-linux-gnu/blas/libblas.so"],
    include: ["/usr/include/x86_64-linux-gnu"],
    link_libc: true

  ~Z"""
  const blas = @cImport({
    @cInclude("cblas.h");
  });

  /// nif: blas_axpy/3
  fn blas_axpy(env: beam.env, a: f64, x: []f64, y: []f64) beam.term {
    if (x.len != y.len) {
      return beam.raise_function_clause_error(env);
    }

    blas.cblas_daxpy(@intCast(c_int, x.len), a, x.ptr, 1, y.ptr, 1);

    return beam.make_f64_list(env, y) catch {
      return beam.raise_function_clause_error(env);
    };
  }
  """
end

test "we can use a blas shared library" do
  # returns aX+Y
  assert [11.0, 18.0] == BlasDynamic.blas_axpy(3.0, [2.0, 4.0], [5.0, 6.0])
end

Documentation

You can document nif functions, local functions, zig structs, variables, and types. If you document a nif function, it will be a part of the module documentation, and accessible using the iex h method, etc.

Example:

defmodule Documentation do
  use Zig
  ~Z"""
  /// a zero-arity function which returns 47.
  /// nif: zero_arity/0
  fn zero_arity() i64 {
    return 47;
  }
  """
end

Formatting

A mix format plugin is available through the zigler_format package. See the installation instructions

Zigler Principles

  1. Make being a good citizen of the BEAM easy.
  2. Use magic, but sparingly, only to prevent errors.
  3. Let the user see behind the curtain.
  4. Let the user opt out of magic.
  5. Magic shouldn't get in the way.

More Repositories

1

mavis

opinionated typing library for elixir
Elixir
106
star
2

selectrix

Static Typechecker for Elixir
Elixir
85
star
3

ez

zig linear algebra bindings for nx
Elixir
34
star
4

librarian

ssh library for elixir
Elixir
31
star
5

yavascript

Javascript embedded inside of elixir
Elixir
19
star
6

net_address

IP and Mac address tools for Elixir
Elixir
14
star
7

state_server

half gen_statem, half gen_server
Elixir
13
star
8

realbook

imperative server provisioning for elixir
Elixir
10
star
9

pony_express

Securely send Phoenix.PubSub one-way, over long distances
Elixir
10
star
10

multiverses

multiverse support for elixir
Elixir
9
star
11

pegasus

peg -> nimbleparsec
Elixir
7
star
12

erps

Remote Protocol call/cast server
Elixir
7
star
13

Unum2-c

C version of Unum2 library
C
7
star
14

typed_headers

typed headers for elixir
Elixir
7
star
15

Unum2

Pivot Unums
Julia
6
star
16

dali.js

lightweight jQuery svg engine
JavaScript
6
star
17

zig_parser

Zig Parser for Elixir
Elixir
6
star
18

linear_algebra

Linear Algebra for Elixir
Elixir
5
star
19

state

11 ways to do state in elixir
Elixir
4
star
20

readme_consistency

Readme Consistency tutorial
Elixir
4
star
21

icmp

Icmp Ping for Elixir
Elixir
4
star
22

ecto_map_set

MapSet support for Ecto
Elixir
4
star
23

chiaroscuro

beam up modules to the browser
Zig
4
star
24

trivial

tftp read-only server for pxe bootstrapping
Elixir
4
star
25

zystem

advanced System module
Zig
3
star
26

opengenepool

Cloud-based DNA software for biologists
JavaScript
3
star
27

multiverses_pubsub

Multiverse Testing for Phoenix PubSub
Elixir
3
star
28

datalevi

privacy-oriented p2p storage server
Elixir
3
star
29

live_struct

Lets your LiveViews have struct assigns
Elixir
2
star
30

complex_nn

complex-valued neural nets
Julia
2
star
31

Underscore.jl

syntactic sugar |> syntactic diabetes
Julia
2
star
32

vscode-zigler

vscode support for Zigler
2
star
33

protoss

Evil, Powerful Protocols for Elixir
Elixir
2
star
34

router_pattern

router pattern example for GenServer and LiveView
Elixir
2
star
35

transport

transport api that unifies ssl and tls abstractions
Elixir
2
star
36

mavis_inference

inference engine for mavis typesystem
Elixir
2
star
37

zing

ICMP ping server for elixir
Elixir
2
star
38

barge

raft implementation in elixir
Elixir
1
star
39

teh_science

a repository for all the science!
1
star
40

Polynomial-Arithmetic

Julia
1
star
41

medians

elixir medians assignment
Elixir
1
star
42

zoltan

some times you just gotta write an operating system
Zig
1
star
43

live_graph_test

live graph testing
Elixir
1
star
44

multiverses_finch

multiverses adapter for the Finch library
Elixir
1
star