From 5b2806dc311a02982f133647238e8d6618c04211 Mon Sep 17 00:00:00 2001 From: Stefan Gula Date: Fri, 1 Mar 2024 14:37:04 +0100 Subject: [PATCH] context: add add_to_dict/remove_from_dict APIs This patch adds add_to_dict and remove_from_dict API, which allows to create internal string reference within the context Signed-off-by: Stefan Gula --- cffi/cdefs.h | 3 +++ libyang/context.py | 10 ++++++++++ tests/test_context.py | 8 ++++++++ 3 files changed, 21 insertions(+) diff --git a/cffi/cdefs.h b/cffi/cdefs.h index 4d461162..39f23723 100644 --- a/cffi/cdefs.h +++ b/cffi/cdefs.h @@ -1032,6 +1032,9 @@ LY_ERR lys_parse(struct ly_ctx *, struct ly_in *, LYS_INFORMAT, const char **, s LY_ERR ly_ctx_new_ylpath(const char *, const char *, LYD_FORMAT, int, struct ly_ctx **); LY_ERR ly_ctx_get_yanglib_data(const struct ly_ctx *, struct lyd_node **, const char *, ...); +LY_ERR lydict_insert(const struct ly_ctx *, const char *, size_t, const char **); +LY_ERR lydict_remove(const struct ly_ctx *, const char *); + struct lyd_meta { struct lyd_node *parent; struct lyd_meta *next; diff --git a/libyang/context.py b/libyang/context.py index eefc4e05..85796d44 100644 --- a/libyang/context.py +++ b/libyang/context.py @@ -463,3 +463,13 @@ def __iter__(self) -> Iterator[Module]: while mod: yield Module(self, mod) mod = lib.ly_ctx_get_module_iter(self.cdata, idx) + + def add_to_dict(self, orig_str: str) -> Any: + cstr = ffi.new("char **") + ret = lib.lydict_insert(self.cdata, str2c(orig_str), 0, cstr) + if ret != lib.LY_SUCCESS: + raise LibyangError("Unable to insert string into context dictionary") + return cstr[0] + + def remove_from_dict(self, orig_str: str) -> None: + lib.lydict_remove(self.cdata, str2c(orig_str)) diff --git a/tests/test_context.py b/tests/test_context.py index 59839284..f43bf1cf 100644 --- a/tests/test_context.py +++ b/tests/test_context.py @@ -5,6 +5,7 @@ import unittest from libyang import Context, LibyangError, Module, SLeaf, SLeafList +from libyang.util import c2str YANG_DIR = os.path.join(os.path.dirname(__file__), "yang") @@ -111,3 +112,10 @@ def test_ctx_leafref_extended(self): with Context(YANG_DIR, leafref_extended=True) as ctx: mod = ctx.load_module("yolo-leafref-extended") self.assertIsInstance(mod, Module) + + def test_context_dict(self): + with Context(YANG_DIR) as ctx: + orig_str = "teststring" + handle = ctx.add_to_dict(orig_str) + self.assertEqual(orig_str, c2str(handle)) + ctx.remove_from_dict(orig_str)