isocpp / isocpp/CppCoreGuidelines

GSL helper functions to convert span of bytes to a well-defined struct

Open
#1,709 18 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
CSS
Stars
45.3k
Forks
5.6k
PR merge metrics
No merged PRs in 30d

Description

gsl::span is widely used in our internal codebases. I see a lot of conversions from a span of bytes to a well-defined struct. Given how often these are used, I am proposing we consider adding the following functions in a SpanExtension namespace in the GSL library, so that developers don't make a mistake when doing such conversions themselves.

    /// <summary>Get a pointer to a structure of type T from an offset within a gsl::span.</summary>
    template<class T, class OffsetType>
    T* get_struct(gsl::span<std::byte> s, OffsetType offset) noexcept;

    /// <summary>Get a gsl::span of type T from a span and truncate any extra content that is not divisable by sizeof(T).</summary>
    template <class T>
    gsl::span<T> convert_span_truncate(gsl::span<std::byte> s) noexcept;

    /// <summary>Convert an address back to a subspan of a gsl::span</summary>
    /// <param name="content">The buffer from which to generate a gsl::span from.</param>
    /// <param name="address">A memory address that is within content.</param>
    /// <param name="countBytes">The count of bytes relative to address that should be included.</param>
    /// <remarks>
    /// For C style functions that return a pointer to some content within a buffer, this can be used to convert it back to a safe span.
    /// </remarks>
    template <class T>
    gsl::span<std::byte> as_subspan(gsl::span<std::byte> content, T* address, size_t countBytes) noexcept;

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 with gsl::span and the proposed SpanExtension entry points: get_struct, convert_span_truncate, and as_subspan. Review existing span conversion patterns and clarify the intended safety and boundary behavior with maintainers; done means the API scope is agreed and the proposed helpers are implemented and verified.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
32/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.