Browse Source

upd erl func wrap

221V 1 week ago
parent
commit
bad26f4f6b
3 changed files with 23 additions and 18 deletions
  1. 7 14
      README.md
  2. 13 1
      niftest.erl
  3. 3 3
      niftest.zig

+ 7 - 14
README.md

@@ -18,24 +18,16 @@ Eshell V13.2  (abort with ^G)
 2> niftest:hello().
 "Hello world!"
 3> niftest:factorial(5).
-<<"x">>
-4> binary:decode_unsigned(niftest:factorial(5)).
 120
-5> niftest:factorial(20).
-<<33,195,103,124,130,180,0,0>>
-6> binary:decode_unsigned(niftest:factorial(20)).
+4> niftest:factorial(20).
 2432902008176640000
-7> niftest:factorial(34).
-<<222,27,196,209,158,252,172,130,68,93,167,91,0,0,0,0>>
-8> binary:decode_unsigned(niftest:factorial(34)).
+5> niftest:factorial(34).
 295232799039604140847618609643520000000
-9> niftest:factorial(35).
+6> niftest:factorial(35).
 {error,"input too large, max is 34"}
-10> niftest:factorial(-5).
-** exception error: bad argument
-     in function  niftest:factorial/1
-        called as niftest:factorial(-5)
-11> q().
+7> niftest:factorial(-5).
+{error,badarg}
+8> q().
 ok
 
 
@@ -45,3 +37,4 @@ https://www.erlang.org/docs/25/man/erl_nif.html
 https://www.erlang.org/doc/system/nif.html
 https://www.erlang.org/doc/system/debugging.html
 ```
+

+ 13 - 1
niftest.erl

@@ -9,7 +9,7 @@
 
 -nifs([
   hello/0,
-  factorial/1
+  factorial1/1
 ]).
 
 
@@ -22,5 +22,17 @@ hello() ->
 
 
 factorial(N) when is_integer(N), N >= 0 ->
+  case factorial1(N) of
+    Bin when is_binary(Bin) ->
+      binary:decode_unsigned(Bin);
+    Error ->
+      Error
+  end;
+
+factorial(_) ->
+  {error, badarg}.
+
+
+factorial1(_) ->
   "NIF not loaded".
 

+ 3 - 3
niftest.zig

@@ -13,7 +13,7 @@ pub export fn hello(env: ?*erl.ErlNifEnv, argc: c_int, argv: [*c]const erl.ERL_N
 }
 
 
-pub export fn factorial(env: ?*erl.ErlNifEnv, argc: c_int, argv: [*c]const erl.ERL_NIF_TERM) erl.ERL_NIF_TERM{
+pub export fn factorial1(env: ?*erl.ErlNifEnv, argc: c_int, argv: [*c]const erl.ERL_NIF_TERM) erl.ERL_NIF_TERM{
   if(argc != 1){
     return erl.enif_make_badarg(env);
   }
@@ -67,9 +67,9 @@ const nif_funcs = [_]erl.ErlNifFunc{
     .flags = 0,
   },
   .{
-    .name = "factorial",
+    .name = "factorial1",
     .arity = 1,
-    .fptr = factorial,
+    .fptr = factorial1,
     .flags = 0,
   },
 };