Skip to content

Commit 3c98acf

Browse files
Add fastmap to build()
1 parent 2ff7239 commit 3c98acf

3 files changed

Lines changed: 28 additions & 2 deletions

File tree

R/caugi_graph.R

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -268,7 +268,7 @@ caugi_graph <- S7::new_class(
268268
# initialize fastmap for name to index mapping
269269
name_index_map <- fastmap::fastmap()
270270
for (i in seq_len(nrow(nodes))) {
271-
name_index_map$set(nodes$name[i], as.integer(id[i]))
271+
name_index_map$set(nodes$name[i], i - 1L)
272272
}
273273

274274
state <- .cg_state(

R/verbs.R

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,8 @@ S7::method(build, caugi_graph) <- function(cg, ...) {
3434
s <- .unfreeze_state(cg@`.state`)
3535

3636
n <- nrow(s$nodes)
37-
id <- setNames(seq_len(n) - 1L, s$nodes$name)
37+
id <- seq_len(n) - 1L
38+
names(id) <- s$nodes$name
3839

3940
reg <- caugi_registry()
4041
b <- graph_builder_new(reg, n = n, simple = cg@simple)
@@ -62,6 +63,11 @@ S7::method(build, caugi_graph) <- function(cg, ...) {
6263
) |>
6364
dplyr::arrange(from, to, edge)
6465

66+
name_index_map <- fastmap::fastmap()
67+
for (i in seq_len(nrow(s$nodes))) {
68+
name_index_map$set(s$nodes$name[i], i - 1L)
69+
}
70+
s$name_index_map <- name_index_map
6571
s$ptr <- p
6672
s$built <- TRUE
6773
.freeze_state(cg@`.state`)

tests/testthat/test-verbs.R

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,26 @@ test_that("build() errors when breaking simple graph assumptions", {
4343
expect_error(build(cg), "self-loop")
4444
})
4545

46+
test_that("build updates name_index_map", {
47+
# start with a built graph
48+
cg <- caugi_graph(from = "A", edge = "-->", to = "B")
49+
expect_true(cg@built)
50+
expect_identical(cg@name_index_map$get("A"), 0L)
51+
expect_identical(cg@name_index_map$get("B"), 1L)
52+
53+
# mutate graph → not built, fastmap still stale
54+
cg <- add_nodes(cg, name = "C")
55+
expect_false(cg@built)
56+
expect_null(cg@name_index_map$get("C"))
57+
58+
# rebuild → fastmap must include the new node with correct index
59+
cg <- build(cg)
60+
expect_true(cg@built)
61+
expect_identical(cg@name_index_map$get("A"), 0L)
62+
expect_identical(cg@name_index_map$get("B"), 1L)
63+
expect_identical(cg@name_index_map$get("C"), 2L)
64+
})
65+
4666
# ──────────────────────────────────────────────────────────────────────────────
4767
# ────────────────────────────────── Edges ─────────────────────────────────────
4868
# ──────────────────────────────────────────────────────────────────────────────

0 commit comments

Comments
 (0)