Skip to content

Commit 0fdecb1

Browse files
EmmeralObserverOfTime
authored andcommitted
feat(treecursor): allow custom allocators in getCurrentNode
1 parent 58dda5e commit 0fdecb1

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

src/main/java/io/github/treesitter/jtreesitter/TreeCursor.java

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
import java.lang.foreign.Arena;
66
import java.lang.foreign.MemorySegment;
7+
import java.lang.foreign.SegmentAllocator;
78
import java.util.OptionalInt;
89
import org.jspecify.annotations.NullMarked;
910
import org.jspecify.annotations.Nullable;
@@ -36,7 +37,11 @@ private TreeCursor(TreeCursor cursor) {
3637
node = cursor.node;
3738
}
3839

39-
/** Get the current node of the cursor. */
40+
/**
41+
* Get the current node of the cursor.
42+
*
43+
* @implNote The node will become invalid once the cursor is closed.
44+
*/
4045
public Node getCurrentNode() {
4146
if (this.node == null) {
4247
var node = ts_tree_cursor_current_node(arena, self);
@@ -45,6 +50,16 @@ public Node getCurrentNode() {
4550
return this.node;
4651
}
4752

53+
/**
54+
* Get the current node of the cursor using the given allocator.
55+
*
56+
* @since 0.25.0
57+
*/
58+
public Node getCurrentNode(SegmentAllocator allocator) {
59+
var node = ts_tree_cursor_current_node(allocator, self);
60+
return new Node(node, tree);
61+
}
62+
4863
/**
4964
* Get the depth of the cursor's current node relative to
5065
* the original node that the cursor was constructed with.

src/test/java/io/github/treesitter/jtreesitter/TreeCursorTest.java

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,13 @@
33
import static org.junit.jupiter.api.Assertions.*;
44

55
import io.github.treesitter.jtreesitter.languages.TreeSitterJava;
6-
import org.junit.jupiter.api.*;
6+
import java.lang.foreign.Arena;
7+
import org.junit.jupiter.api.AfterAll;
8+
import org.junit.jupiter.api.AfterEach;
9+
import org.junit.jupiter.api.BeforeAll;
10+
import org.junit.jupiter.api.BeforeEach;
11+
import org.junit.jupiter.api.DisplayName;
12+
import org.junit.jupiter.api.Test;
713

814
class TreeCursorTest {
915
private static Tree tree;
@@ -37,6 +43,15 @@ void getCurrentNode() {
3743
var node = cursor.getCurrentNode();
3844
assertEquals(tree.getRootNode(), node);
3945
assertSame(node, cursor.getCurrentNode());
46+
47+
try (var arena = Arena.ofConfined()) {
48+
try (var copy = cursor.clone()) {
49+
node = copy.getCurrentNode(arena);
50+
assertEquals(node, tree.getRootNode());
51+
}
52+
// can still access node after cursor was closed
53+
assertEquals(node, tree.getRootNode());
54+
}
4055
}
4156

4257
@Test

0 commit comments

Comments
 (0)