Skip to content

Commit

Permalink
add unchecked version of GTElement.from_bytes
Browse files Browse the repository at this point in the history
  • Loading branch information
arvidn authored and UdjinM6 committed Sep 6, 2022
1 parent 7089a38 commit f3df224
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
18 changes: 18 additions & 0 deletions python-bindings/pythonbindings.cpp
Expand Up @@ -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<uint8_t>::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<const uint8_t *>(info.ptr);
std::array<uint8_t, GTElement::SIZE> data;
std::copy(data_ptr, data_ptr + GTElement::SIZE, data.data());
py::gil_scoped_release release;
return GTElement::FromBytesUnchecked(data);
})
.def("unity", &GTElement::Unity)
.def(py::self == py::self)
.def(py::self != py::self)
Expand Down
10 changes: 8 additions & 2 deletions src/elements.cpp
Expand Up @@ -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;
}
Expand Down
1 change: 1 addition & 0 deletions src/elements.hpp
Expand Up @@ -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<uint8_t> &bytevec);
static GTElement FromNative(const gt_t *element);
static GTElement Unity(); // unity
Expand Down

0 comments on commit f3df224

Please sign in to comment.