Skip to content

Commit 41a4f74

Browse files
stewegsamuel-gauthier
authored andcommitted
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. Closes: #102 Signed-off-by: Stefan Gula <steweg@gmail.com>
1 parent b7adea4 commit 41a4f74

File tree

3 files changed

+21
-0
lines changed

3 files changed

+21
-0
lines changed

cffi/cdefs.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1071,6 +1071,9 @@ LY_ERR lys_parse(struct ly_ctx *, struct ly_in *, LYS_INFORMAT, const char **, s
10711071
LY_ERR ly_ctx_new_ylpath(const char *, const char *, LYD_FORMAT, int, struct ly_ctx **);
10721072
LY_ERR ly_ctx_get_yanglib_data(const struct ly_ctx *, struct lyd_node **, const char *, ...);
10731073

1074+
LY_ERR lydict_insert(const struct ly_ctx *, const char *, size_t, const char **);
1075+
LY_ERR lydict_remove(const struct ly_ctx *, const char *);
1076+
10741077
struct lyd_meta {
10751078
struct lyd_node *parent;
10761079
struct lyd_meta *next;

libyang/context.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -465,3 +465,13 @@ def __iter__(self) -> Iterator[Module]:
465465
while mod:
466466
yield Module(self, mod)
467467
mod = lib.ly_ctx_get_module_iter(self.cdata, idx)
468+
469+
def add_to_dict(self, orig_str: str) -> Any:
470+
cstr = ffi.new("char **")
471+
ret = lib.lydict_insert(self.cdata, str2c(orig_str), 0, cstr)
472+
if ret != lib.LY_SUCCESS:
473+
raise LibyangError("Unable to insert string into context dictionary")
474+
return cstr[0]
475+
476+
def remove_from_dict(self, orig_str: str) -> None:
477+
lib.lydict_remove(self.cdata, str2c(orig_str))

tests/test_context.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import unittest
66

77
from libyang import Context, LibyangError, Module, SLeaf, SLeafList
8+
from libyang.util import c2str
89

910

1011
YANG_DIR = os.path.join(os.path.dirname(__file__), "yang")
@@ -111,3 +112,10 @@ def test_ctx_leafref_extended(self):
111112
with Context(YANG_DIR, leafref_extended=True) as ctx:
112113
mod = ctx.load_module("yolo-leafref-extended")
113114
self.assertIsInstance(mod, Module)
115+
116+
def test_context_dict(self):
117+
with Context(YANG_DIR) as ctx:
118+
orig_str = "teststring"
119+
handle = ctx.add_to_dict(orig_str)
120+
self.assertEqual(orig_str, c2str(handle))
121+
ctx.remove_from_dict(orig_str)

0 commit comments

Comments
 (0)