Convert Figma logo to code with AI

microsoft logoGSL

Guidelines Support Library

6,172
740
6,172
10

Top Related Projects

Zero overhead utilities for preventing bugs at compile time

Abseil Common Libraries (C++)

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.

28,292

An open-source C++ library developed and used at Facebook.

Quick Overview

The Microsoft Guidelines Support Library (GSL) is a collection of C++ core guidelines support types and functions. It aims to provide standardized, efficient, and safe implementations of common programming patterns, helping developers write more robust and less error-prone code in modern C++.

Pros

  • Improves code safety and reduces common programming errors
  • Lightweight and header-only library, easy to integrate
  • Implements many of the C++ Core Guidelines recommendations
  • Actively maintained by Microsoft and the community

Cons

  • May require a learning curve for developers unfamiliar with C++ Core Guidelines
  • Some features might have a small performance overhead
  • Not all C++ compilers fully support all GSL features
  • Can introduce additional dependencies in projects

Code Examples

  1. Using gsl::span for safer array access:
#include <gsl/span>
#include <vector>

void process_data(gsl::span<int> data) {
    for (int& item : data) {
        item *= 2;
    }
}

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};
    process_data(vec);  // Safely pass vector as a span
    return 0;
}
  1. Using gsl::not_null to ensure non-null pointers:
#include <gsl/pointers>

void print_value(gsl::not_null<int*> ptr) {
    std::cout << *ptr << std::endl;
}

int main() {
    int value = 42;
    print_value(&value);  // OK
    // print_value(nullptr);  // Compile-time error
    return 0;
}
  1. Using gsl::finally for guaranteed cleanup:
#include <gsl/util>

void resource_intensive_function() {
    auto cleanup = gsl::finally([]{ /* cleanup code */ });
    // Function body...
    // Cleanup will be called automatically when exiting the function
}

Getting Started

To use GSL in your project, follow these steps:

  1. Clone the repository or download the headers:

    git clone https://github.com/microsoft/GSL.git
    
  2. Add the include directory to your project's include path.

  3. Include the desired GSL headers in your C++ files:

    #include <gsl/gsl>
    
  4. Compile your project with a C++14 or later compiler.

  5. Start using GSL types and functions in your code to improve safety and follow C++ Core Guidelines.

Competitor Comparisons

Zero overhead utilities for preventing bugs at compile time

Pros of type_safe

  • Focuses on strong typing and type safety, providing more specialized tools for type-safe programming
  • Offers a wider range of vocabulary types, including strong_typedef for creating distinct types
  • Provides more comprehensive constexpr support, enabling better compile-time checks

Cons of type_safe

  • Smaller community and less widespread adoption compared to GSL
  • May have a steeper learning curve due to its more specialized nature
  • Less comprehensive documentation and examples available

Code Comparison

GSL:

gsl::span<int> arr = ...;
gsl::not_null<int*> ptr = ...;

type_safe:

type_safe::array_ref<int> arr = ...;
type_safe::object_ref<int> ptr = ...;

Summary

While GSL provides a broader set of guidelines and utilities for C++ programming, type_safe focuses more specifically on enhancing type safety. GSL has wider adoption and more extensive documentation, but type_safe offers more specialized tools for creating type-safe code. The choice between the two depends on the specific needs of the project and the developer's preferences for type safety enforcement.

Abseil Common Libraries (C++)

Pros of Abseil

  • More comprehensive library with a wider range of utilities and data structures
  • Actively maintained and regularly updated by Google
  • Designed for better compatibility across different C++ versions

Cons of Abseil

  • Larger codebase and potentially higher learning curve
  • May introduce dependencies that are not needed for smaller projects
  • Some features might be Google-specific and less applicable to general use cases

Code Comparison

GSL example:

gsl::span<int> mySpan(myVector);
gsl::not_null<int*> ptr = &myInt;

Abseil example:

absl::Span<int> mySpan(myVector);
absl::optional<int> maybeInt = absl::nullopt;

Both libraries provide similar functionality for spans, but Abseil offers a broader range of utilities. GSL focuses more on core guidelines support, while Abseil includes additional features like string formatting, time utilities, and synchronization primitives.

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.

Pros of LLVM Project

  • Comprehensive compiler infrastructure with multiple frontends and backends
  • Extensive toolchain including debugger, linker, and optimization passes
  • Large, active community with frequent updates and contributions

Cons of LLVM Project

  • Steeper learning curve due to its size and complexity
  • Heavier resource requirements for building and using
  • May be overkill for projects not requiring full compiler infrastructure

Code Comparison

GSL (Guidelines Support Library):

#include <gsl/gsl>

void example(gsl::span<int> arr) {
    for (int& elem : arr) {
        elem *= 2;
    }
}

LLVM Project:

#include "llvm/IR/IRBuilder.h"

LLVMContext Context;
IRBuilder<> Builder(Context);
auto *FunctionType = FunctionType::get(Builder.getVoidTy(), false);
Function *MyFunction = Function::Create(FunctionType, Function::ExternalLinkage, "example", Module);

Summary

While GSL focuses on providing lightweight abstractions for C++ programming guidelines, LLVM Project offers a complete compiler infrastructure. GSL is more suitable for projects aiming to improve C++ code safety and readability, while LLVM is ideal for tasks involving code generation, optimization, and analysis across multiple programming languages.

28,292

An open-source C++ library developed and used at Facebook.

