Skip to content

Commit e62a0fe

Browse files
committed
objstr: Allow to convert any buffer proto object to str.
Original motivation is to support converting bytearrays, but easier to just support buffer protocol at all.
1 parent 31619cc commit e62a0fe

3 files changed

Lines changed: 24 additions & 16 deletions

File tree

py/objstr.c

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -160,15 +160,18 @@ STATIC mp_obj_t str_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t n_kw,
160160
case 3:
161161
{
162162
// TODO: validate 2nd/3rd args
163-
if (!MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
164-
nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "bytes expected"));
163+
if (MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
164+
GET_STR_DATA_LEN(args[0], str_data, str_len);
165+
GET_STR_HASH(args[0], str_hash);
166+
mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_str, NULL, str_len);
167+
o->data = str_data;
168+
o->hash = str_hash;
169+
return o;
170+
} else {
171+
mp_buffer_info_t bufinfo;
172+
mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ);
173+
return mp_obj_new_str(bufinfo.buf, bufinfo.len, false);
165174
}
166-
GET_STR_DATA_LEN(args[0], str_data, str_len);
167-
GET_STR_HASH(args[0], str_hash);
168-
mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_str, NULL, str_len);
169-
o->data = str_data;
170-
o->hash = str_hash;
171-
return o;
172175
}
173176

174177
default:

py/objstrunicode.c

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -142,15 +142,18 @@ STATIC mp_obj_t str_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t n_kw,
142142
case 3:
143143
{
144144
// TODO: validate 2nd/3rd args
145-
if (!MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
146-
nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "bytes expected"));
145+
if (MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
146+
GET_STR_DATA_LEN(args[0], str_data, str_len);
147+
GET_STR_HASH(args[0], str_hash);
148+
mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_str, NULL, str_len);
149+
o->data = str_data;
150+
o->hash = str_hash;
151+
return o;
152+
} else {
153+
mp_buffer_info_t bufinfo;
154+
mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ);
155+
return mp_obj_new_str(bufinfo.buf, bufinfo.len, false);
147156
}
148-
GET_STR_DATA_LEN(args[0], str_data, str_len);
149-
GET_STR_HASH(args[0], str_hash);
150-
mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_str, NULL, str_len);
151-
o->data = str_data;
152-
o->hash = str_hash;
153-
return o;
154157
}
155158

156159
default:

tests/basics/bytearray1.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
print(a[:-1])
1919
print(a[2:3])
2020

21+
print(str(bytearray(b"123"), "utf-8"))
22+
2123
# Comparisons
2224
print(bytearray([1]) == bytearray([1]))
2325
print(bytearray([1]) == bytearray([2]))

0 commit comments

Comments
 (0)