From f3df22410813a273118b860f879cd930773602f8 Mon Sep 17 00:00:00 2001 From: arvidn Date: Thu, 4 Aug 2022 14:19:42 -0700 Subject: [PATCH] add unchecked version of GTElement.from_bytes --- python-bindings/pythonbindings.cpp | 18 ++++++++++++++++++ src/elements.cpp | 10 ++++++++-- src/elements.hpp | 1 + 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/python-bindings/pythonbindings.cpp b/python-bindings/pythonbindings.cpp index 8a715fe28..32d237080 100644 --- a/python-bindings/pythonbindings.cpp +++ b/python-bindings/pythonbindings.cpp @@ -676,6 +676,24 @@ PYBIND11_MODULE(blspy, m) py::gil_scoped_release release; return GTElement::FromBytes(data); }) + .def( + "from_bytes_unchecked", + [](py::buffer const b) { + py::buffer_info info = b.request(); + if (info.format != py::format_descriptor::format() || + info.ndim != 1) + throw std::runtime_error("Incompatible buffer format!"); + + if ((int)info.size != GTElement::SIZE) { + throw std::invalid_argument( + "Length of bytes object not equal to GTElement::SIZE"); + } + auto data_ptr = reinterpret_cast(info.ptr); + std::array data; + std::copy(data_ptr, data_ptr + GTElement::SIZE, data.data()); + py::gil_scoped_release release; + return GTElement::FromBytesUnchecked(data); + }) .def("unity", >Element::Unity) .def(py::self == py::self) .def(py::self != py::self) diff --git a/src/elements.cpp b/src/elements.cpp index b27a26597..bf3d76264 100644 --- a/src/elements.cpp +++ b/src/elements.cpp @@ -449,14 +449,20 @@ G2Element operator*(const bn_t& k, const G2Element& a) { return a * k; } const size_t GTElement::SIZE; GTElement GTElement::FromBytes(Bytes const bytes) +{ + GTElement ele = GTElement::FromBytesUnchecked(bytes); + if (gt_is_valid(*(gt_t*)&ele) == 0) + throw std::invalid_argument("GTElement is invalid"); + return ele; +} + +GTElement GTElement::FromBytesUnchecked(Bytes const bytes) { if (bytes.size() != SIZE) { throw std::invalid_argument("GTElement::FromBytes: Invalid size"); } GTElement ele = GTElement(); gt_read_bin(ele.r, bytes.begin(), GTElement::SIZE); - if (gt_is_valid(*(gt_t*)&ele) == 0) - throw std::invalid_argument("GTElement is invalid"); BLS::CheckRelicErrors(); return ele; } diff --git a/src/elements.hpp b/src/elements.hpp index 5c0a203cd..a14711590 100644 --- a/src/elements.hpp +++ b/src/elements.hpp @@ -118,6 +118,7 @@ class GTElement { public: static const size_t SIZE = 384; static GTElement FromBytes(Bytes bytes); + static GTElement FromBytesUnchecked(Bytes bytes); static GTElement FromByteVector(const std::vector &bytevec); static GTElement FromNative(const gt_t *element); static GTElement Unity(); // unity