__codecs.pyx 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import six
  2. from libcpp cimport bool
  3. from util.generic.string cimport TString, TStringBuf
  4. def to_bytes(s):
  5. try:
  6. return s.encode('utf-8')
  7. except AttributeError:
  8. pass
  9. return s
  10. def from_bytes(s):
  11. if six.PY3:
  12. return s.decode('utf-8')
  13. return s
  14. cdef extern from "library/cpp/blockcodecs/codecs.h" namespace "NBlockCodecs":
  15. cdef cppclass ICodec:
  16. void Encode(TStringBuf data, TString& res) nogil
  17. void Decode(TStringBuf data, TString& res) nogil
  18. cdef const ICodec* Codec(const TStringBuf& name) except +
  19. cdef TString ListAllCodecsAsString() except +
  20. def dumps(name, data):
  21. name = to_bytes(name)
  22. cdef const ICodec* codec = Codec(TStringBuf(name, len(name)))
  23. cdef TString res
  24. cdef TStringBuf cdata = TStringBuf(data, len(data))
  25. with nogil:
  26. codec.Encode(cdata, res)
  27. return res.c_str()[:res.length()]
  28. def loads(name, data):
  29. name = to_bytes(name)
  30. cdef const ICodec* codec = Codec(TStringBuf(name, len(name)))
  31. cdef TString res
  32. cdef TStringBuf cdata = TStringBuf(data, len(data))
  33. with nogil:
  34. codec.Decode(cdata, res)
  35. return res.c_str()[:res.length()]
  36. def list_all_codecs():
  37. cdef TString res = ListAllCodecsAsString()
  38. return from_bytes(res.c_str()[:res.length()]).split(',')