Pros of Folly

  • Broader scope with a more extensive collection of utilities and components
  • Optimized for high-performance systems and large-scale applications
  • Active development with frequent updates and contributions from Facebook engineers

Cons of Folly

  • Larger codebase and more complex API, potentially steeper learning curve
  • May include unnecessary features for smaller projects
  • Heavier dependency footprint compared to GSL's lightweight design

Code Comparison

GSL (Guidelines Support Library):

#include <gsl/gsl>

void example(gsl::span<int> data) {
    for (int& item : data) {
        // Process item
    }
}

Folly:

#include <folly/FBVector.h>

folly::fbvector<int> data;
data.reserve(1000);
for (int i = 0; i < 1000; ++i) {
    data.push_back(i);
}

GSL focuses on providing lightweight abstractions for safer C++ programming, while Folly offers a broader range of utilities optimized for performance in large-scale applications. GSL's span example demonstrates its emphasis on bounds-safe views, whereas Folly's FBVector showcases its high-performance container implementations.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

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 opencode@microsoft.com 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:

FeatureSupported?Description
1. Views
ownerAn alias for a raw pointer
not_nullRestricts a pointer/smart pointer to hold non-null values
spanA view over a contiguous sequence of memory. Based on the standardized version of std::span, however gsl::span enforces bounds checking.
span_pSpans a range starting from a pointer to the first place for which the predicate is true
basic_zstringA pointer to a C-string (zero-terminated array) with a templated char type
zstringAn alias to basic_zstring with dynamic extent and a char type of char
czstringAn alias to basic_zstring with dynamic extent and a char type of const char
wzstringAn alias to basic_zstring with dynamic extent and a char type of wchar_t
cwzstringAn alias to basic_zstring with dynamic extent and a char type of const wchar_t
u16zstringAn alias to basic_zstring with dynamic extent and a char type of char16_t
cu16zstringAn alias to basic_zstring with dynamic extent and a char type of const char16_t
u32zstringAn alias to basic_zstring with dynamic extent and a char type of char32_t
cu32zstringAn alias to basic_zstring with dynamic extent and a char type of const char32_t
2. Owners
unique_ptrAn alias to std::unique_ptr
shared_ptrAn alias to std::shared_ptr
stack_arrayA stack-allocated array
dyn_arrayA heap-allocated array
3. Assertions
ExpectsA precondition assertion; on failure it terminates
EnsuresA postcondition assertion; on failure it terminates
4. Utilities
move_ownerA helper function that moves one owner to the other
byteEither an alias to std::byte or a byte type
final_actionA RAII style class that invokes a functor on its destruction
finallyA helper function instantiating final_action
GSL_SUPPRESSA 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
indexA type to use for all container and array indexing (currently an alias for std::ptrdiff_t)
joining_threadA RAII style version of std::thread that joins
narrowA checked version of narrow_cast; it can throw narrowing_error
narrow_castA narrowing cast for values and a synonym for static_cast
narrowing_errorA custom exception type thrown by narrow
5. Concepts

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

FeatureSupported?Description
strict_not_nullA stricter version of not_null with explicit constructors
multi_spanDeprecated. Multi-dimensional span.
strided_spanDeprecated. Support for this type has been discontinued.
basic_string_spanDeprecated. Like span but for strings with a templated char type
string_spanDeprecated. An alias to basic_string_span with a char type of char
cstring_spanDeprecated. An alias to basic_string_span with a char type of const char
wstring_spanDeprecated. An alias to basic_string_span with a char type of wchar_t
cwstring_spanDeprecated. An alias to basic_string_span with a char type of const wchar_t
u16string_spanDeprecated. An alias to basic_string_span with a char type of char16_t
cu16string_spanDeprecated. An alias to basic_string_span with a char type of const char16_t
u32string_spanDeprecated. An alias to basic_string_span with a char type of char32_t
cu32string_spanDeprecated. 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 / Toolsets

The GSL officially supports the latest and previous major versions of VS with MSVC & LLVM, GCC, Clang, and XCode with Apple-Clang. Within these two major versions, we try to target the latest minor updates / revisions (although this may be affected by delays between a toolchain's release and when it becomes widely available for use). Below is a table showing the versions currently being tested.

CompilerToolset Versions Currently Tested
XCode13.2.1 & 12.5.1
GCC111 & 102
Clang122 & 112
Visual Studio with MSVCVS20223 & VS20194
Visual Studio with LLVMVS20223 & VS20194

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!
TargetCI/CD Status
iOSCI_iOS
AndroidCI_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.14 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.

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

find_package(Microsoft.GSL CONFIG REQUIRED)

target_link_libraries(foobar PRIVATE Microsoft.GSL::GSL)

FetchContent

If you are using CMake version 3.11+ you can use the official 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)

FetchContent_Declare(GSL
    GIT_REPOSITORY "https://github.com/microsoft/GSL"
    GIT_TAG "v4.0.0"
    GIT_SHALLOW ON
)

FetchContent_MakeAvailable(GSL)

target_link_libraries(foobar PRIVATE Microsoft.GSL::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.

Footnotes

  1. Precise version may be found in the latest CI results.

  2. Precise version may be found in the latest CI results. Should be the version specified here. 2 3

  3. Precise version may be found in the latest CI results. Should be the version specified here. 2

  4. Precise version may be found in the latest CI results. Should be the version specified here. 2