You will use
external Name from erlang "module" { … }with the types of each functioncrypto:strong_rand_bytes/1andbinary:encode_hex/1from OTPBitArrayfor Erlang binaries of raw bytes
The whole program
module main
import pooka/io
import pooka/string
external Crypto from erlang "crypto" {
strong_rand_bytes(count: Int) -> BitArray
}
external Binary from erlang "binary" {
encode_hex(bytes: BitArray) -> String
}
/// A random token, `count` bytes long, as lowercase hexadecimal.
token(count: Int) -> String {
Crypto.strong_rand_bytes(count)
|> Binary.encode_hex
|> string.lowercase
}
main() {
io.println("session: " + token(16))
io.println("short: " + token(4))
}
Run it
The tokens are random, so yours will differ:
$ pooka run
session: 831e187d36c58349f482be99855d42ae
short: 6b401a61
How it works
- Name the module, list the functions.
external Crypto from erlang "crypto"gives the Erlang modulecryptoa Pooka name, and each line inside gives one function its argument and return types. - Types are a promise you make. Pooka cannot look inside Erlang, so it trusts what you write.
strong_rand_bytesreturns a binary of raw bytes, which is aBitArray;encode_hexreturns text, which is aString. - Wrap it once.
tokenis ordinary Pooka. The rest of the program callstoken(16)and never needs to know Erlang was involved.
Try next: for code of your own in Erlang, put a .erl file in the project's ffi/ folder and bind it the same way. The BEAM interop guide shows how Pooka values look on the Erlang side.