MCPcopy Create free account
hub / github.com/lief-project/LIEF / from_python

Method from_python

api/python/src/pyIOStream.cpp:28–68  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

26PyIOStream& PyIOStream::operator=(PyIOStream&& other) = default;
27
28result<PyIOStream> PyIOStream::from_python(nb::object object) {
29 const nb::module_ mod_io = nb::module_::import_("io");
30 const nb::object IOBase = mod_io.attr("IOBase");
31
32 if (!nb::isinstance(object, IOBase)) {
33 logging::log(logging::LEVEL::ERR,
34 "The provided io object does not sub-class io.IOBase");
35 return make_error_code(lief_errors::read_error);
36 }
37
38 if (!nb::hasattr(object, "read") && !nb::hasattr(object, "readinto")) {
39 logging::log(logging::LEVEL::ERR,
40 "The provided io object does not implement read() or readinto()");
41 return make_error_code(lief_errors::read_error);
42 }
43
44 auto seek = object.attr("seek");
45 seek(0, PY_SEEK_SET);
46 seek(0, PY_SEEK_END);
47 const auto size = nb::cast<size_t>(object.attr("tell")());
48
49 if (size == 0) {
50 return PyIOStream(std::move(object), {});
51 }
52
53 std::vector<uint8_t> data;
54 data.resize(size);
55
56 seek(0, PY_SEEK_SET);
57 if (nb::hasattr(object, "readinto")) {
58 auto view = nb::memoryview::from_memory(data.data(), size);
59 object.attr("readinto")(view);
60 }
61 else if (nb::hasattr(object, "read")) {
62 auto content = nb::cast<nb::bytes>(object.attr("read")(size));
63 std::string tmp(content.c_str(), content.size());
64 std::move(std::begin(tmp), std::end(tmp), data.data());
65 }
66
67 return PyIOStream(std::move(object), std::move(data));
68}
69
70PyIOStream::PyIOStream(nb::object io, std::vector<uint8_t> data) :
71 VectorStream(std::move(data)),

Callers

nothing calls this directly

Calls 8

make_error_codeFunction · 0.85
PyIOStreamClass · 0.85
c_strMethod · 0.80
logFunction · 0.50
beginFunction · 0.50
endFunction · 0.50
dataMethod · 0.45
sizeMethod · 0.45

Tested by

no test coverage detected