## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
library(rzig)
compiler <- find_zig(required = FALSE)
has_zig <- isTRUE(compiler$supported)

## ----scaffold-----------------------------------------------------------------
package_path <- tempfile("yourpackage-", tmpdir = tempdir())
dir.create(package_path)
writeLines(
  c(
    "Package: yourpackage",
    "Type: Package",
    "Title: A Small RZig Example",
    "Version: 0.0.1",
    "Authors@R: person('Your', 'Name', email = 'you@example.org', role = c('aut', 'cre'))",
    "Description: Demonstrates a native implementation written in Zig.",
    "License: GPL-3",
    "Encoding: UTF-8"
  ),
  file.path(package_path, "DESCRIPTION")
)
scaffold <- use_rzig(package_path)
scaffold

## ----write-zig, comment = ""--------------------------------------------------
main_path <- file.path(package_path, "src", "rzig", "src", "main.zig")
file.copy(system.file("examples", "axpy.zig", package = "rzig"), main_path,
  overwrite = TRUE)
cat(readLines(main_path), sep = "\n")

## ----scan---------------------------------------------------------------------
scan_exports(package_path)

## ----document-----------------------------------------------------------------
bindings <- document(package_path)
cat(bindings$wrappers)
cat(bindings$namespace)

## ----status-------------------------------------------------------------------
rzig_status(package_path)

## ----unsupported--------------------------------------------------------------
broken_path <- tempfile("brokenpackage-", tmpdir = tempdir())
dir.create(broken_path)
writeLines(c("Package: brokenpackage", "Version: 0.0.1"),
  file.path(broken_path, "DESCRIPTION"))
invisible(use_rzig(broken_path))
broken_main <- file.path(broken_path, "src", "rzig", "src", "main.zig")
cat("/// @export\npub fn half(x: f32) f32 {\n    return x / 2;\n}\n",
  file = broken_main, append = TRUE)
rzig_status(broken_path)

## ----install, eval = has_zig--------------------------------------------------
build <- build_zig(package_path)
build
package_name <- "yourpackage"
loadNamespace(package_name, lib.loc = build$library)
axpy <- getExportedValue(package_name, "axpy")

## ----call, eval = has_zig-----------------------------------------------------
x <- c(1, 2, 3)
y <- c(10, 20, 30)
result <- axpy(x, y, 0.5)
x
result
try(axpy(1:2, c(1, 2, 3), 1))
sum(1:10)

## ----cleanup, include = FALSE-------------------------------------------------
if (has_zig) unloadNamespace(package_name)
unlink(c(package_path, broken_path), recursive = TRUE)
if (has_zig) unlink(build$library, recursive = TRUE)

