pybind / pybind/pybind11

[FEAT] Get a read-only view of the data in py::bytes

Open
#2,517 4 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
C++
Stars
18k
Forks
2.3k
Avg merge
5d 17h
Merged PRs (30d)
10

Description

Looking at the pybind11::bytes class (in pytypes.h), it is not obvious how to get the data out without first making an unnecessary std::string copy of it.

This function is not terribly useful:

operator std::string() const {
    char *buffer;
    ssize_t length;
    if (PYBIND11_BYTES_AS_STRING_AND_SIZE(m_ptr, &buffer, &length))
        pybind11_fail("Unable to extract bytes contents!");
    return std::string(buffer, (size_t) length);
}

More useful:

operator byte_view() const {
    char *buffer;
    ssize_t length;
    if (PYBIND11_BYTES_AS_STRING_AND_SIZE(m_ptr, &buffer, &length))
        pybind11_fail("Unable to extract contents of bytes object!");
    return { as_unsigned(buffer), as_unsigned(length) };
}
// Boiler plate
using byte_view = std::basic_string_view<uint8_t>;
size_t as_unsigned(ssize_t val) { return static_cast<size_t>(val); }
const uint8_t *as_unsigned(const char *s) { return reinterpret_cast<const uint8_t *>(s); }

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in pytypes.h by reading pybind11::bytes and its existing operator std::string() implementation, then assess the proposed read-only byte_view interface and its ownership and type-conversion implications. Done means providing a documented way to view the bytes data without an unnecessary std::string copy, with behavior consistent with the existing error handling.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, python
Domain
api, backend
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.