|
| 1 | +from collections.abc import MutableMapping |
| 2 | + |
| 3 | +import cython |
| 4 | +from cython.cimports.av.error import err_check |
| 5 | + |
| 6 | + |
| 7 | +@cython.cclass |
| 8 | +class _Dictionary: |
| 9 | + def __cinit__(self, *args, **kwargs): |
| 10 | + for arg in args: |
| 11 | + self.update(arg) |
| 12 | + if kwargs: |
| 13 | + self.update(kwargs) |
| 14 | + |
| 15 | + def __dealloc__(self): |
| 16 | + if self.ptr != cython.NULL: |
| 17 | + lib.av_dict_free(cython.address(self.ptr)) |
| 18 | + |
| 19 | + def __getitem__(self, key: cython.str): |
| 20 | + element = cython.declare( |
| 21 | + cython.pointer[lib.AVDictionaryEntry], |
| 22 | + lib.av_dict_get(self.ptr, key, cython.NULL, 0), |
| 23 | + ) |
| 24 | + if element == cython.NULL: |
| 25 | + raise KeyError(key) |
| 26 | + return element.value |
| 27 | + |
| 28 | + def __setitem__(self, key: cython.str, value: cython.str): |
| 29 | + err_check(lib.av_dict_set(cython.address(self.ptr), key, value, 0)) |
| 30 | + |
| 31 | + def __delitem__(self, key: cython.str): |
| 32 | + err_check(lib.av_dict_set(cython.address(self.ptr), key, cython.NULL, 0)) |
| 33 | + |
| 34 | + def __len__(self): |
| 35 | + return err_check(lib.av_dict_count(self.ptr)) |
| 36 | + |
| 37 | + def __iter__(self): |
| 38 | + element = cython.declare(cython.pointer[lib.AVDictionaryEntry], cython.NULL) |
| 39 | + while True: |
| 40 | + element = lib.av_dict_get(self.ptr, "", element, lib.AV_DICT_IGNORE_SUFFIX) |
| 41 | + if element == cython.NULL: |
| 42 | + break |
| 43 | + yield element.key |
| 44 | + |
| 45 | + def __repr__(self): |
| 46 | + return f"bv.Dictionary({dict(self)!r})" |
| 47 | + |
| 48 | + def copy(self): |
| 49 | + other = cython.declare(_Dictionary, Dictionary()) |
| 50 | + lib.av_dict_copy(cython.address(other.ptr), self.ptr, 0) |
| 51 | + return other |
| 52 | + |
| 53 | + |
| 54 | +class Dictionary(_Dictionary, MutableMapping): |
| 55 | + pass |
| 56 | + |
| 57 | + |
| 58 | +@cython.cfunc |
| 59 | +def wrap_dictionary(input_: cython.pointer[lib.AVDictionary]) -> _Dictionary: |
| 60 | + output = cython.declare(_Dictionary, Dictionary()) |
| 61 | + output.ptr = input_ |
| 62 | + return output |
0 commit comments