Guidelines Support Library

Overview

GSL: Guidelines Support Library

Build Status

The Guidelines Support Library (GSL) contains functions and types that are suggested for use by the C++ Core Guidelines maintained by the Standard C++ Foundation. This repo contains Microsoft's implementation of GSL.

The entire implementation is provided inline in the headers under the gsl directory. The implementation generally assumes a platform that implements C++14 support.

While some types have been broken out into their own headers (e.g. gsl/span), it is simplest to just include gsl/gsl and gain access to the entire library.

NOTE: We encourage contributions that improve or refine any of the types in this library as well as ports to other platforms. Please see CONTRIBUTING.md for more information about contributing.

Project Code of Conduct

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

Usage of Third Party Libraries

This project makes use of the Google Test testing library. Please see the ThirdPartyNotices.txt file for details regarding the licensing of Google Test.

Supported features

Microsoft GSL implements the following from the C++ Core Guidelines:

Feature Supported? Description
1. Views
owner an alias for a raw pointer
not_null restricts a pointer / smart pointer to hold non-null values
span a view over a contiguous sequence of memory. Based on the standardized verison of std::span, however gsl::span enforces bounds checking. See the wiki for additional information.
span_p spans a range starting from a pointer to the first place for which the predicate is true
basic_zstring A pointer to a C-string (zero-terminated array) with a templated char type
zstring An alias to basic_zstring with dynamic extent and a char type of char
czstring An alias to basic_zstring with dynamic extent and a char type of const char
wzstring An alias to basic_zstring with dynamic extent and a char type of wchar_t
cwzstring An alias to basic_zstring with dynamic extent and a char type of const wchar_t
u16zstring An alias to basic_zstring with dynamic extent and a char type of char16_t
cu16zstring An alias to basic_zstring with dynamic extent and a char type of const char16_t
u32zstring An alias to basic_zstring with dynamic extent and a char type of char32_t
cu32zstring An alias to basic_zstring with dynamic extent and a char type of const char32_t
2. Owners
unique_ptr an alias to std::unique_ptr
shared_ptr an alias to std::shared_ptr
stack_array a stack-allocated array
dyn_array a heap-allocated array
3. Assertions
Expects a precondition assertion; on failure it terminates
Ensures a postcondition assertion; on failure it terminates
4. Utilities
move_owner a helper function that moves one owner to the other
byte either an alias to std::byte or a byte type
final_action a RAII style class that invokes a functor on its destruction
finally a helper function instantiating final_action
GSL_SUPPRESS a macro that takes an argument and turns it into [[gsl::suppress(x)]] or [[gsl::suppress("x")]]
[[implicit]] a "marker" to put on single-argument constructors to explicitly make them non-explicit
index a type to use for all container and array indexing (currently an alias for std::ptrdiff_t)
joining_thread a RAII style version of std::thread that joins
narrow a checked version of narrow_cast; it can throw narrowing_error
narrow_cast a narrowing cast for values and a synonym for static_cast
narrowing_error a custom exception type thrown by narrow()
5. Concepts

The following features do not exist in or have been removed from the C++ Core Guidelines:

Feature Supported? Description
strict_not_null A stricter version of not_null with explicit constructors
multi_span Deprecated. Multi-dimensional span.
strided_span Deprecated. Support for this type has been discontinued.
basic_string_span Deprecated. Like span but for strings with a templated char type
string_span Deprecated. An alias to basic_string_span with a char type of char
cstring_span Deprecated. An alias to basic_string_span with a char type of const char
wstring_span Deprecated. An alias to basic_string_span with a char type of wchar_t
cwstring_span Deprecated. An alias to basic_string_span with a char type of const wchar_t
u16string_span Deprecated. An alias to basic_string_span with a char type of char16_t
cu16string_span Deprecated. An alias to basic_string_span with a char type of const char16_t
u32string_span Deprecated. An alias to basic_string_span with a char type of char32_t
cu32string_span Deprecated. An alias to basic_string_span with a char type of const char32_t

This is based on CppCoreGuidelines semi-specification.

Quick Start

Supported Compilers

The GSL officially supports the current and previous major release of MSVC, GCC, Clang, and XCode's Apple-Clang. See our latest test results for the most up-to-date list of supported configurations.

Compiler Toolset Versions Currently Tested
XCode 11.4 & 10.3
GCC 9 & 8
Clang 11 & 10
Visual Studio with MSVC VS2017 (15.9) & VS2019 (16.4)
Visual Studio with LLVM VS2017 (Clang 9) & VS2019 (Clang 10)

If you successfully port GSL to another platform, we would love to hear from you!

  • Submit an issue specifying the platform and target.
  • Consider contributing your changes by filing a pull request with any necessary changes.
  • If at all possible, add a CI/CD step and add the button to the table below!
Target CI/CD Status
iOS CI_iOS
Android CI_Android

Note: These CI/CD steps are run with each pull request, however failures in them are non-blocking.

Building the tests

