diff --git a/include/zenoh-pico/api/primitives.h b/include/zenoh-pico/api/primitives.h index f0a5c1c19..93b0116a8 100644 --- a/include/zenoh-pico/api/primitives.h +++ b/include/zenoh-pico/api/primitives.h @@ -1533,6 +1533,18 @@ int8_t z_info_routers_zid(const z_loaned_session_t *zs, z_moved_closure_zid_t *c */ z_id_t z_info_zid(const z_loaned_session_t *zs); +/** + * Converts a Zenoh ID into a string for print purposes. + * + * Parameters: + * str: Pointer to uninitialized :c:type:`z_owned_string_t` to store the string. + * id: Pointer to the id to convert. + * + * Return: + * ``0`` if operation successful, ``negative value`` otherwise. + */ +z_result_t z_id_to_string(z_owned_string_t *str, z_id_t *id); + /** * Gets the keyexpr from a sample by aliasing it. * diff --git a/src/api/api.c b/src/api/api.c index 3188ea561..3b9aae0ea 100644 --- a/src/api/api.c +++ b/src/api/api.c @@ -968,6 +968,15 @@ int8_t z_info_routers_zid(const z_loaned_session_t *zs, z_moved_closure_zid_t *c z_id_t z_info_zid(const z_loaned_session_t *zs) { return _Z_RC_IN_VAL(zs)->_local_zid; } +z_result_t z_id_to_string(z_owned_string_t *str, z_id_t *id) { + _z_slice_t buf = _z_slice_alias_buf(id->id, sizeof(id->id)); + str->_val = _z_string_convert_bytes(&buf); + if (!_z_string_check(&str->_val)) { + return _Z_ERR_SYSTEM_OUT_OF_MEMORY; + } + return _Z_RES_OK; +} + const z_loaned_keyexpr_t *z_sample_keyexpr(const z_loaned_sample_t *sample) { return &sample->keyexpr; } z_sample_kind_t z_sample_kind(const z_loaned_sample_t *sample) { return sample->kind; } const z_loaned_bytes_t *z_sample_payload(const z_loaned_sample_t *sample) { return &sample->payload; } diff --git a/src/collections/string.c b/src/collections/string.c index 88f9bbd91..0e8129be4 100644 --- a/src/collections/string.c +++ b/src/collections/string.c @@ -119,17 +119,12 @@ _z_string_t _z_string_convert_bytes(const _z_slice_t *bs) { return s; } - if (s_val != NULL) { - const char c[] = "0123456789ABCDEF"; - for (size_t i = 0; i < bs->len; i++) { - s_val[i * (size_t)2] = c[(bs->start[i] & (uint8_t)0xF0) >> (uint8_t)4]; - s_val[(i * (size_t)2)] = c[bs->start[i] & (uint8_t)0x0F]; - } - } else { - len = 0; + const char c[] = "0123456789ABCDEF"; + for (size_t i = 0; i < bs->len; i++) { + s_val[i * (size_t)2] = c[(bs->start[i] & (uint8_t)0xF0) >> (uint8_t)4]; + s_val[(i * (size_t)2) + 1] = c[bs->start[i] & (uint8_t)0x0F]; } s._slice = _z_slice_from_buf_custom_deleter((const uint8_t *)s_val, len, _z_delete_context_default()); - return s; }