From 2d02383ae774f1eef9898e48a8d6ad1fca50d950 Mon Sep 17 00:00:00 2001 From: IrfanMohammad Date: Tue, 22 Aug 2023 11:56:51 +0000 Subject: [PATCH] Add lyd_print_mem_len API to return printed size It can be useful to know how many bytes were written, and avoid an expensive and redundant strlen by the application. --- src/printer_data.c | 18 ++++++++++++++++++ src/printer_data.h | 5 +++++ 2 files changed, 23 insertions(+) diff --git a/src/printer_data.c b/src/printer_data.c index ea330c739..d44a3d25a 100644 --- a/src/printer_data.c +++ b/src/printer_data.c @@ -102,6 +102,24 @@ lyd_print_mem(char **strp, const struct lyd_node *root, LYD_FORMAT format, uint3 return ret; } +LIBYANG_API_DEF LY_ERR +lyd_print_mem_len(char **strp, const struct lyd_node *root, LYD_FORMAT format, uint32_t options, size_t *len) +{ + LY_ERR ret; + struct ly_out *out; + + LY_CHECK_ARG_RET(NULL, strp && len, LY_EINVAL); + + /* init */ + *strp = NULL; + + LY_CHECK_RET(ly_out_new_memory(strp, 0, &out)); + ret = lyd_print_(out, root, format, options); + *len = out->printed; + ly_out_free(out, NULL, 0); + return ret; +} + LIBYANG_API_DEF LY_ERR lyd_print_fd(int fd, const struct lyd_node *root, LYD_FORMAT format, uint32_t options) { diff --git a/src/printer_data.h b/src/printer_data.h index fb2a5fb50..6823d843f 100644 --- a/src/printer_data.h +++ b/src/printer_data.h @@ -133,6 +133,11 @@ LIBYANG_API_DECL LY_ERR lyd_print_tree(struct ly_out *out, const struct lyd_node */ LIBYANG_API_DECL LY_ERR lyd_print_mem(char **strp, const struct lyd_node *root, LYD_FORMAT format, uint32_t options); +/** + * @brief Same as lyd_print_mem but also return the length of buffer written + */ +LIBYANG_API_DEF LY_ERR lyd_print_mem_len(char **strp, const struct lyd_node *root, LYD_FORMAT format, uint32_t options, size_t *len); + /** * @brief Print data tree in the specified format. *