Skip to content

Commit

Permalink
context: add add_to_dict/remove_from_dict APIs
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
steweg authored and samuel-gauthier committed Aug 2, 2024
1 parent b7adea4 commit 41a4f74
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 0 deletions.
3 changes: 3 additions & 0 deletions cffi/cdefs.h
Original file line number Diff line number Diff line change
Expand Up @@ -1071,6 +1071,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;
Expand Down
10 changes: 10 additions & 0 deletions libyang/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -465,3 +465,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))
8 changes: 8 additions & 0 deletions tests/test_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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)

0 comments on commit 41a4f74

Please sign in to comment.