## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)

## ----eval = FALSE-------------------------------------------------------------
# vctrs::field(old, "b8") <- xor(vctrs::field(old, "b8"), as.raw(0xFC))
# old <- a5_migrate(old)

## -----------------------------------------------------------------------------
library(a5R)
cell <- a5_lonlat_to_cell(-3.19, 55.95, resolution = 10)
vctrs::field(cell, "b1")
vctrs::field(cell, "b8") # stored XOR 0xFC

## -----------------------------------------------------------------------------
# Display calls format(), which converts to hex for readability
cell

# Explicit conversion
a5_u64_to_hex(cell)

# Round-trip from hex; unpadded ids and a 0x prefix are read too
a5_cell(c("0800000000000006", "800000000000006", "0x0800000000000006"))

## -----------------------------------------------------------------------------
set.seed(42)
cells <- a5_lonlat_to_cell(
  runif(1e6, -180, 180),
  runif(1e6, -80, 80),
  resolution = 10
)

# rcrd: eight contiguous raw vectors (8 × 1 byte × 1M ≈ 7.6 MB)
format(object.size(cells), units = "MB")

# equivalent hex strings would be ~81 MB
# (16 chars + 56-byte SEXP header per string)
hex <- a5_u64_to_hex(cells)
format(object.size(hex), units = "MB")

## -----------------------------------------------------------------------------
cells_with_na <- a5_cell(c("0800000000000006", NA))
is.na(cells_with_na)
is.na(c(cell, NA))

## ----base-r-------------------------------------------------------------------
cells <- a5_lonlat_to_cell(c(0, 10, 0), c(0, 10, 0), resolution = 5)

# A leading NA: start with a cell, or use vctrs
c(a5_cell(NA), cells)
vctrs::vec_c(NA, cells)

# Grouping by cell: use vctrs
vctrs::vec_split(1:3, cells)$val

# Flattening lapply() output
parts <- lapply(1:3, function(i) a5_cell_to_children(cells[i]))
unlist(as_a5_cell_list(parts))

## -----------------------------------------------------------------------------
covering <- a5_compact(a5_cell_to_children(cell, child_resolution = 12))
covering
bytes <- unclass(covering)[[1]]
length(bytes) / 8                 # one stored cell, then the marker
rev(bytes[9:16])                  # the marker, most significant byte first