To build the tests, you will require the following:

  • CMake, version 3.1.3 (3.2.3 for AppleClang) or later to be installed and in your PATH.

These steps assume the source code of this repository has been cloned into a directory named c:\GSL.

  1. Create a directory to contain the build outputs for a particular architecture (we name it c:\GSL\build-x86 in this example).

     cd GSL
     md build-x86
     cd build-x86
    
  2. Configure CMake to use the compiler of your choice (you can see a list by running cmake --help).

     cmake -G "Visual Studio 15 2017" c:\GSL
    
  3. Build the test suite (in this case, in the Debug configuration, Release is another good choice).

     cmake --build . --config Debug
    
  4. Run the test suite.

     ctest -C Debug
    

All tests should pass - indicating your platform is fully supported and you are ready to use the GSL types!

Building GSL - Using vcpkg

You can download and install GSL using the vcpkg dependency manager:

git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.sh
./vcpkg integrate install
vcpkg install ms-gsl

The GSL port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please create an issue or pull request on the vcpkg repository.

Using the libraries

As the types are entirely implemented inline in headers, there are no linking requirements.

You can copy the gsl directory into your source tree so it is available to your compiler, then include the appropriate headers in your program.

Alternatively set your compiler's include path flag to point to the GSL development folder (c:\GSL\include in the example above) or installation folder (after running the install). Eg.

MSVC++

/I c:\GSL\include

GCC/clang

-I$HOME/dev/GSL/include

Include the library using:

#include <gsl/gsl>

Usage in CMake

The library provides a Config file for CMake, once installed it can be found via

find_package(Microsoft.GSL CONFIG)

Which, when successful, will add library target called Microsoft.GSL::GSL which you can use via the usual target_link_libraries mechanism.

FetchContent

If you are using cmake version 3.11+ you can use the offical FetchContent module. This allows you to easily incorporate GSL into your project.

# NOTE: This example uses cmake version 3.14 (FetchContent_MakeAvailable).
# Since it streamlines the FetchContent process
cmake_minimum_required(VERSION 3.14)

include(FetchContent)

# In this example we are picking a specific tag.
# You can also pick a specific commit, if you need to.
FetchContent_Declare(GSL
    GIT_REPOSITORY "https://github.com/microsoft/GSL"
    GIT_TAG "v3.1.0"
)

FetchContent_MakeAvailable(GSL)

# Now you can link against the GSL interface library
add_executable(foobar)

# Link against the interface library (IE header only library)
target_link_libraries(foobar PRIVATE GSL)

Debugging visualization support

For Visual Studio users, the file GSL.natvis in the root directory of the repository can be added to your project if you would like more helpful visualization of GSL types in the Visual Studio debugger than would be offered by default.

If you are using cmake this will be done automatically for you. See 'GSL_VS_ADD_NATIVE_VISUALIZERS'

