Skip to content

Commit 2da9830

Browse files
committed
py: Make objstr support buffer protocol (read only).
1 parent 0ec6bd4 commit 2da9830

1 file changed

Lines changed: 15 additions & 0 deletions

File tree

py/objstr.c

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -487,6 +487,20 @@ STATIC mp_obj_t str_replace(uint n_args, const mp_obj_t *args) {
487487
return mp_obj_str_builder_end(replaced_str);
488488
}
489489

490+
STATIC machine_int_t str_get_buffer(mp_obj_t self_in, buffer_info_t *bufinfo, int flags) {
491+
if (flags == BUFFER_READ) {
492+
GET_STR_DATA_LEN(self_in, str_data, str_len);
493+
bufinfo->buf = (void*)str_data;
494+
bufinfo->len = str_len;
495+
return 0;
496+
} else {
497+
// can't write to a string
498+
bufinfo->buf = NULL;
499+
bufinfo->len = 0;
500+
return 1;
501+
}
502+
}
503+
490504
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
491505
STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
492506
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, str_split);
@@ -513,6 +527,7 @@ const mp_obj_type_t str_type = {
513527
.binary_op = str_binary_op,
514528
.getiter = mp_obj_new_str_iterator,
515529
.methods = str_type_methods,
530+
.buffer_p = { .get_buffer = str_get_buffer },
516531
};
517532

518533
// Reuses most of methods from str

0 commit comments

Comments
 (0)