Ruby 4.1.0dev (2026-11-18 revision 9de06831e37534f8a163e598cc0c6903c7687430)
line_offset_list.c
1#include "prism/internal/line_offset_list.h"
2
4#include "prism/internal/arena.h"
5
6#include <string.h>
7
11void
12pm_line_offset_list_init(pm_arena_t *arena, pm_line_offset_list_t *list, size_t capacity) {
13 list->offsets = PM_ARENA_ALLOC_ARRAY(arena, uint32_t, capacity);
14
15 // The first line always has offset 0.
16 list->offsets[0] = 0;
17 list->size = 1;
18 list->capacity = capacity;
19}
20
24void
25pm_line_offset_list_clear(pm_line_offset_list_t *list) {
26 list->size = 1;
27}
28
32void
33pm_line_offset_list_append_slow(pm_arena_t *arena, pm_line_offset_list_t *list, uint32_t cursor) {
34 size_t new_capacity = (list->capacity * 3) / 2;
35 uint32_t *new_offsets = PM_ARENA_ALLOC_ARRAY(arena, uint32_t, new_capacity);
36
37 memcpy(new_offsets, list->offsets, list->size * sizeof(uint32_t));
38
39 list->offsets = new_offsets;
40 list->capacity = new_capacity;
41
42 list->offsets[list->size++] = cursor;
43}
44
49int32_t
50pm_line_offset_list_line(const pm_line_offset_list_t *list, uint32_t cursor, int32_t start_line) {
51 size_t left = 0;
52 size_t right = list->size - 1;
53
54 while (left <= right) {
55 size_t mid = left + (right - left) / 2;
56
57 if (list->offsets[mid] == cursor) {
58 return pm_line_offset_list_line_number(mid, start_line);
59 }
60
61 if (list->offsets[mid] < cursor) {
62 left = mid + 1;
63 } else {
64 right = mid - 1;
65 }
66 }
67
68 return pm_line_offset_list_line_number(left - 1, start_line);
69}
70
77pm_line_offset_list_line_column(const pm_line_offset_list_t *list, uint32_t cursor, int32_t start_line) {
78 size_t left = 0;
79 size_t right = list->size - 1;
80
81 while (left <= right) {
82 size_t mid = left + (right - left) / 2;
83
84 if (list->offsets[mid] == cursor) {
85 return ((pm_line_column_t) { pm_line_offset_list_line_number(mid, start_line), 0 });
86 }
87
88 if (list->offsets[mid] < cursor) {
89 left = mid + 1;
90 } else {
91 right = mid - 1;
92 }
93 }
94
95 return ((pm_line_column_t) {
96 .line = pm_line_offset_list_line_number(left - 1, start_line),
97 .column = cursor - list->offsets[left - 1]
98 });
99}
A line and column in a string.
A list of offsets of the start of lines in a string.
uint32_t * offsets
The list of offsets.
size_t size
The number of offsets in the list.
size_t capacity
The capacity of the list that has been allocated.