Comments
  • array_view not possible with incomplete Classes

    array_view not possible with incomplete Classes

    Hello,

    I use a small simple class that takes a pointer and a size for wrapping normal arrays, quite the same what array_view is designed to solve in a much more generic fashion. I found a drawback compared to using a simple class, and that is that array_view does not work with incomplete classes. I dont know if its possible to fix this via templates specialization and sfinae voodoo, but would be really nice if this use-case is covered aswell

    #include <array_view.h>
    class CIncomplete;
    
    void foo(gsl::array_view<CIncomplete> s); // OK
    gsl::array_view<CIncomplete> s; // Not OK (says clang 3.6 and gcc 5.1 )
    
    resolved 
    opened by nolange 67
  • array_view should have a constructor that takes an initializer_list

    array_view should have a constructor that takes an initializer_list

    I started trying to convert some code that provides safety / convenience wrappers around D3D API calls over to use gsl::array_view and ran into a problem that means I can't support the interface I want. I have calling code that looks like this:

    // defined somewhere 
    Microsoft::WRL::ComPtr<ID3D11DeviceContext> context;
    Micrsofot::WRL::ComPtr<ID3D11Buffer> vertices;
    UINT stride;
    
    // calling code somewhere else
    IASetVertexBuffers(context, 0, {vertices.Get()}, {stride});
    

    And a wrapper around ID3D11DeviceContext::IASetVertexBuffers() with signature:

    void IASetVertexBuffers(
      [in]                 UINT                StartSlot,
      [in]                 UINT                NumBuffers,
      [in, optional]       ID3D11Buffer *const *ppVertexBuffers,
      [in, optional] const UINT                *pStrides,
      [in, optional] const UINT                *pOffsets
    );
    

    That currently looks like this:

    template <typename Context, typename Buffers = std::initializer_list<ID3D11Buffer*>,
              typename Strides = std::initializer_list<UINT>>
    void IASetVertexBuffers(const Context& context, unsigned startSlot, const Buffers& buffers,
                            const Strides& strides) {
        UINT offsets[D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT] = {};
        context->IASetVertexBuffers(UINT(startSlot), UINT(std::size(buffers)), std::begin(buffers),
                                    std::begin(strides), std::begin(offsets));
    };
    

    This wrapper lets me directly pass a braced init list as an argument for buffers and strides (the default std::initializer_list template arguments allow the compiler to deduce the type correctly in this case) or any other Container type that supports begin() and end().

    I'd like to convert the buffers and strides parameters to gsl::array_views over the appropriate types. Currently however gsl::array_view has no constructor taking an std::initializer_list which means I can't get my desired call-site syntax of directly passing a braced init list and having a gsl::array_view implicitly constructed from it. I could write my own as_array_view helper but I hate unnecessary typing at the call site :-)

    I think a gsl::array_view constructor taking an std::initializer_list would give me the call syntax I'd like but I may be missing some subtlety that means that wouldn't work. Still, one way or another I'd like to be able to directly pass braced init lists to functions taking a gsl::array_view of the corresponding type.

    declined 
    opened by mattnewport 44
  • 2fc94db made gsl::not_null constructor explicit, why?

    2fc94db made gsl::not_null constructor explicit, why?

    Since 2fc94db3ebfb1b066edeafac1837f34d6111bff4, this program does not work anymore without explicit cast to not_null (here tested with clang 5.0.2 on linux with -std=c++14):

    #include <gsl/pointers>
    #include <iostream>
    
    void f(gsl::not_null<const int *> i) {
      std::cout << *i << '\n';
    }
    
    int main() {
      int i = 42;
      f(&i); // no matching function for call to 'f'
             // note: candidate function not viable: no known conversion from 'int *' to 'gsl::not_null<const int *>' for 1st argument
      return 0;
    }
    

    If this is really wanted, could you explain why?

    Kind regards

    opened by kivadiu 31
  • not_null has converting constructors?

    not_null has converting constructors?

    It seems to me that offering a conversion from T to not_null<T> looses the potential to detect certain bugs at compile-time.

    if I have a function that returns a raw (potentially null) pointer, and I carelessly pass it to a function taking not_null it will compile fine, and will try report a bug at run-time when it is likely too late.

    Instead, if the constructor from T were explicit, an inadvertent assignment:

    use_ptr(make_ptr());
    

    would be impossible, and I would be forced to explicitly require a potentially unsafe conversion:

    use_ptr(not_null<T>{make_ptr()});
    

    This would be a kind of the signature: by writing this cast, I am taking the responsibility for guaranteeing that the raw pointer will not be null. If it is not the case, you will know that I did it consciously.

    See also CppCoreGuidelines issue: https://github.com/isocpp/CppCoreGuidelines/issues/767

    open 
    opened by akrzemi1 31
  • Name collision with GNU Scientific Library

    Name collision with GNU Scientific Library

    Guidelines Support Library shorthand "GSL" if will get widespread could be ambiguous in projects that use GNU Scientific Library (shorthand is GSL). Namespace gsl:: is used for some C++ wrappers for GNU Scientific Library. Same goes for macro prefixed with GSL_. Related to #9 #38

    resolved 
    opened by ivan-aksamentov 27
  • Broken test for constexpr support

    Broken test for constexpr support

    You have this -

    #if _MSC_VER < 1910 #pragma push_macro("constexpr") #define constexpr /constexpr/ #define GSL_USE_STATIC_CONSTEXPR_WORKAROUND #endif // _MSC_VER < 1910 #else // _MSC_VER // See if we have enough C++17 power to use a static constexpr data member // without needing an out-of-line definition #if !(defined(__cplusplus) && (__cplusplus >= 201703L)) #define GSL_USE_STATIC_CONSTEXPR_WORKAROUND #endif // !(defined(__cplusplus) && (__cplusplus >= 201703L)) #endif // _MSC_VER

    Which will fail, because Visual Studio doesn't correctly set __cplusplus value.

    A correct, cross-platform way to do this can be found in https://github.com/dcleblanc/SafeInt/commits/master/SafeInt.hpp from lines 19-128

    I don't assert that my approach in SafeInt is ideal, but it definitely works, I've tested it.

    opened by dcleblanc 26
  • array_view as_bytes() and as_writeable_bytes() appear to invoke undefined behaviour in current implementation

    array_view as_bytes() and as_writeable_bytes() appear to invoke undefined behaviour in current implementation

    The current implementations of array_view's as_bytes() and as_writeable_bytes() do this:

    // as_bytes()
    return { reinterpret_cast<const byte*>(this->data()), this->bytes() };
    // as_writeable_bytes()
    return { reinterpret_cast<byte*>(this->data()), this->bytes() };
    

    Where byte is defined as:

    enum class byte : std::uint8_t {};
    

    This appears to invoke undefined behaviour if the array_view is used to access memory as per 3.10.10:

    If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:

    • the dynamic type of the object,
    • a cv-qualified version of the dynamic type of the object,
    • a type similar (as defined in 4.4) to the dynamic type of the object,
    • a type that is the signed or unsigned type corresponding to the dynamic type of the object,
    • a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object,
    • an aggregate or union type that includes one of the aforementioned types among its elements or nonstatic data members (including, recursively, an element or non-static data member of a subaggregate or contained union),
    • a type that is a (possibly cv-qualified) base class type of the dynamic type of the object,
    • a char or unsigned char type.

    The usual get-out for this type of operation is the bolded clause (you are allowed to access any memory via a pointer to char or unsigned char) however I don't believe this applies because a) uint8_t is not guaranteed to be a typedef for either char or unsigned char (18.4.1):

    typedef unsigned integer type uint8_t; // optional

    and b) an enum is a distinct type even if its storage is specified as a char type (7.2.1):

    An enumeration is a distinct type (3.9.2) with named constants.

    It's possible there is language elsewhere in the standard that makes this code not undefined behaviour but I can't find anything that would seem to make this well defined.

    resolved 
    opened by mattnewport 26
  • Compile without exception support

    Compile without exception support

    I am trying to use this in an other project which compiles without exception support.
    I would not mind substituting the exceptions with asserts, and let it fire only in debug.

    currently I use only the <gsl/span> header, my problem lies in <gsl/gsl_util>.
    Could we get something like:

    #if defined ( __cpp_exceptions) || \
            (defined (_MSC_VER) && defined (__CPPUNWIND)) || \
            (defined (__GNUC__) && defined (__EXCEPTIONS))
        #define ABORT_THROW (x) throw x
    #else
        #define ABORT_THROW (x) (x, std::abort())
    #endif
    

    and then use ABORT_THROW when needed?

    resolved 
    opened by LucaFulchir 24
  • Intel compiler compilation error

    Intel compiler compilation error

    I tried using gsl with Intel compiler 16 under SUSE Linux Enterprise Server 11 SP4 and got a

    icpc ../main.cpp -o test -std=c++14
    In file included from ../gsl/multi_span(23),
                 from ../gsl/gsl(24),
                 from ../main.cpp(1):
    ../gsl/gsl_byte(78): error #3377: constexpr function return is non-constant
        return l = byte(static_cast<unsigned char>(l) | static_cast<unsigned char>(r));
    

    (multiple times)

    icpc --version
    icpc (ICC) 16.0.3 20160415
    Copyright (C) 1985-2016 Intel Corporation.  All rights reserved.
    
    cat ../main.cpp
    #include "gsl/gsl"
    int main(int argc, char* argv[]) {
    }
    
    resolved 
    opened by steinret 23
  • Name conflict with the GNU Scientific Library

    Name conflict with the GNU Scientific Library

    Microsoft/GSL conflicts with https://www.gnu.org/software/gsl/ (another completely different project) and not only with the name, but as far as I can see also in the installed files.

    Would it be possible to ponder a rename of this project, on the basis that GNU's GSL is much older than Microsoft's GSL?

    declined 
    opened by mapreri 21
  • Fix compiler warning

    Fix compiler warning

    When building with GCC 5.4, the compiler spits out a warning about the following:

    warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false [-Wstrict-overflow]

    This patch fixes this issue.

    Signed-off-by: “Rian <“[email protected]”>

    resolved 
    opened by rianquinn 20
  • Remove non-essential null-checking from gsl::not_null

    Remove non-essential null-checking from gsl::not_null

    We are thinking of revising the gsl::not_null threat-model to reserve all nullness checking to the constructor, and to trust all created instances post-construction:

    not_null<int*> a = some_pointer; // check that some_pointer is not null in a's constructor
    int* b = a.get(); // no need to check that `a.ptr_` is not null; it's already been checked in a's constructor
    not_null<int*> other = a; // no need to check that `a.ptr_` is not null; it's already been checked in a's constructor.  
                              // transitively, `other._ptr_` will now also be trusted
    

    This change will remove many existing runtime checks that occur inside gsl::not_null, notably the one inside not_null::get(), and will overall simplify the design of the gsl::not_null type.

    The revised threat model should be publicly documented.

    opened by dmitrykobets-msft 0
  • gsl::not_null is trivially copyable, but not trivially move-constructible

    gsl::not_null is trivially copyable, but not trivially move-constructible

    The gsl::not_null class template has:

    • a compiler-generated trivial destructor;
    • an explicitly defaulted trivial copy constructor;
    • an explicitly defaulted trivial copy assignment operator;
    • no move constructor;
    • no move assignment operator.

    This makes it trivially copyable. However, move construction of an object of this class invokes a non-trivial, non-noexcept constructor template (include/gsl/pointers, line 90). This is unusual and unexpected; in fact, this triggers a bug in libstdc++’s implementation of std::variant. This could be fixed by adding explicitly defaulted move constructor and move assignment operator.

    opened by VoidPhantom 1
  • `Expects` and `Ensures` should be `GSL_EXPECTS` and `GSL_ENSURES`

    `Expects` and `Ensures` should be `GSL_EXPECTS` and `GSL_ENSURES`

    GSL should obey the core guidelines. Expects and Ensures should be GSL_EXPECTS and GSL_ENSURES. As the person who has suffered for 30 years for defining widely used macros check and require I can attest to just how bad an idea those names are. (https://opensource.apple.com/source/xnu/xnu-7195.141.2/EXTERNAL_HEADERS/AssertMacros.h.auto.html)

    opened by sean-parent 4
  • size_bytes unnecessarily optimizes poorly

    size_bytes unnecessarily optimizes poorly

    The span function size_bytes is currently implemented as follows:

        constexpr size_type size_bytes() const noexcept
        {
            Expects(size() < dynamic_extent / sizeof(element_type));
            return size() * sizeof(element_type);
        }
    

    This check is attempting to ensure that the multiplication doesn't overflow. This check is not actually needed because it is not possible for "size" to become so large that the overflow occurs. The only way this could happen is if the span was somehow representing more than size_t bytes worth of data but there's no room in the virtual address space for this.

    It leads to code optimizing poorly. In my current project I am calling size_bytes and it is actually a function call (I imagine because this code is compiled for size and size_bytes is a lot of code).

    binary!gsl::span<unsigned char const ,-1>::size_bytes:
    00000001`40434650 4883ec28        sub     rsp,28h
    00000001`40434654 488b01          mov     rax,qword ptr [rcx]
    00000001`40434657 4883f8ff        cmp     rax,0FFFFFFFFFFFFFFFFh
    00000001`4043465b 7306            jae     binary!gsl::span<unsigned char const ,-1>::size_bytes+0x13 (00000001`40434663)
    00000001`4043465d 4883c428        add     rsp,28h
    00000001`40434661 c3              ret
    00000001`40434662 cc              int     3
    00000001`40434663 e864000000      call    binary!gsl::details::terminate (00000001`404346cc)
    

    Notice since this is a span of bytes, there is a comparison to check if rax (the size) is bigger than or equal to 0xFFFFFFFF'FFFFFFFF. There is no way a span could be this big, and this check is resulting in a ton of code generation for what should just be loading the size field and returning it.

    opened by JosephBialekMsft 1
  • not_null conversion operator for non-copy constructible types

    not_null conversion operator for non-copy constructible types

    gsl::not_null< T > has the following conversion operator:

    constexpr operator T() const
    {
        return get();
    }
    

    which is deleted for non-copy constructible types such as std::unique_ptr due to gsl::not_null< T >'s conditional return type mapping to const T&:

    constexpr std::conditional_t<std::is_copy_constructible<T>::value, T, const T&> get() const
    {
        Ensures(ptr_ != nullptr);
        return ptr_;
    }
    

    Therefore, it is not possible to extract (the potentially expensive) ptr_ anymore for non-copy constructible types once a gsl::not_null< T > is constructed around it. Wouldn't it make sense to use ref-qualified member methods for both methods (i.e. conversion operator and get)?

    // For non-copy constructible types:
    
    constexpr operator const T&() const &
    {
        return ptr_;
    }
    
    constexpr operator T() &&
    {
        return std::move(ptr_);
    }
    
    opened by matt77hias 3
  • is_different_signedness using std::is_signed< T > instead of std::numeric_limits< T >::is_signed

    is_different_signedness using std::is_signed< T > instead of std::numeric_limits< T >::is_signed

    gsl::narrow internally uses

    constexpr const bool is_different_signedness = (std::is_signed<T>::value != std::is_signed<U>::value);

    which uses std::is_signed< T >. The latter cannot be specialized for custom arithmetic types (e.g., 16 bit floating point type, 128 bit integral types, etc.):

    The behavior of a program that adds specializations for is_signed or is_signed_v (since C++17) is undefined.

    unlike std::numeric_limits< T >::is_signed. Wouldn't gsl::narrow become more extendible, if std::is_signed< T > is replaced with std::numeric_limits< T >::is_signed?

    opened by matt77hias 7
Releases(v4.0.0)
  • v4.0.0(Jan 25, 2022)

    Version 4.0.0 of Microsoft's implementation of the C++ Core Guidelines Support Library (GSL) is now available! This release maintains the safety guarantees that we have always offered, and adds improvements to various parts of the library.

    What changed in this release?

    Deprecation of gsl::string_span

    isocpp/CppCoreGuidelines#1680 removed string_span from the C++ Core Guidelines. The recommendation is to use std::string_view, std::span<char> or gsl::span<char> instead. To more closely align Microsoft’s GSL with the C++ Core Guidelines, we deprecated our implementation of string_span and zstring_span, including basic_string_span, basic_zstring_span, and all related types. For the time being, we will continue to provide the <gsl/string_span> header, but it will not be actively worked on or maintained. A table of all supported and unsupported types/features can be found in the README.md.

    Removal of <gsl/multi_span>

    multi_span, strided_span, and everything else in <gsl/multi_span> were deprecated over a year ago in GSL 3.0.0, and it is time for them and their associated tests to be removed from the library.

    Header files dropped the gsl_ prefix

    All headers which previously contained a gsl_ prefix in their name have had this prefix removed. For example, <gsl/gsl_algorithm> is now <gsl/algorithm>. The gsl_ prefixed files still exist and pass through to the updated files, but will be removed in a future release.

    Changes to not_null

    To more closely align Microsoft’s GSL with the C++ Core Guidelines, gsl::not_null now accepts only types which are comparable to nullptr. Previously, it accepted only types which are assignable from nullptr, but this was stricter than what was intended by the Core Guidelines.

    The functions make_not_null and make_strict_not_null, and the not_null comparison operators, are now all noexcept.

    gsl::span and std::span now use the correct specialization of gsl::at

    gsl::span and std::span now have their own separate specializations of gsl::at, to ensure consistent behavior between the two versions of span. Both overloads are included when importing <gsl/span>. The std::span overload can be separately included from <gsl/util>.

    GSL will work in environments where exceptions are disabled, with some caveats

    gsl::narrow is the only part of the library which may throw exceptions and has been moved into its own header <gsl/narrow>. This header is included in <gsl/gsl> only if exceptions are enabled. This allows users of the library who are working in environments without exceptions to use all of the other components of the library.

    Note: gsl::narrow_cast is still in <gsl/util>, since it does not throw exceptions.

    Updated compiler support

    The list of supported compilers/toolsets has been updated with newer versions. More info on compiler support can be found in the README.md.

    | Compiler/Toolset | Version | | ----------------------- | ------------------------------ | | XCode | 13.2.1 & 12.5.1 | | GCC | 11.1.0 & 10.3.0 | | Clang | 12.0.0 & 11.0.0 | | Visual Studio with MSVC | VS2022 (17.0) & VS2019 (16.11) | | Visual Studio with LLVM | VS2022 (17.0) & VS2019 (16.11) |

    CMake and build improvements

    • GSL Install logic is now guarded by a cmake option GSL_INSTALL: #964
    • Fix bug which prevented the library from being built on a 32-bit host and then being used on a 64-bit machine: #893
    • Build will now use CMAKE_CXX_STANDARD if it's provided #953
    • Clean up GSL_SUPPRESS warning for intel compilers: #906
    • Fix build failure for C++20 compilers which don't have std::span: #993
    • Cleaned up some static analysis warnings
    • The cmake cache variable VS_ADD_NATIVE_VISUALIZERS has been renamed to GSL_VS_ADD_NATIVE_VISUALIZERS: #941

    Updates

    • Update 1/28/2022: Bumped the release forward to hotfix a353456
    Source code(tar.gz)
    Source code(zip)
  • v3.1.0(Jun 4, 2020)

    New this release

    • Implementation of P1976R2 for gsl::span introduces explicit construction of fixed-length spans from dynamic spans.
    • Better template argument deduction for gsl::span.
    • Improved natvis for span and span derived types.
      • PR: #857
    • Added CMake find_package version support.
      • PR: #879
    Source code(tar.gz)
    Source code(zip)
  • v3.0.1(Apr 23, 2020)

    This is a minor release that addresses a bug in gsl::narrow.

    Bug details: Previously gsl::narrow was changed to follow the same termination behavior as contract violations. However the Core Guidelines explicitly says gsl::narrow should throw a gsl::narrowing_error on failure.
    Fix: PR #873 corrects this issue and re-introduces the throwing behavior for gsl::narrow.

    Source code(tar.gz)
    Source code(zip)
  • v3.0.0(Apr 16, 2020)

    Version 3.0.0 of Microsoft's implementation of the C++ Core Guidelines Support Library (GSL) is now available! Microsoft’s implementation of gsl::span has played a pivotal role in the standardization of span for C++20. However, the standard does not provide any runtime checking guarantees for memory bounds safety. The bounds safety provided by gsl::span has been very successful in preventing security issues in Microsoft products. This release maintains the safety guarantees that we have always offered but modernizes our implementation to align with C++20 span.

    What changed in this release?

    • New implementations of gsl::span and gsl::span_iterator that align to the C++ 20 standard.
    • Changes to contract violation behavior.
    • Additional CMake support.
    • Deprecation of gsl::multi_span and gsl::strided_span.

    When should I use gsl::span instead of std::span?

    By default, use std::span which is shipping in VS2019 16.6 (with additional interface changes in 16.7, see release notes) if you have enabled C++20 mode and do not need runtime bounds checking guarantees. Use gsl::span if you need support for a version of C++ lower than C++20 (gsl::span supports C++14 and higher) or runtime bounds checking guarantees (all operations performed on gsl::span and its iterators have explicit bounds safety checks.)

    gsl::span

    With the standardization of span nearing completion, we decided it was time to align our implementation with the design changes in the standard. The new implementation provides full bounds checking, guaranteeing bounds safety if the underlying data is valid.

    General changes

    gsl::span was rewritten to have its interface align to std::span. The biggest change is that span's Extent is now unsigned. It is now implemented as std::size_t whereas previously it was std::ptrdiff_t. By extension, dynamic_extent is now defined as static_cast<std::size_t>(-1) instead of just -1.

    • The field span::index_type was removed, superseded by span::size_type.
    • Addition of Class Template Argument Deduction (CTAD) support.

    Interface alignment

    These are the changes required to align gsl::span to the interface of std::span.

    Removed functions

    • span::operator()
    • span::at
    • span::cbegin
    • span::cend
    • span::crbegin
    • span::crend

    Added functions

    • span::front
    • span::back

    Renamed functions

    • span::as_writeable_bytes was renamed to span::as_writable_bytes

    gsl::span_iterator

    General changes

    Our implementation of span_iterator has been completely rewritten to be more range-like. Previously, the implementation consisted of a span pointer and an offset. The new implementation is a set of three pointers: begin, end, and current.

    Benefits of our new implementation

    The new implementation can perform all of the bounds checks by itself, instead of calling into the span. By relying on pointers to the underlying data, rather than a pointer to the span, the new span_iterator can outlive the underlying span.

    The new <gsl/span_ext> header

    The <gsl/span_ext> header was created to support our customers who rely on portions of the old span implementation that no longer exist in the standard definition of span.

    Elements moved from <gsl/span> and inserted into <gsl/span_ext>

    • span comparison operators
    • gsl::make_span
    • span specialization of gsl::at
    • gsl::begin
    • gsl::rbegin
    • gsl::crbegin
    • gsl::end
    • gsl::rend
    • gsl::crend

    Contract violations

    Contract violations are no longer configurable. Contract violations always result in termination, rather than providing a compile-time option to throw or disregard the contract violation. This is subject to change in the future. Some concerns over this decision have been raised and the conversation continues here: isocpp/CppCoreGuidelines#1561. As a side note, the removal of the throwing behavior required the migration of our test infrastructure from Catch2 to Google Test, whose support of death tests easily enabled testing of contract violation behavior.

    CMake improvements

    This release now supports find_package. Once installed, use find_package(Microsoft.GSL CONFIG) to easily consume the GSL.

    Deprecation of multi_span and strided_span

    To more closely align Microsoft’s GSL to the C++ Core Guidelines, we decided to deprecate our implementation of gsl::multi_span and gsl::strided_span. For the time being, we will continue to provide these headers, but they will not be actively worked on or maintained unless the C++ Core Guidelines identifies a need for them.

    Improvement changes causing potential build breaks and mitigations

    • Change: The change from signed std::ptrdiff_t to unsigned std::size_t in gsl::span may introduce signed/unsigned mismatches.
      • Mitigation: Use static_cast or gsl::narrow_cast to resolve mismatches.
    • Change: gsl::multi_span and gsl::strided_span have been deprecated.
      • Mitigation: Pass multi-dimensional arrays as constant references instead of gsl::multi_span.
    • Change: Code that makes use of moved span helper functions will generate compiler errors. Examples of these functions include span comparison operators, gsl::make_span, etc.
      • Mitigation: Include <gsl/span_ext> instead of <gsl/span> in files where you use these functions.
    • Change: Throwing contract violation behavior is removed.
      • Mitigation: Use a terminate handler to log relevant information before termination executes for debugging. Relying on throwing behavior does not guarantee safety.

    Upcoming changes

    The paper P1976R2 that came out of the WG21 Prague meeting has yet to be implemented in GSL. A minor release will be issued when it is added to GSL.

    Source code(tar.gz)
    Source code(zip)
  • v2.1.0(Dec 31, 2019)

    Changes included in this version

    Major changes

    • Deprecation of multi_span and strided_span.

    Minor changes

    • Additional constexpr support
    • Bug fixes

    What to look forward to in future releases

    • The GSL is changing how it handles contract violations.
    • The test framework is being replaced with GoogleTest to accommodate the contract violation changes.

    Additional information on contract violation changes

    Previous behavior on contract violation

    • Option to ignore, terminate, or throw on contract violation.

    New behavior

    • Contract violation will always result in termination.
    Source code(tar.gz)
    Source code(zip)
  • v2.0.0(Aug 20, 2018)

    Main API changes include

    • explicit not_null contructors (see samples/gsl_transition for ideas on how to move to the new version)
    • added make_not_null
    • cleanup of constexpr and noexcept

    Test changes:

    • added tests for c++14 and c++17

    Also fixed CppCorecheck warnings and made numerous bug fixes.

    Source code(tar.gz)
    Source code(zip)
  • v1.0.0(May 1, 2018)

    GSL commits are all CI verified and considered stable. However, we would like to mark significant changes (such as API breaking ones or adding extra functionality) by changing versions.

    Those commits are additionally verified by compiling and testing MS Static analysis tools that use GSL.

    Source code(tar.gz)
    Source code(zip)
Owner
Microsoft
Open source projects and samples from Microsoft
Microsoft
gsl-lite – A single-file header-only version of ISO C++ Guidelines Support Library (GSL) for C++98, C++11, and later

gsl-lite: Guidelines Support Library for C++98, C++11 up metadata build packages try online gsl-lite is an implementation of the C++ Core Guidelines S

gsl-lite 753 Sep 13, 2022
Guidelines Support Library

GSL: Guidelines Support Library The Guidelines Support Library (GSL) contains functions and types that are suggested for use by the C++ Core Guideline

Microsoft 5.1k Sep 25, 2022
Bsl - Rust 2018 and C++20, "constexpr everything", AUTOSAR compliant header-only library intended to support the development of critical systems applications

Description The Bareflank Support Library (BSL) is a Rust 2018 and C++20, "constexpr everything", AUTOSAR compliant header-only library intended to su

Bareflank 70 Sep 13, 2022
GNU Scientific Library with CMake build support and AMPL bindings

GSL - GNU Scientific Library This is GSL, the GNU Scientific Library, a collection of numerical routines for scientific computing. GSL is free softwar

AMPL 415 Sep 20, 2022
C++ STL in the Windows Kernel with C++ Exception Support

C++ STL in Windows Drivers This project uses MSVC C++ STL in a Windows Kernel Driver. In this solution jxystl.lib is implemented as a kernel-tuned, po

Johnny Shaw 265 Sep 17, 2022
C++11/14/17 std::optional with functional-style extensions and reference support

optional Single header implementation of std::optional with functional-style extensions and support for references. Clang + GCC: MSVC: std::optional i

Sy Brand 672 Sep 16, 2022
Libft is an individual project at 42 that requires us to re-create some standard C library functions including some additional ones that can be used later to build a library of useful functions for the rest of the program.

?? Index What is Libft? List of Functions Technologies ✨ What is Libft? Libft is an individual project at 42 that requires us to re-create some standa

Paulo Rafael Ramalho 7 Jan 17, 2022
Library that simplify to find header for class from STL library.

Library that simplify to find header for class from STL library. Instead of searching header for some class you can just include header with the class name.

null 6 Jun 7, 2022
Thrust is a C++ parallel programming library which resembles the C++ Standard Library.

Thrust: Code at the speed of light Thrust is a C++ parallel programming library which resembles the C++ Standard Library. Thrust's high-level interfac

NVIDIA Corporation 4.2k Sep 17, 2022
jkds is a modern header-only C++20 library that complements the standard library.

jkds is a modern header-only C++20 library that complements the standard library. It provides generic atypical data structures, ergonomic functional programming abstractions, and then some.

Alberto Schiabel 5 May 24, 2022
Bionic BSD-3-ClauseBionic - Google's standard library, developed for Android. BSD-3-Clause

bionic bionic is Android's C library, math library, and dynamic linker. Using bionic as an app developer See the user documentation. Working on bionic

Android Open Source Project 553 Sep 12, 2022
CloudABI's standard C library

NOTE: This project is unmaintained CloudABI is no longer being maintained. It was an awesome experiment, but it never got enough traction to be sustai

Nuxi 272 Sep 15, 2022
libcu++: The C++ Standard Library for Your Entire System

libcu++, the NVIDIA C++ Standard Library, is the C++ Standard Library for your entire system. It provides a heterogeneous implementation of the C++ Standard Library that can be used in and between CPU and GPU code.

NVIDIA Corporation 2k Sep 19, 2022
D++ Extremely Lightweight C++ Discord Library

D++ An incredibly lightweight C++ Discord library This project is in alpha stages of development. Completed so far: Websocket connection with heartbea

brainbox.cc 496 Sep 21, 2022
EASTL stands for Electronic Arts Standard C++ Template Library

EASTL stands for Electronic Arts Standard Template Library. It is an extensive and robust implementation that has an emphasis on high performance.

Electronic Arts 6.7k Sep 20, 2022
An open source standard C library that includes useful functions && (Reimplementation of libc functions + own functions).

?? LIBFT-42 : Artistic view of LIBC: ?? HOW DOES IT FEEL HAVING YOUR OWN LIB: SUBJECT : ENGLISH PDF ℹ️ What is LIBFT : This project aims to code a C l

Abdessamad Laamimi 11 Sep 21, 2022
Single-header header-only C++11 / C++14 / C++17 library for easily managing set of auto-generated type-safe flags.

Single-header header-only C++11 / C++14 / C++17 library for easily managing set of auto-generated type-safe flags. Quick start #include <bitflags/bitf

Marin Peko 72 Aug 24, 2022
expected lite - Expected objects in C++11 and later in a single-file header-only library

expected lite: expected objects for C++11 and later expected lite is a single-file header-only library for objects that either represent a valid value

Martin Moene 231 Sep 19, 2022
Your standard library for metaprogramming

Boost.Hana Your standard library for metaprogramming Overview #include <boost/hana.hpp> #include <cassert> #include <string> namespace hana = boost::h

Boost.org 1.4k Sep 22, 2022