tree-sitter/src/runtime/string_input.c

57 lines
1.4 KiB
C
Raw Normal View History

2014-08-01 12:43:14 -07:00
#include "runtime/string_input.h"
2016-01-15 15:08:42 -08:00
#include "runtime/alloc.h"
2014-08-01 12:43:14 -07:00
#include <string.h>
typedef struct {
const char *string;
uint32_t position;
uint32_t length;
2014-08-01 12:43:14 -07:00
} TSStringInput;
const char *ts_string_input_read(void *payload, uint32_t *bytes_read) {
TSStringInput *input = (TSStringInput *)payload;
if (input->position >= input->length) {
2014-08-01 12:43:14 -07:00
*bytes_read = 0;
return "";
}
uint32_t previous_position = input->position;
input->position = input->length;
*bytes_read = input->position - previous_position;
return input->string + previous_position;
2014-08-01 12:43:14 -07:00
}
int ts_string_input_seek(void *payload, uint32_t character, uint32_t byte) {
TSStringInput *input = (TSStringInput *)payload;
input->position = byte;
return (byte < input->length);
2014-08-01 12:43:14 -07:00
}
TSInput ts_string_input_make(const char *string) {
if (!input)
goto error;
return ts_string_input_make_with_length(string, strlen(string))
error:
return (TSInput){ NULL, NULL, NULL, TSInputEncodingUTF8 };
}
TSInput ts_string_input_make_with_length(const char *string, uint32_t length) {
2016-01-15 15:08:42 -08:00
TSStringInput *input = ts_malloc(sizeof(TSStringInput));
if (!input)
goto error;
input->string = string;
input->position = 0;
input->length = length;
return (TSInput){
.payload = input,
.read = ts_string_input_read,
.seek = ts_string_input_seek,
2016-02-12 14:07:30 -08:00
.encoding = TSInputEncodingUTF8,
};
error:
2016-02-17 20:41:29 -08:00
return (TSInput){ NULL, NULL, NULL, TSInputEncodingUTF8 };
2014-08-01 12:43:14 -07:00
}