pax_global_header00006660000000000000000000000064151156131250014512gustar00rootroot0000000000000052 comment=249146590e322123cd0b378b1f364d6069717687 GSL-4.2.1/000077500000000000000000000000001511561312500121435ustar00rootroot00000000000000GSL-4.2.1/.clang-format000066400000000000000000000014101511561312500145120ustar00rootroot00000000000000ColumnLimit: 100 UseTab: Never IndentWidth: 4 AccessModifierOffset: -4 NamespaceIndentation: Inner BreakBeforeBraces: Custom BraceWrapping: AfterNamespace: true AfterEnum: true AfterStruct: true AfterClass: true SplitEmptyFunction: false AfterControlStatement: true AfterFunction: true AfterUnion: true BeforeElse: true AlwaysBreakTemplateDeclarations: true BreakConstructorInitializersBeforeComma: true ConstructorInitializerAllOnOneLineOrOnePerLine: true AllowShortBlocksOnASingleLine: true AllowShortFunctionsOnASingleLine: All AllowShortIfStatementsOnASingleLine: true AllowShortLoopsOnASingleLine: true PointerAlignment: Left AlignConsecutiveAssignments: false AlignTrailingComments: true SpaceAfterCStyleCast: true CommentPragmas: '^ NO-FORMAT:' GSL-4.2.1/.gitattributes000066400000000000000000000000441511561312500150340ustar00rootroot00000000000000include/gsl/* linguist-language=C++ GSL-4.2.1/.github/000077500000000000000000000000001511561312500135035ustar00rootroot00000000000000GSL-4.2.1/.github/ISSUE_TEMPLATE/000077500000000000000000000000001511561312500156665ustar00rootroot00000000000000GSL-4.2.1/.github/ISSUE_TEMPLATE/bug_report.md000066400000000000000000000010551511561312500203610ustar00rootroot00000000000000--- name: Bug report about: Create a report to help us improve title: '' labels: 'Status: Open, Type: Bug' assignees: '' --- **Describe the bug** A clear and concise description of what the bug is. **To Reproduce** ```c++ #include // your repro here: ... ``` **Expected behavior** A clear and concise description of what you expected to happen. **Spec (please complete the following information):** - OS: [e.g. Windows] - Compiler: [e.g. MSVC] - C++ Version: [e.g. C++20] **Additional context** Add any other context about the problem here. GSL-4.2.1/.github/workflows/000077500000000000000000000000001511561312500155405ustar00rootroot00000000000000GSL-4.2.1/.github/workflows/android.yml000066400000000000000000000037701511561312500177120ustar00rootroot00000000000000name: CI_Android concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: true on: push: branches: [ main ] pull_request: branches: [ main ] jobs: Android: runs-on: macos-latest-large defaults: run: working-directory: build steps: - uses: actions/checkout@v4 - name: Create build directory run: mkdir -p build working-directory: . - uses: actions/setup-java@v4 with: java-version: 8 distribution: zulu - name: Start Emulator run: | echo "y" | $ANDROID_HOME/tools/bin/sdkmanager --install 'system-images;android-24;default;x86_64' echo "no" | $ANDROID_HOME/tools/bin/avdmanager create avd -n xamarin_android_emulator -k 'system-images;android-24;default;x86_64' --force $ANDROID_HOME/emulator/emulator -list-avds echo "Starting emulator..." nohup $ANDROID_HOME/emulator/emulator -no-audio -no-snapshot -avd xamarin_android_emulator &> /dev/null & echo "Emulator starting in background" - name: Configure run: cmake -DCMAKE_TOOLCHAIN_FILE=$ANDROID_NDK_LATEST_HOME/build/cmake/android.toolchain.cmake -DANDROID_PLATFORM=16 -DANDROID_ABI=x86_64 -DCMAKE_BUILD_TYPE=Debug .. - name: Build run: cmake --build . --parallel - name: Wait for emulator ready timeout-minutes: 2 run: | $ANDROID_HOME/platform-tools/adb wait-for-device shell 'while [[ -z $(getprop sys.boot_completed | tr -d '\r') ]]; do sleep 10; done; input keyevent 82' $ANDROID_HOME/platform-tools/adb devices $ANDROID_HOME/platform-tools/adb shell getprop ro.product.cpu.abi - name: Deploy tests run: | adb push tests /data/local/tmp adb shell find /data/local/tmp/tests -maxdepth 1 -exec chmod +x {} \\\; - name: Test run: adb shell find /data/local/tmp/tests -name "*_tests" -maxdepth 1 -exec {} \\\; GSL-4.2.1/.github/workflows/cmake/000077500000000000000000000000001511561312500166205ustar00rootroot00000000000000GSL-4.2.1/.github/workflows/cmake/action.yml000066400000000000000000000025111511561312500206170ustar00rootroot00000000000000name: Composite CMake inputs: cmake_generator: required: false type: string default: 'Unix Makefiles' cmake_build_type: required: true type: string default: '' cmake_cxx_compiler: required: false type: string gsl_cxx_standard: required: true type: number extra_cmake_args: required: false type: string default: '' build_cmd: required: true type: string default: 'make' test_cmd: required: false type: string default: 'make test' shell: required: false type: string default: 'bash' runs: using: composite steps: - name: Create build directory run: mkdir build shell: ${{ inputs.shell }} - name: Configure CMake working-directory: build run: cmake -G "${{ inputs.cmake_generator }}" -DCMAKE_BUILD_TYPE=${{ inputs.cmake_build_type }} -DCMAKE_CXX_COMPILER=${{ inputs.cmake_cxx_compiler }} -DGSL_CXX_STANDARD=${{ inputs.gsl_cxx_standard }} -DCI_TESTING:BOOL=ON -DCMAKE_VERBOSE_MAKEFILE:BOOL=ON -Werror=dev ${{ inputs.extra_cmake_args }} .. shell: ${{ inputs.shell }} - name: Build working-directory: build run: ${{ inputs.build_cmd }} shell: ${{ inputs.shell }} - name: Test working-directory: build run: ${{ inputs.test_cmd }} shell: ${{ inputs.shell }} GSL-4.2.1/.github/workflows/cmake_find_package.yml000066400000000000000000000014471511561312500220240ustar00rootroot00000000000000name: cmake_find_package on: push: branches: [ main ] pull_request: branches: [ main ] jobs: cmake-find-package: name: Build ${{ matrix.os }} runs-on: ${{ matrix.os }} strategy: matrix: os: [ ubuntu-latest, macos-latest ] steps: - uses: actions/checkout@v4 - uses: lukka/get-cmake@latest with: cmakeVersion: 3.14.0 - name: Configure GSL run: cmake -S . -B build -G "Ninja" -D GSL_TEST=OFF -D CMAKE_INSTALL_PREFIX=${GITHUB_WORKSPACE}/build/install - name: Install GSL run: cmake --build build --target install - name: Test GSL find_package support run: cmake -S tests/ -B build/tests_find_package -G "Ninja" -D CMAKE_PREFIX_PATH=${GITHUB_WORKSPACE}/build/install -D CMAKE_BUILD_TYPE=Release GSL-4.2.1/.github/workflows/compilers.yml000066400000000000000000000070341511561312500202640ustar00rootroot00000000000000name: Compiler Integration Tests concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: true on: push: branches: [ main ] pull_request: branches: [ main ] # These jobs are correlated with the officially supported compilers # and toolsets. If you change any versions, please update README.md. jobs: gcc: strategy: matrix: gcc_version: [ 12, 13, 14 ] build_type: [ Debug, Release ] cxx_version: [ 14, 17, 20, 23 ] exclude: # https://github.com/google/googletest/issues/4232 # Looks like GoogleTest is not interested in making version 1.14 # work with gcc-12. - gcc_version: 12 cxx_version: 20 - gcc_version: 12 cxx_version: 23 runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Run CMake (configure, build, test) uses: ./.github/workflows/cmake with: cmake_build_type: ${{ matrix.build_type }} cmake_cxx_compiler: g++-${{ matrix.gcc_version }} gsl_cxx_standard: ${{ matrix.cxx_version }} clang: strategy: matrix: clang_version: [ 16, 17, 18 ] build_type: [ Debug, Release ] cxx_version: [ 14, 17, 20, 23 ] exclude: # https://github.com/llvm/llvm-project/issues/93734 # Looks like clang fixed this issue in clang-18, but won't backport # the fix. - clang_version: 17 cxx_version: 23 runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Run CMake (configure, build, test) uses: ./.github/workflows/cmake with: cmake_build_type: ${{ matrix.build_type }} cmake_cxx_compiler: clang++-${{ matrix.clang_version }} gsl_cxx_standard: ${{ matrix.cxx_version }} xcode: strategy: matrix: xcode_version: [ '15.4' ] build_type: [ Debug, Release ] cxx_version: [ 14, 17, 20, 23 ] runs-on: macos-latest steps: - uses: actions/checkout@v4 - name: select xcode version run: sudo xcode-select -s /Applications/Xcode_${{ matrix.xcode_version }}.app - name: Run CMake (configure, build, test) uses: ./.github/workflows/cmake with: cmake_build_type: ${{ matrix.build_type }} cmake_cxx_compiler: clang++ gsl_cxx_standard: ${{ matrix.cxx_version }} VisualStudio: strategy: matrix: generator: [ 'Visual Studio 16 2019', 'Visual Studio 17 2022' ] image: [ windows-2019, windows-2022 ] build_type: [ Debug, Release ] extra_args: [ '', '-T ClangCL' ] cxx_version: [ 14, 17, 20, 23 ] exclude: - generator: 'Visual Studio 17 2022' image: windows-2019 - generator: 'Visual Studio 16 2019' image: windows-2022 - generator: 'Visual Studio 16 2019' cxx_version: 23 runs-on: ${{ matrix.image }} steps: - uses: actions/checkout@v4 - uses: microsoft/setup-msbuild@v2 - name: Run CMake (configure, build, test) uses: ./.github/workflows/cmake with: cmake_generator: ${{ matrix.generator }} cmake_build_type: ${{ matrix.build_type }} gsl_cxx_standard: ${{ matrix.cxx_version }} extra_cmake_args: ${{ matrix.extra_args }} build_cmd: msbuild GSL.sln test_cmd: ctest . --output-on-failure --no-compress-output shell: pwsh GSL-4.2.1/.github/workflows/ios.yml000066400000000000000000000032021511561312500170520ustar00rootroot00000000000000name: CI_iOS on: push: branches: [ main ] pull_request: branches: [ main ] jobs: iOS: runs-on: macos-latest defaults: run: working-directory: build steps: - uses: actions/checkout@v4 - name: Create build directory run: mkdir -p build working-directory: . - name: Configure run: | cmake \ -Werror=dev \ -GXcode \ -DCMAKE_SYSTEM_NAME=iOS \ "-DCMAKE_OSX_ARCHITECTURES=arm64;x86_64" \ -DCMAKE_OSX_DEPLOYMENT_TARGET=9 \ -DCMAKE_TRY_COMPILE_TARGET_TYPE=STATIC_LIBRARY \ "-DMACOSX_BUNDLE_GUI_IDENTIFIER=GSL.\$(EXECUTABLE_NAME)" \ -DMACOSX_BUNDLE_BUNDLE_VERSION=4.2.1 \ -DMACOSX_BUNDLE_SHORT_VERSION_STRING=4.2.1 \ .. - name: Build run: cmake --build . --parallel `sysctl -n hw.ncpu` --config Release -- -sdk iphonesimulator - name: Start simulator run: | RUNTIME=`xcrun simctl list runtimes iOS -j|jq '.runtimes|last.identifier'` UDID=`xcrun simctl list devices iPhone available -j|jq -r ".devices[$RUNTIME]|last.udid"` xcrun simctl bootstatus $UDID -b - name: Test run: | for TEST in `find tests/Release-iphonesimulator -depth 1 -name "*.app"` do xcrun simctl install booted $TEST TEST_ID=`plutil -convert json -o - $TEST/Info.plist|jq -r ".CFBundleIdentifier"` xcrun simctl launch --console booted $TEST_ID xcrun simctl uninstall booted $TEST_ID done GSL-4.2.1/.gitignore000066400000000000000000000002611511561312500141320ustar00rootroot00000000000000CMakeFiles build tests/CMakeFiles tests/Debug *.opensdf *.sdf tests/*tests.dir *.vcxproj *.vcxproj.filters *.sln *.tlog Testing/Temporary/*.* CMakeCache.txt *.suo .vs/ .vscode/ GSL-4.2.1/CMakeLists.txt000066400000000000000000000033631511561312500147100ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.14...3.16) project(GSL VERSION 4.2.1 LANGUAGES CXX) add_library(GSL INTERFACE) add_library(Microsoft.GSL::GSL ALIAS GSL) # https://cmake.org/cmake/help/latest/variable/PROJECT_IS_TOP_LEVEL.html string(COMPARE EQUAL ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_SOURCE_DIR} PROJECT_IS_TOP_LEVEL) option(GSL_INSTALL "Generate and install GSL target" ${PROJECT_IS_TOP_LEVEL}) option(GSL_TEST "Build and perform GSL tests" ${PROJECT_IS_TOP_LEVEL}) # The implementation generally assumes a platform that implements C++14 support target_compile_features(GSL INTERFACE "cxx_std_14") # Setup include directory add_subdirectory(include) target_sources(GSL INTERFACE $) if (GSL_TEST) enable_testing() add_subdirectory(tests) endif() if (GSL_INSTALL) include(GNUInstallDirs) include(CMakePackageConfigHelpers) install(DIRECTORY "${PROJECT_SOURCE_DIR}/include/gsl" DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) set(export_name "Microsoft.GSLConfig") set(namespace "Microsoft.GSL::") set(cmake_files_install_dir ${CMAKE_INSTALL_DATADIR}/cmake/Microsoft.GSL) install(TARGETS GSL EXPORT ${export_name} INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) install(EXPORT ${export_name} NAMESPACE ${namespace} DESTINATION ${cmake_files_install_dir}) export(TARGETS GSL NAMESPACE ${namespace} FILE ${export_name}.cmake) set(gls_config_version "${CMAKE_CURRENT_BINARY_DIR}/Microsoft.GSLConfigVersion.cmake") write_basic_package_version_file(${gls_config_version} COMPATIBILITY SameMajorVersion ARCH_INDEPENDENT) install(FILES ${gls_config_version} DESTINATION ${cmake_files_install_dir}) install(FILES GSL.natvis DESTINATION ${cmake_files_install_dir}) endif() GSL-4.2.1/CMakeSettings.json000066400000000000000000000010411511561312500155330ustar00rootroot00000000000000{ "configurations": [ { "name": "x64-Debug", "generator": "Ninja", "configurationType": "Debug", "inheritEnvironments": [ "msvc_x64_x64" ], "buildRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\build\\${name}", "installRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\install\\${name}", "cmakeCommandArgs": "-DGSL_CXX_STANDARD=17", "buildCommandArgs": "-v", "ctestCommandArgs": "", "codeAnalysisRuleset": "CppCoreCheckRules.ruleset" } ] }GSL-4.2.1/CONTRIBUTING.md000066400000000000000000000037221511561312500144000ustar00rootroot00000000000000## Contributing to the Guidelines Support Library The Guidelines Support Library (GSL) contains functions and types that are suggested for use by the [C++ Core Guidelines](https://github.com/isocpp/CppCoreGuidelines). GSL design changes are made only as a result of modifications to the Guidelines. GSL is accepting contributions that improve or refine any of the types in this library as well as ports to other platforms. Changes should have an issue tracking the suggestion that has been approved by the maintainers. Your pull request should include a link to the bug that you are fixing. If you've submitted a PR, please post a comment in the associated issue to avoid duplication of effort. ## Legal You will need to complete a Contributor License Agreement (CLA). Briefly, this agreement testifies that you are granting us and the community permission to use the submitted change according to the terms of the project's license, and that the work being submitted is under appropriate copyright. Please submit a Contributor License Agreement (CLA) before submitting a pull request. You may visit https://cla.microsoft.com to sign digitally. ## Housekeeping Your pull request should: * Include a description of what your change intends to do * Be a child commit of a reasonably recent commit in the **main** branch * Requests need not be a single commit, but should be a linear sequence of commits (i.e. no merge commits in your PR) * It is desirable, but not necessary, for the tests to pass at each commit. Please see [README.md](./README.md) for instructions to build the test suite. * Have clear commit messages * e.g. "Fix issue", "Add tests for type", etc. * Include appropriate tests * Tests should include reasonable permutations of the target fix/change * Include baseline changes with your change * All changed code must have 100% code coverage * To avoid line ending issues, set `autocrlf = input` and `whitespace = cr-at-eol` in your git configuration GSL-4.2.1/GSL.natvis000066400000000000000000000022071511561312500140170ustar00rootroot00000000000000 {{ invoke = {invoke_}, action = {f_} }} invoke_ f_ {{ extent = {storage_.size_} }} storage_.size_ storage_.data_ value = {*ptr_} GSL-4.2.1/LICENSE000066400000000000000000000022051511561312500131470ustar00rootroot00000000000000Copyright (c) 2015 Microsoft Corporation. All rights reserved. This code is licensed under the MIT License (MIT). Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. GSL-4.2.1/README.md000066400000000000000000000350561511561312500134330ustar00rootroot00000000000000# GSL: Guidelines Support Library [![CI](https://github.com/Microsoft/GSL/actions/workflows/compilers.yml/badge.svg)](https://github.com/microsoft/GSL/actions/workflows/compilers.yml?query=branch%3Amain) [![vcpkg](https://img.shields.io/vcpkg/v/ms-gsl)](https://vcpkg.io/en/package/ms-gsl) The Guidelines Support Library (GSL) contains functions and types that are suggested for use by the [C++ Core Guidelines](https://github.com/isocpp/CppCoreGuidelines) maintained by the [Standard C++ Foundation](https://isocpp.org). This repo contains Microsoft's implementation of GSL. The entire implementation is provided inline in the headers under the [gsl](./include/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](./include/gsl/span)), it is simplest to just include [gsl/gsl](./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](./CONTRIBUTING.md) for more information about contributing. # Project Code of Conduct This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. # Usage of Third Party Libraries This project makes use of the [Google Test](https://github.com/google/googletest) testing library. Please see the [ThirdPartyNotices.txt](./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**][cg-views] | | [owner](docs/headers.md#user-content-H-pointers-owner) | ☑ | An alias for a raw pointer [not_null](docs/headers.md#user-content-H-pointers-not_null) | ☑ | Restricts a pointer/smart pointer to hold non-null values [span](docs/headers.md#user-content-H-span-span) | ☑ | A view over a contiguous sequence of memory. Based on the standardized version of `std::span`, however `gsl::span` enforces bounds checking. span_p | ☐ | Spans a range starting from a pointer to the first place for which the predicate is true [basic_zstring](docs/headers.md#user-content-H-zstring) | ☑ | A pointer to a C-string (zero-terminated array) with a templated char type [zstring](docs/headers.md#user-content-H-zstring) | ☑ | An alias to `basic_zstring` with dynamic extent and a char type of `char` [czstring](docs/headers.md#user-content-H-zstring) | ☑ | An alias to `basic_zstring` with dynamic extent and a char type of `const char` [wzstring](docs/headers.md#user-content-H-zstring) | ☑ | An alias to `basic_zstring` with dynamic extent and a char type of `wchar_t` [cwzstring](docs/headers.md#user-content-H-zstring) | ☑ | An alias to `basic_zstring` with dynamic extent and a char type of `const wchar_t` [u16zstring](docs/headers.md#user-content-H-zstring) | ☑ | An alias to `basic_zstring` with dynamic extent and a char type of `char16_t` [cu16zstring](docs/headers.md#user-content-H-zstring) | ☑ | An alias to `basic_zstring` with dynamic extent and a char type of `const char16_t` [u32zstring](docs/headers.md#user-content-H-zstring) | ☑ | An alias to `basic_zstring` with dynamic extent and a char type of `char32_t` [cu32zstring](docs/headers.md#user-content-H-zstring) | ☑ | An alias to `basic_zstring` with dynamic extent and a char type of `const char32_t` [**2. Owners**][cg-owners] | | stack_array | ☐ | A stack-allocated array dyn_array | ☐ | A heap-allocated array [**3. Assertions**][cg-assertions] | | [Expects](docs/headers.md#user-content-H-assert-expects) | ☑ | A precondition assertion; on failure it terminates [Ensures](docs/headers.md#user-content-H-assert-ensures) | ☑ | A postcondition assertion; on failure it terminates [**4. Utilities**][cg-utilities] | | move_owner | ☐ | A helper function that moves one `owner` to the other [final_action](docs/headers.md#user-content-H-util-final_action) | ☑ | A RAII style class that invokes a functor on its destruction [finally](docs/headers.md#user-content-H-util-finally) | ☑ | A helper function instantiating [final_action](docs/headers.md#user-content-H-util-final_action) [GSL_SUPPRESS](docs/headers.md#user-content-H-assert-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](docs/headers.md#user-content-H-util-index) | ☑ | A type to use for all container and array indexing (currently an alias for `std::ptrdiff_t`) [narrow](docs/headers.md#user-content-H-narrow-narrow) | ☑ | A checked version of `narrow_cast`; it can throw [narrowing_error](docs/headers.md#user-content-H-narrow-narrowing_error) [narrow_cast](docs/headers.md#user-content-H-util-narrow_cast) | ☑ | A narrowing cast for values and a synonym for `static_cast` [narrowing_error](docs/headers.md#user-content-H-narrow-narrowing_error) | ☑ | A custom exception type thrown by [narrow](docs/headers.md#user-content-H-narrow-narrow) [**5. Concepts**][cg-concepts] | ☐ | ## The following features do not exist in or have been removed from the C++ Core Guidelines: Feature | Supported? | Description -----------------------------------|:----------:|------------- [strict_not_null](docs/headers.md#user-content-H-pointers-strict_not_null) | ☑ | A stricter version of [not_null](docs/headers.md#user-content-H-pointers-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` ## The following features have been adopted by WG21. They are deprecated in GSL. Feature | Deprecated Since | Notes ------------------------------------------------------------------|------------------|------ [unique_ptr](docs/headers.md#user-content-H-pointers-unique_ptr) | C++11 | Use std::unique_ptr instead. [shared_ptr](docs/headers.md#user-content-H-pointers-shared_ptr) | C++11 | Use std::shared_ptr instead. [byte](docs/headers.md#user-content-H-byte-byte) | C++17 | Use std::byte instead. joining_thread | C++20 (Note: Not yet implemented in GSL) | Use std::jthread instead. This is based on [CppCoreGuidelines semi-specification](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#gsl-guidelines-support-library). [cg-views]: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#gslview-views [cg-owners]: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#gslowner-ownership-pointers [cg-assertions]: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#gslassert-assertions [cg-utilities]: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#gslutil-utilities [cg-concepts]: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#gslconcept-concepts # Quick Start ## Supported Compilers / Toolsets The GSL officially supports recent major versions of Visual Studio with both MSVC and LLVM, GCC, Clang, and XCode with Apple-Clang. For each of these major versions, the GSL officially supports C++14, C++17, C++20, and C++23 (when supported by the compiler). Below is a table showing the versions currently being tested (also see [.github/workflows/compilers.yml](the workflow).) Compiler |Toolset Versions Currently Tested :------- |--: GCC | 12, 13, 14 XCode | 14.3.1, 15.4 Clang | 16, 17, 18 Visual Studio with MSVC | VS2019, VS2022 Visual Studio with LLVM | VS2019, VS2022 --- 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](https://github.com/microsoft/GSL/workflows/CI_iOS/badge.svg?branch=main)](https://github.com/microsoft/GSL/actions/workflows/ios.yml?query=branch%3Amain) Android | [![CI_Android](https://github.com/microsoft/GSL/workflows/CI_Android/badge.svg?branch=main)](https://github.com/microsoft/GSL/actions/workflows/android.yml?query=branch%3Amain) 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](http://cmake.org), 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](https://github.com/Microsoft/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](https://github.com/Microsoft/vcpkg) 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](./include/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 ## 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. ```cmake 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](https://cmake.org/cmake/help/latest/module/FetchContent.html). This allows you to easily incorporate GSL into your project. ```cmake # 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.2.1" 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](./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. ## See Also For information on [Microsoft Gray Systems Lab (GSL)](https://aka.ms/gsl) of applied data management and system research see . GSL-4.2.1/SECURITY.md000066400000000000000000000053051511561312500137370ustar00rootroot00000000000000 ## Security Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/). If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/opensource/security/definition), please report it to us as described below. ## Reporting Security Issues **Please do not report security vulnerabilities through public GitHub issues.** Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/opensource/security/create-report). If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://aka.ms/opensource/security/pgpkey). You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://aka.ms/opensource/security/msrc). Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) * Full paths of source file(s) related to the manifestation of the issue * The location of the affected source code (tag/branch/commit or direct URL) * Any special configuration required to reproduce the issue * Step-by-step instructions to reproduce the issue * Proof-of-concept or exploit code (if possible) * Impact of the issue, including how an attacker might exploit the issue This information will help us triage your report more quickly. If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/opensource/security/bounty) page for more details about our active programs. ## Preferred Languages We prefer all communications to be in English. ## Policy Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/opensource/security/cvd). GSL-4.2.1/ThirdPartyNotices.txt000066400000000000000000000037461511561312500163350ustar00rootroot00000000000000 THIRD-PARTY SOFTWARE NOTICES AND INFORMATION Do Not Translate or Localize GSL: Guidelines Support Library incorporates third party material from the projects listed below. ------------------------------------------------------------------------------- Software: Google Test Owner: Google Inc. Source URL: github.com/google/googletest License: BSD 3 - Clause Text: Copyright 2008, Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------- GSL-4.2.1/docs/000077500000000000000000000000001511561312500130735ustar00rootroot00000000000000GSL-4.2.1/docs/headers.md000066400000000000000000001056301511561312500150350ustar00rootroot00000000000000The Guidelines Support Library (GSL) interface is very lightweight and exposed via a header-only library. This document attempts to document all of the headers and their exposed classes and functions. Types and functions are exported in the namespace `gsl`. See [GSL: Guidelines support library](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#S-gsl) # Headers - [``](#user-content-H-algorithms) - [``](#user-content-H-assert) - [``](#user-content-H-byte) - [``](#user-content-H-gsl) - [``](#user-content-H-narrow) - [``](#user-content-H-pointers) - [``](#user-content-H-span) - [``](#user-content-H-span_ext) - [``](#user-content-H-zstring) - [``](#user-content-H-util) ## `` This header contains some common algorithms that have been wrapped in GSL safety features. - [`gsl::copy`](#user-content-H-algorithms-copy) ### `gsl::copy` ```cpp template void copy(span src, span dest); ``` This function copies the content from the `src` [`span`](#user-content-H-span-span) to the `dest` [`span`](#user-content-H-span-span). It [`Expects`](#user-content-H-assert-expects) that the destination `span` is at least as large as the source `span`. ## `` This header contains some macros used for contract checking and suppressing code analysis warnings. See [GSL.assert: Assertions](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#SS-assertions) - [`GSL_SUPPRESS`](#user-content-H-assert-gsl_suppress) - [`Expects`](#user-content-H-assert-expects) - [`Ensures`](#user-content-H-assert-ensures) ### `GSL_SUPPRESS` This macro can be used to suppress a code analysis warning. The core guidelines request tools that check for the rules to respect suppressing a rule by writing `[[gsl::suppress(tag)]]` or `[[gsl::suppress(tag, justification: "message")]]`. Clang does not use exactly that syntax, but requires `tag` to be put in double quotes `[[gsl::suppress("tag")]]`. For portable code you can use `GSL_SUPPRESS(tag)`. See [In.force: Enforcement](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#inforce-enforcement). ### `Expects` This macro can be used for expressing a precondition. If the precondition is not held, then `std::terminate` will be called. See [I.6: Prefer `Expects()` for expressing preconditions](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#i6-prefer-expects-for-expressing-preconditions) ### `Ensures` This macro can be used for expressing a postcondition. If the postcondition is not held, then `std::terminate` will be called. See [I.8: Prefer `Ensures()` for expressing postconditions](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#i8-prefer-ensures-for-expressing-postconditions) ## `` This header contains the definition of a byte type, implementing `std::byte` before it was standardized into C++17. - [`gsl::byte`](#user-content-H-byte-byte) ### `gsl::byte` If `GSL_USE_STD_BYTE` is defined to be `1`, then `gsl::byte` will be an alias to `std::byte`. If `GSL_USE_STD_BYTE` is defined to be `0`, then `gsl::byte` will be a distinct type that implements the concept of byte. If `GSL_USE_STD_BYTE` is not defined, then the header file will check if `std::byte` is available (C\+\+17 or higher). If yes, `gsl::byte` will be an alias to `std::byte`, otherwise `gsl::byte` will be a distinct type that implements the concept of byte. ⚠ Take care when linking projects that were compiled with different language standards (before C\+\+17 and C\+\+17 or higher). If you do so, you might want to `#define GSL_USE_STD_BYTE 0` to a fixed value to be sure that both projects use exactly the same type. Otherwise you might get linker errors. See [SL.str.5: Use `std::byte` to refer to byte values that do not necessarily represent characters](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rstr-byte) ### Non-member functions ```cpp template ::value, bool> = true> constexpr byte& operator<<=(byte& b, IntegerType shift) noexcept; template ::value, bool> = true> constexpr byte operator<<(byte b, IntegerType shift) noexcept; template ::value, bool> = true> constexpr byte& operator>>=(byte& b, IntegerType shift) noexcept; template ::value, bool> = true> constexpr byte operator>>(byte b, IntegerType shift) noexcept; ``` Left or right shift a `byte` by a given number of bits. ```cpp constexpr byte& operator|=(byte& l, byte r) noexcept; constexpr byte operator|(byte l, byte r) noexcept; ``` Bitwise "or" of two `byte`s. ```cpp constexpr byte& operator&=(byte& l, byte r) noexcept; constexpr byte operator&(byte l, byte r) noexcept; ``` Bitwise "and" of two `byte`s. ```cpp constexpr byte& operator^=(byte& l, byte r) noexcept; constexpr byte operator^(byte l, byte r) noexcept; ``` Bitwise xor of two `byte`s. ```cpp constexpr byte operator~(byte b) noexcept; ``` Bitwise negation of a `byte`. Flips all bits. Zeroes become ones, ones become zeroes. ```cpp template ::value, bool> = true> constexpr IntegerType to_integer(byte b) noexcept; ``` Convert the given `byte` value to an integral type. ```cpp template constexpr byte to_byte(T t) noexcept; ``` Convert the given value to a `byte`. The template requires `T` to be an `unsigned char` so that no data loss can occur. If you want to convert an integer constant to a `byte` you probably want to call `to_byte()`. ```cpp template constexpr byte to_byte() noexcept; ``` Convert the given value `I` to a `byte`. The template requires `I` to be in the valid range 0..255 for a `gsl::byte`. ## `` This header is a convenience header that includes all other [GSL headers](#user-content-H). Since `` requires exceptions, it will only be included if exceptions are enabled. ## `` This header contains utility functions and classes, for narrowing casts, which require exceptions. The narrowing-related utilities that don't require exceptions are found inside [util](#user-content-H-util). See [GSL.util: Utilities](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#SS-utilities) - [`gsl::narrowing_error`](#user-content-H-narrow-narrowing_error) - [`gsl::narrow`](#user-content-H-narrow-narrow) ### `gsl::narrowing_error` `gsl::narrowing_error` is the exception thrown by [`gsl::narrow`](#user-content-H-narrow-narrow) when a narrowing conversion fails. It is derived from `std::exception`. ### `gsl::narrow` `gsl::narrow(x)` is a named cast that does a `static_cast(x)` for narrowing conversions with no signedness promotions. If the argument `x` cannot be represented in the target type `T`, then the function throws a [`gsl::narrowing_error`](#user-content-H-narrow-narrowing_error) (e.g., `narrow(-42)` and `narrow(300)` throw). Note: compare [`gsl::narrow_cast`](#user-content-H-util-narrow_cast) in header [util](#user-content-H-util). See [ES.46: Avoid lossy (narrowing, truncating) arithmetic conversions](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-narrowing) and [ES.49: If you must use a cast, use a named cast](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-casts-named) ## `` This header contains some pointer types. See [GSL.view](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#SS-views) - [`gsl::unique_ptr`](#user-content-H-pointers-unique_ptr) - [`gsl::shared_ptr`](#user-content-H-pointers-shared_ptr) - [`gsl::owner`](#user-content-H-pointers-owner) - [`gsl::not_null`](#user-content-H-pointers-not_null) - [`gsl::strict_not_null`](#user-content-H-pointers-strict_not_null) ### `gsl::unique_ptr` `gsl::unique_ptr` is an alias to `std::unique_ptr`. See [GSL.owner: Ownership pointers](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#SS-ownership) ### `gsl::shared_ptr` `gsl::shared_ptr` is an alias to `std::shared_ptr`. See [GSL.owner: Ownership pointers](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#SS-ownership) ### `gsl::owner` `gsl::owner` is designed as a safety mechanism for code that must deal directly with raw pointers that own memory. Ideally such code should be restricted to the implementation of low-level abstractions. `gsl::owner` can also be used as a stepping point in converting legacy code to use more modern RAII constructs such as smart pointers. `T` must be a pointer type (`std::is_pointer`). A `gsl::owner` is a typedef to `T`. It adds no runtime overhead whatsoever, as it is purely syntactic and does not add any runtime checks. Instead, it serves as an annotation for static analysis tools which check for memory safety, and as a code comprehension guide for human readers. See Enforcement section of [C.31: All resources acquired by a class must be released by the class’s destructor](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rc-dtor-release). ### `gsl::not_null` `gsl::not_null` restricts a pointer or smart pointer to only hold non-null values. It has no size overhead over `T`. The checks for ensuring that the pointer is not null are done in the constructor. There is no overhead when retrieving or dereferencing the checked pointer. When a nullptr check fails, `std::terminate` is called. See [F.23: Use a `not_null` to indicate that “null” is not a valid value](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rf-nullptr) #### Member Types ```cpp using element_type = T; ``` The type of the pointer or smart pointer that is managed by this object. #### Member functions ##### Construct/Copy ```cpp template ::value>> constexpr not_null(U&& u); template ::value>> constexpr not_null(T u); ``` Constructs a `gsl_owner` from a pointer that is convertible to `T` or that is a `T`. It [`Expects`](#user-content-H-assert-expects) that the provided pointer is not `== nullptr`. ```cpp template ::value>> constexpr not_null(const not_null& other); ``` Constructs a `gsl_owner` from another `gsl_owner` where the other pointer is convertible to `T`. It [`Expects`](#user-content-H-assert-expects) that the provided pointer is not `== nullptr`. ```cpp not_null(const not_null& other) = default; not_null& operator=(const not_null& other) = default; ``` Copy construction and assignment. ```cpp not_null(std::nullptr_t) = delete; not_null& operator=(std::nullptr_t) = delete; ``` Construction from `std::nullptr_t` and assignment of `std::nullptr_t` are explicitly deleted. ##### Modifiers ```cpp not_null& operator++() = delete; not_null& operator--() = delete; not_null operator++(int) = delete; not_null operator--(int) = delete; not_null& operator+=(std::ptrdiff_t) = delete; not_null& operator-=(std::ptrdiff_t) = delete; ``` Explicitly deleted operators. Pointers point to single objects ([I.13: Do not pass an array as a single pointer](http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Ri-array)), so don't allow these operators. ##### Observers ```cpp constexpr details::value_or_reference_return_t get() const; constexpr operator T() const { return get(); } ``` Get the underlying pointer. ```cpp constexpr decltype(auto) operator->() const { return get(); } constexpr decltype(auto) operator*() const { return *get(); } ``` Dereference the underlying pointer. ```cpp void operator[](std::ptrdiff_t) const = delete; ``` Array index operator is explicitly deleted. Pointers point to single objects ([I.13: Do not pass an array as a single pointer](http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Ri-array)), so don't allow treating them as an array. ```cpp void swap(not_null& other) { std::swap(ptr_, other.ptr_); } ``` Swaps contents with another `gsl::not_null` object. #### Non-member functions ```cpp template auto make_not_null(T&& t) noexcept; ``` Creates a `gsl::not_null` object, deducing the target type from the type of the argument. ```cpp template ::value && std::is_move_constructible::value, bool> = true> void swap(not_null& a, not_null& b); ``` Swaps the contents of two `gsl::not_null` objects. ```cpp template auto operator==(const not_null& lhs, const not_null& rhs) noexcept(noexcept(lhs.get() == rhs.get())) -> decltype(lhs.get() == rhs.get()); template auto operator!=(const not_null& lhs, const not_null& rhs) noexcept(noexcept(lhs.get() != rhs.get())) -> decltype(lhs.get() != rhs.get()); template auto operator<(const not_null& lhs, const not_null& rhs) noexcept(noexcept(lhs.get() < rhs.get())) -> decltype(lhs.get() < rhs.get()); template auto operator<=(const not_null& lhs, const not_null& rhs) noexcept(noexcept(lhs.get() <= rhs.get())) -> decltype(lhs.get() <= rhs.get()); template auto operator>(const not_null& lhs, const not_null& rhs) noexcept(noexcept(lhs.get() > rhs.get())) -> decltype(lhs.get() > rhs.get()); template auto operator>=(const not_null& lhs, const not_null& rhs) noexcept(noexcept(lhs.get() >= rhs.get())) -> decltype(lhs.get() >= rhs.get()); ``` Comparison of pointers that are convertible to each other. ##### Input/Output ```cpp template std::ostream& operator<<(std::ostream& os, const not_null& val); ``` Performs stream output on a `not_null` pointer, invoking `os << val.get()`. This function is only available when `GSL_NO_IOSTREAMS` is not defined. ##### Modifiers ```cpp template std::ptrdiff_t operator-(const not_null&, const not_null&) = delete; template not_null operator-(const not_null&, std::ptrdiff_t) = delete; template not_null operator+(const not_null&, std::ptrdiff_t) = delete; template not_null operator+(std::ptrdiff_t, const not_null&) = delete; ``` Addition and subtraction are explicitly deleted. Pointers point to single objects ([I.13: Do not pass an array as a single pointer](http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Ri-array)), so don't allow these operators. ##### STL integration ```cpp template struct std::hash> { ... }; ``` Specialization of `std::hash` for `gsl::not_null`. ### `gsl::strict_not_null` `strict_not_null` is the same as [`not_null`](#user-content-H-pointers-not_null) except that the constructors are `explicit`. The free function that deduces the target type from the type of the argument and creates a `gsl::strict_not_null` object is `gsl::make_strict_not_null`. ## `` This header file exports the class `gsl::span`, a bounds-checked implementation of `std::span`. - [`gsl::span`](#user-content-H-span-span) ### `gsl::span` ```cpp template class span; ``` `gsl::span` is a view over memory. It does not own the memory and is only a way to access contiguous sequences of objects. The extent can be either a fixed size or [`gsl::dynamic_extent`](#user-content-H-span_ext-dynamic_extent). The `gsl::span` is based on the standardized version of `std::span` which was added to C++20. Originally, the plan was to deprecate `gsl::span` when `std::span` finished standardization, however that plan changed when the runtime bounds checking was removed from `std::span`'s design. The only difference between `gsl::span` and `std::span` is that `gsl::span` strictly enforces runtime bounds checking. Any violations of the bounds check results in termination of the program. Like `gsl::span`, `gsl::span`'s iterators also differ from `std::span`'s iterator in that all access operations are bounds checked. #### Which version of span should I use? ##### Use `gsl::span` if - you want to guarantee bounds safety in your project. - All data accessing operations use bounds checking to ensure you are only accessing valid memory. - your project uses C++14 or C++17. - `std::span` is not available as it was not introduced into the STL until C++20. ##### Use `std::span` if - your project is C++20 and you need the performance offered by `std::span`. #### Types ```cpp using element_type = ElementType; using value_type = std::remove_cv_t; using size_type = std::size_t; using pointer = element_type*; using const_pointer = const element_type*; using reference = element_type&; using const_reference = const element_type&; using difference_type = std::ptrdiff_t; using iterator = details::span_iterator; using reverse_iterator = std::reverse_iterator; ``` #### Member functions ```cpp constexpr span() noexcept; ``` Constructs an empty `span`. This constructor is only available if `Extent` is 0 or [`gsl::dynamic_extent`](#user-content-H-span_ext-dynamic_extent). `span::data()` will return `nullptr`. ```cpp constexpr explicit(Extent != gsl::dynamic_extent) span(pointer ptr, size_type count) noexcept; ``` Constructs a `span` from a pointer and a size. If `Extent` is not [`gsl::dynamic_extent`](#user-content-H-span_ext-dynamic_extent), then the constructor [`Expects`](#user-content-H-assert-expects) that `count == Extent`. ```cpp constexpr explicit(Extent != gsl::dynamic_extent) span(pointer firstElem, pointer lastElem) noexcept; ``` Constructs a `span` from a pointer to the begin and the end of the data. If `Extent` is not [`gsl::dynamic_extent`](#user-content-H-span_ext-dynamic_extent), then the constructor [`Expects`](#user-content-H-assert-expects) that `lastElem - firstElem == Extent`. ```cpp template constexpr span(element_type (&arr)[N]) noexcept; ``` Constructs a `span` from a C style array. This overload is available if `Extent ==`[`gsl::dynamic_extent`](#user-content-H-span_ext-dynamic_extent) or `N == Extent`. ```cpp template constexpr span(std::array& arr) noexcept; template constexpr span(const std::array& arr) noexcept; ``` Constructs a `span` from a `std::array`. These overloads are available if `Extent ==`[`gsl::dynamic_extent`](#user-content-H-span_ext-dynamic_extent) or `N == Extent`, and if the array can be interpreted as a `ElementType` array. ```cpp template constexpr explicit(Extent != gsl::dynamic_extent) span(Container& cont) noexcept; template constexpr explicit(Extent != gsl::dynamic_extent) span(const Container& cont) noexcept; ``` Constructs a `span` from a container. These overloads are available if `Extent ==`[`gsl::dynamic_extent`](#user-content-H-span_ext-dynamic_extent) or `N == Extent`, and if the container can be interpreted as a contiguous `ElementType` array. ```cpp constexpr span(const span& other) noexcept = default; ``` Copy constructor. ```cpp template explicit(Extent != gsl::dynamic_extent && OtherExtent == dynamic_extent) constexpr span(const span& other) noexcept; ``` Constructs a `span` from another `span`. This constructor is available if `OtherExtent == Extent || Extent ==`[`gsl::dynamic_extent`](#user-content-H-span_ext-dynamic_extent)` || OtherExtent ==`[`gsl::dynamic_extent`](#user-content-H-span_ext-dynamic_extent) and if `ElementType` and `OtherElementType` are compatible. If `Extent !=`[`gsl::dynamic_extent`](#user-content-H-span_ext-dynamic_extent) and `OtherExtent ==`[`gsl::dynamic_extent`](#user-content-H-span_ext-dynamic_extent), then the constructor [`Expects`](#user-content-H-assert-expects) that `other.size() == Extent`. ```cpp constexpr span& operator=(const span& other) noexcept = default; ``` Copy assignment ```cpp template constexpr span first() const noexcept; constexpr span first(size_type count) const noexcept; template constexpr span last() const noexcept; constexpr span last(size_type count) const noexcept; ``` Return a subspan of the first/last `Count` elements. [`Expects`](#user-content-H-assert-expects) that `Count` does not exceed the `span`'s size. ```cpp template constexpr auto subspan() const noexcept; constexpr span subspan(size_type offset, size_type count = dynamic_extent) const noexcept; ``` Return a subspan starting at `offset` and having size `count`. [`Expects`](#user-content-H-assert-expects) that `offset` does not exceed the `span`'s size, and that `offset == `[`gsl::dynamic_extent`](#user-content-H-span_ext-dynamic_extent) or `offset + count` does not exceed the `span`'s size. If `count` is `gsl::dynamic_extent`, the number of elements in the subspan is `size() - offset`. ```cpp constexpr size_type size() const noexcept; constexpr size_type size_bytes() const noexcept; ``` Returns the size respective the size in bytes of the `span`. ```cpp constexpr bool empty() const noexcept; ``` Is the `span` empty? ```cpp constexpr reference operator[](size_type idx) const noexcept; ``` Returns a reference to the element at the given index. [`Expects`](#user-content-H-assert-expects) that `idx` is less than the `span`'s size. ```cpp constexpr reference front() const noexcept; constexpr reference back() const noexcept; ``` Returns a reference to the first/last element in the `span`. [`Expects`](#user-content-H-assert-expects) that the `span` is not empty. ```cpp constexpr pointer data() const noexcept; ``` Returns a pointer to the beginning of the contained data. ```cpp constexpr iterator begin() const noexcept; constexpr iterator end() const noexcept; constexpr reverse_iterator rbegin() const noexcept; constexpr reverse_iterator rend() const noexcept; ``` Returns an iterator to the first/last normal/reverse iterator. ```cpp template span(Type (&)[Extent]) -> span; template span(std::array&) -> span; template span(const std::array&) -> span; template ().data())>> span(Container&) -> span; template ().data())>> span(const Container&) -> span; ``` Deduction guides. ```cpp template span::value> as_bytes(span s) noexcept; template span::value> as_writable_bytes(span s) noexcept; ``` Converts a `span` into a `span` of `byte`s. `as_writable_bytes` will only be available for non-const `ElementType`s. ## `` This file is a companion for and included by [``](#user-content-H-span), and should not be used on its own. It contains useful features that aren't part of the `std::span` API as found inside the STL `` header (with the exception of [`gsl::dynamic_extent`](#user-content-H-span_ext-dynamic_extent), which is included here due to implementation constraints). - [`gsl::dynamic_extent`](#user-content-H-span_ext-dynamic_extent) - [`gsl::span`](#user-content-H-span_ext-span) - [`gsl::span` comparison operators](#user-content-H-span_ext-span_comparison_operators) - [`gsl::make_span`](#user-content-H-span_ext-make_span) - [`gsl::at`](#user-content-H-span_ext-at) - [`gsl::ssize`](#user-content-H-span_ext-ssize) - [`gsl::span` iterator functions](#user-content-H-span_ext-span_iterator_functions) ### `gsl::dynamic_extent` Defines the extent value to be used by all `gsl::span` with dynamic extent. Note: `std::dynamic_extent` is exposed by the STL `` header and so ideally `gsl::dynamic_extent` would be under [``](#user-content-H-span), but to avoid cyclic dependency issues it is under `` instead. ### `gsl::span` ```cpp template class span; ``` Forward declaration of `gsl::span`. ### `gsl::span` comparison operators ```cpp template constexpr bool operator==(span l, span r); template constexpr bool operator!=(span l, span r); template constexpr bool operator<(span l, span r); template constexpr bool operator<=(span l, span r); template constexpr bool operator>(span l, span r); template constexpr bool operator>=(span l, span r); ``` The comparison operators for two `span`s lexicographically compare the elements in the `span`s. ### `gsl::make_span` ```cpp template constexpr span make_span(ElementType* ptr, typename span::size_type count); template constexpr span make_span(ElementType* firstElem, ElementType* lastElem); template constexpr span make_span(ElementType (&arr)[N]) noexcept; template constexpr span make_span(Container& cont); template constexpr span make_span(const Container& cont); ``` Utility function for creating a `span` with [`gsl::dynamic_extent`](#user-content-H-span_ext-dynamic_extent) from - pointer and length, - pointer to start and pointer to end, - a C style array, or - a container. ### `gsl::at` ```cpp template constexpr ElementType& at(span s, index i); ``` The function `gsl::at` offers a safe way to access data with index bounds checking. This is the specialization of [`gsl::at`](#user-content-H-util-at) for [`span`](#user-content-H-span-span). It returns a reference to the `i`th element and [`Expects`](#user-content-H-assert-expects) that the provided index is within the bounds of the `span`. Note: `gsl::at` supports indexes up to `PTRDIFF_MAX`. ### `gsl::ssize` ```cpp template constexpr std::ptrdiff_t ssize(const span& s) noexcept; ``` Return the size of a [`span`](#user-content-H-span-span) as a `ptrdiff_t`. ### `gsl::span` iterator functions ```cpp template constexpr typename span::iterator begin(const span& s) noexcept; template constexpr typename span::iterator end(const span& s) noexcept; template constexpr typename span::reverse_iterator rbegin(const span& s) noexcept; template constexpr typename span::reverse_iterator rend(const span& s) noexcept; template constexpr typename span::iterator cbegin(const span& s) noexcept; template constexpr typename span::iterator cend(const span& s) noexcept; template constexpr typename span::reverse_iterator crbegin(const span& s) noexcept; template constexpr typename span::reverse_iterator crend(const span& s) noexcept; ``` Free functions for getting a non-const/const begin/end normal/reverse iterator for a [`span`](#user-content-H-span-span). ## `` This header exports a family of `*zstring` types. A `gsl::XXzstring` is a typedef to `T`. It adds no checks whatsoever, it is just for having a syntax to describe that a pointer points to a zero terminated C style string. This helps static code analysis, and it helps human readers. `basic_zstring` is a pointer to a C-string (zero-terminated array) with a templated char type. Used to implement the rest of the `*zstring` family. `zstring` is a zero terminated `char` string. `czstring` is a const zero terminated `char` string. `wzstring` is a zero terminated `wchar_t` string. `cwzstring` is a const zero terminated `wchar_t` string. `u16zstring` is a zero terminated `char16_t` string. `cu16zstring` is a const zero terminated `char16_t` string. `u32zstring` is a zero terminated `char32_t` string. `cu32zstring` is a const zero terminated `char32_t` string. See [GSL.view](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#SS-views) and [SL.str.3: Use zstring or czstring to refer to a C-style, zero-terminated, sequence of characters](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rstr-zstring). ## `` This header contains utility functions and classes. This header works without exceptions being available. The parts that require exceptions being available are in their own header file [narrow](#user-content-H-narrow). See [GSL.util: Utilities](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#SS-utilities) - [`gsl::narrow_cast`](#user-content-H-util-narrow_cast) - [`gsl::final_action`](#user-content-H-util-final_action) - [`gsl::at`](#user-content-H-util-at) ### `gsl::index` An alias to `std::ptrdiff_t`. It serves as the index type for all container indexes/subscripts/sizes. ### `gsl::narrow_cast` `gsl::narrow_cast(x)` is a named cast that is identical to a `static_cast(x)`. It exists to make clear to static code analysis tools and to human readers that a lossy conversion is acceptable. Note: compare the throwing version [`gsl::narrow`](#user-content-H-narrow-narrow) in header [narrow](#user-content-H-narrow). See [ES.46: Avoid lossy (narrowing, truncating) arithmetic conversions](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-narrowing) and [ES.49: If you must use a cast, use a named cast](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-casts-named) ### `gsl::final_action` ```cpp template class final_action { ... }; ``` `final_action` allows you to ensure something gets run at the end of a scope. See [E.19: Use a final_action object to express cleanup if no suitable resource handle is available](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Re-finally) #### Member functions ```cpp explicit final_action(const F& ff) noexcept; explicit final_action(F&& ff) noexcept; ``` Construct an object with the action to invoke in the destructor. ```cpp ~final_action() noexcept; ``` The destructor will call the action that was passed in the constructor. ```cpp final_action(final_action&& other) noexcept; final_action(const final_action&) = delete; void operator=(const final_action&) = delete; void operator=(final_action&&) = delete; ``` Move construction is allowed. Copy construction is deleted. Copy and move assignment are also explicitly deleted. #### Non-member functions ```cpp template auto finally(F&& f) noexcept; ``` Creates a `gsl::final_action` object, deducing the template argument type from the type of the argument. ### `gsl::at` The function `gsl::at` offers a safe way to access data with index bounds checking. Note: `gsl::at` supports indexes up to `PTRDIFF_MAX`. See [ES.42: Keep use of pointers simple and straightforward](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-ptr) ```cpp template constexpr T& at(T (&arr)[N], const index i); ``` This overload returns a reference to the `i`s element of a C style array `arr`. It [`Expects`](#user-content-H-assert-expects) that the provided index is within the bounds of the array. ```cpp template constexpr auto at(Cont& cont, const index i) -> decltype(cont[cont.size()]); ``` This overload returns a reference to the `i`s element of the container `cont`. It [`Expects`](#user-content-H-assert-expects) that the provided index is within the bounds of the array. ```cpp template constexpr T at(const std::initializer_list cont, const index i); ``` This overload returns a reference to the `i`s element of the initializer list `cont`. It [`Expects`](#user-content-H-assert-expects) that the provided index is within the bounds of the array. ```cpp template constexpr auto at(std::span sp, const index i) -> decltype(sp[sp.size()]); ``` This overload returns a reference to the `i`s element of the `std::span` `sp`. It [`Expects`](#user-content-H-assert-expects) that the provided index is within the bounds of the array. For [`gsl::at`](#user-content-H-span_ext-at) for [`gsl::span`](#user-content-H-span-span) see header [`span_ext`](#user-content-H-span_ext). ```cpp template ::value && std::is_move_constructible::value>> void swap(T& a, T& b); ``` Swaps the contents of two objects. Exists only to specialize `gsl::swap(gsl::not_null&, gsl::not_null&)`. GSL-4.2.1/include/000077500000000000000000000000001511561312500135665ustar00rootroot00000000000000GSL-4.2.1/include/CMakeLists.txt000066400000000000000000000007441511561312500163330ustar00rootroot00000000000000# Add include folders to the library and targets that consume it # the SYSTEM keyword suppresses warnings for users of the library # # By adding this directory as an include directory the user gets a # namespace effect. # # IE: # #include if(PROJECT_IS_TOP_LEVEL) target_include_directories(GSL INTERFACE $) else() target_include_directories(GSL SYSTEM INTERFACE $) endif() GSL-4.2.1/include/gsl/000077500000000000000000000000001511561312500143535ustar00rootroot00000000000000GSL-4.2.1/include/gsl/algorithm000066400000000000000000000044471511561312500162750ustar00rootroot00000000000000/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// #ifndef GSL_ALGORITHM_H #define GSL_ALGORITHM_H #include "./assert" // for Expects #include "./span" // for dynamic_extent, span #include // for copy_n #include // for ptrdiff_t #include // for is_assignable #ifdef _MSC_VER #pragma warning(push) // turn off some warnings that are noisy about our Expects statements #pragma warning(disable : 4127) // conditional expression is constant #pragma warning(disable : 4996) // unsafe use of std::copy_n #endif // _MSC_VER namespace gsl { // Note: this will generate faster code than std::copy using span iterator in older msvc+stl // not necessary for msvc since VS2017 15.8 (_MSC_VER >= 1915) template void copy(span src, span dest) { static_assert(std::is_assignable::value, "Elements of source span can not be assigned to elements of destination span"); static_assert(SrcExtent == dynamic_extent || DestExtent == dynamic_extent || (SrcExtent <= DestExtent), "Source range is longer than target range"); Expects(dest.size() >= src.size()); // clang-format off GSL_SUPPRESS(stl.1) // NO-FORMAT: attribute // clang-format on std::copy_n(src.data(), src.size(), dest.data()); } } // namespace gsl #ifdef _MSC_VER #pragma warning(pop) #endif // _MSC_VER #endif // GSL_ALGORITHM_H GSL-4.2.1/include/gsl/assert000066400000000000000000000076241511561312500156100ustar00rootroot00000000000000/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// #ifndef GSL_ASSERT_H #define GSL_ASSERT_H // // Temporary until MSVC STL supports no-exceptions mode. // Currently terminate is a no-op in this mode, so we add termination behavior back // #if defined(_MSC_VER) && (defined(_KERNEL_MODE) || (defined(_HAS_EXCEPTIONS) && !_HAS_EXCEPTIONS)) #define GSL_KERNEL_MODE #define GSL_MSVC_USE_STL_NOEXCEPTION_WORKAROUND #include #define RANGE_CHECKS_FAILURE 0 #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-noreturn" #endif // defined(__clang__) #else // defined(_MSC_VER) && (defined(_KERNEL_MODE) || (defined(_HAS_EXCEPTIONS) && // !_HAS_EXCEPTIONS)) #include #endif // defined(_MSC_VER) && (defined(_KERNEL_MODE) || (defined(_HAS_EXCEPTIONS) && // !_HAS_EXCEPTIONS)) // // make suppress attributes parse for some compilers // Hopefully temporary until suppression standardization occurs // #if defined(__clang__) #define GSL_SUPPRESS(x) [[gsl::suppress(#x)]] #else #if defined(_MSC_VER) && !defined(__INTEL_COMPILER) && !defined(__NVCC__) #define GSL_SUPPRESS(x) [[gsl::suppress(x)]] #else #define GSL_SUPPRESS(x) #endif // _MSC_VER #endif // __clang__ #if defined(__clang__) || defined(__GNUC__) #define GSL_LIKELY(x) __builtin_expect(!!(x), 1) #define GSL_UNLIKELY(x) __builtin_expect(!!(x), 0) #else #define GSL_LIKELY(x) (!!(x)) #define GSL_UNLIKELY(x) (!!(x)) #endif // defined(__clang__) || defined(__GNUC__) // // GSL_ASSUME(cond) // // Tell the optimizer that the predicate cond must hold. It is unspecified // whether or not cond is actually evaluated. // #ifdef _MSC_VER #define GSL_ASSUME(cond) __assume(cond) #elif defined(__GNUC__) #define GSL_ASSUME(cond) ((cond) ? static_cast(0) : __builtin_unreachable()) #else #define GSL_ASSUME(cond) static_cast((cond) ? 0 : 0) #endif // // GSL.assert: assertions // namespace gsl { namespace details { #if defined(GSL_MSVC_USE_STL_NOEXCEPTION_WORKAROUND) typedef void(__cdecl* terminate_handler)(); // clang-format off GSL_SUPPRESS(f.6) // NO-FORMAT: attribute // clang-format on [[noreturn]] inline void __cdecl default_terminate_handler() { __fastfail(RANGE_CHECKS_FAILURE); } inline gsl::details::terminate_handler& get_terminate_handler() noexcept { static terminate_handler handler = &default_terminate_handler; return handler; } #endif // defined(GSL_MSVC_USE_STL_NOEXCEPTION_WORKAROUND) [[noreturn]] inline void terminate() noexcept { #if defined(GSL_MSVC_USE_STL_NOEXCEPTION_WORKAROUND) (*gsl::details::get_terminate_handler())(); #else std::terminate(); #endif // defined(GSL_MSVC_USE_STL_NOEXCEPTION_WORKAROUND) } } // namespace details } // namespace gsl #define GSL_CONTRACT_CHECK(type, cond) \ (GSL_LIKELY(cond) ? static_cast(0) : gsl::details::terminate()) #define Expects(cond) GSL_CONTRACT_CHECK("Precondition", cond) #define Ensures(cond) GSL_CONTRACT_CHECK("Postcondition", cond) #if defined(GSL_MSVC_USE_STL_NOEXCEPTION_WORKAROUND) && defined(__clang__) #pragma clang diagnostic pop #endif #endif // GSL_ASSERT_H GSL-4.2.1/include/gsl/byte000066400000000000000000000147301511561312500152460ustar00rootroot00000000000000/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// #ifndef GSL_BYTE_H #define GSL_BYTE_H #include "./util" // for GSL_DEPRECATED #include #ifdef _MSC_VER #pragma warning(push) // Turn MSVC /analyze rules that generate too much noise. TODO: fix in the tool. #pragma warning(disable : 26493) // don't use c-style casts // TODO: MSVC suppression in templates // does not always work #ifndef GSL_USE_STD_BYTE // this tests if we are under MSVC and the standard lib has std::byte and it is enabled #if defined(__cpp_lib_byte) && __cpp_lib_byte >= 201603 #define GSL_USE_STD_BYTE 1 #else // defined(__cpp_lib_byte) && __cpp_lib_byte >= 201603 #define GSL_USE_STD_BYTE 0 #endif // defined(__cpp_lib_byte) && __cpp_lib_byte >= 201603 #endif // GSL_USE_STD_BYTE #else // _MSC_VER #ifndef GSL_USE_STD_BYTE #include /* __cpp_lib_byte */ // this tests if we are under GCC or Clang with enough -std=c++1z power to get us std::byte // also check if libc++ version is sufficient (> 5.0) or libstdc++ actually contains std::byte #if defined(__cplusplus) && (__cplusplus >= 201703L) && \ (defined(__cpp_lib_byte) && (__cpp_lib_byte >= 201603) || \ defined(_LIBCPP_VERSION) && (_LIBCPP_VERSION >= 5000)) #define GSL_USE_STD_BYTE 1 #else // defined(__cplusplus) && (__cplusplus >= 201703L) && // (defined(__cpp_lib_byte) && (__cpp_lib_byte >= 201603) || // defined(_LIBCPP_VERSION) && (_LIBCPP_VERSION >= 5000)) #define GSL_USE_STD_BYTE 0 #endif // defined(__cplusplus) && (__cplusplus >= 201703L) && // (defined(__cpp_lib_byte) && (__cpp_lib_byte >= 201603) || // defined(_LIBCPP_VERSION) && (_LIBCPP_VERSION >= 5000)) #endif // GSL_USE_STD_BYTE #endif // _MSC_VER // Use __may_alias__ attribute on gcc and clang #if defined __clang__ || (defined(__GNUC__) && __GNUC__ > 5) #define byte_may_alias __attribute__((__may_alias__)) #else // defined __clang__ || defined __GNUC__ #define byte_may_alias #endif // defined __clang__ || defined __GNUC__ #if GSL_USE_STD_BYTE #include #endif namespace gsl { #if GSL_USE_STD_BYTE namespace impl { // impl::byte is used by gsl::as_bytes so our own code does not trigger a deprecation warning as would be the case when we used gsl::byte. // Users of GSL should only use gsl::byte, not gsl::impl::byte. using byte = std::byte; } using byte GSL_DEPRECATED("Use std::byte instead.") = std::byte; using std::to_integer; #else // GSL_USE_STD_BYTE // This is a simple definition for now that allows // use of byte within span<> to be standards-compliant enum class byte_may_alias byte : unsigned char { }; namespace impl { // impl::byte is used by gsl::as_bytes so our own code does not trigger a deprecation warning as would be the case when we used gsl::byte. // Users of GSL should only use gsl::byte, not gsl::impl::byte. using byte = gsl::byte; } template ::value, bool> = true> constexpr byte& operator<<=(byte& b, IntegerType shift) noexcept { return b = byte(static_cast(b) << shift); } template ::value, bool> = true> constexpr byte operator<<(byte b, IntegerType shift) noexcept { return byte(static_cast(b) << shift); } template ::value, bool> = true> constexpr byte& operator>>=(byte& b, IntegerType shift) noexcept { return b = byte(static_cast(b) >> shift); } template ::value, bool> = true> constexpr byte operator>>(byte b, IntegerType shift) noexcept { return byte(static_cast(b) >> shift); } constexpr byte& operator|=(byte& l, byte r) noexcept { return l = byte(static_cast(l) | static_cast(r)); } constexpr byte operator|(byte l, byte r) noexcept { return byte(static_cast(l) | static_cast(r)); } constexpr byte& operator&=(byte& l, byte r) noexcept { return l = byte(static_cast(l) & static_cast(r)); } constexpr byte operator&(byte l, byte r) noexcept { return byte(static_cast(l) & static_cast(r)); } constexpr byte& operator^=(byte& l, byte r) noexcept { return l = byte(static_cast(l) ^ static_cast(r)); } constexpr byte operator^(byte l, byte r) noexcept { return byte(static_cast(l) ^ static_cast(r)); } constexpr byte operator~(byte b) noexcept { return byte(~static_cast(b)); } template ::value, bool> = true> constexpr IntegerType to_integer(byte b) noexcept { return static_cast(b); } #endif // GSL_USE_STD_BYTE template // NOTE: need suppression since c++14 does not allow "return {t}" // GSL_SUPPRESS(type.4) // NO-FORMAT: attribute // TODO: suppression does not work constexpr gsl::impl::byte to_byte(T t) noexcept { static_assert(std::is_same::value, "gsl::to_byte(t) must be provided an unsigned char, otherwise data loss may occur. " "If you are calling to_byte with an integer constant use: gsl::to_byte() version."); return gsl::impl::byte(t); } template constexpr gsl::impl::byte to_byte() noexcept { static_assert(I >= 0 && I <= 255, "gsl::byte only has 8 bits of storage, values must be in range 0-255"); return static_cast(I); } } // namespace gsl #ifdef _MSC_VER #pragma warning(pop) #endif // _MSC_VER #endif // GSL_BYTE_H GSL-4.2.1/include/gsl/gsl000066400000000000000000000023211511561312500150610ustar00rootroot00000000000000/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// #ifndef GSL_GSL_H #define GSL_GSL_H // IWYU pragma: begin_exports #include "./algorithm" // copy #include "./assert" // Ensures/Expects #include "./byte" // byte #include "./pointers" // owner, not_null #include "./span" // span #include "./zstring" // zstring #include "./util" // finally()/narrow_cast()... #ifdef __cpp_exceptions #include "./narrow" // narrow() #endif // IWYU pragma: end_exports #endif // GSL_GSL_H GSL-4.2.1/include/gsl/narrow000066400000000000000000000065241511561312500156150ustar00rootroot00000000000000/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// #ifndef GSL_NARROW_H #define GSL_NARROW_H #include "./assert" // for GSL_SUPPRESS #include "./util" // for narrow_cast #include // for std::exception namespace gsl { struct narrowing_error : public std::exception { const char* what() const noexcept override { return "narrowing_error"; } }; // narrow() : a checked version of narrow_cast() that throws if the cast changed the value template ::value>::type* = nullptr> // clang-format off GSL_SUPPRESS(type.1) // NO-FORMAT: attribute GSL_SUPPRESS(es.46) // NO-FORMAT: attribute // The warning suggests that a floating->unsigned conversion can occur // in the static_cast below, and that gsl::narrow should be used instead. // Suppress this warning, since gsl::narrow is defined in terms of // static_cast // clang-format on constexpr T narrow(U u) { constexpr const bool is_different_signedness = (std::is_signed::value != std::is_signed::value); GSL_SUPPRESS(es.103) // NO-FORMAT: attribute // don't overflow GSL_SUPPRESS(es.104) // NO-FORMAT: attribute // don't underflow GSL_SUPPRESS(p.2) // NO-FORMAT: attribute // don't rely on undefined behavior const T t = narrow_cast(u); // While this is technically undefined behavior in some cases (i.e., if the source value is of floating-point type // and cannot fit into the destination integral type), the resultant behavior is benign on the platforms // that we target (i.e., no hardware trap representations are hit). #if defined(__clang__) || defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wfloat-equal" #endif // Note: NaN will always throw, since NaN != NaN if (static_cast(t) != u || (is_different_signedness && ((t < T{}) != (u < U{})))) { throw narrowing_error{}; } #if defined(__clang__) || defined(__GNUC__) #pragma GCC diagnostic pop #endif return t; } template ::value>::type* = nullptr> // clang-format off GSL_SUPPRESS(type.1) // NO-FORMAT: attribute // clang-format on constexpr T narrow(U u) { const T t = narrow_cast(u); if (static_cast(t) != u) { throw narrowing_error{}; } return t; } } // namespace gsl #endif // GSL_NARROW_H GSL-4.2.1/include/gsl/pointers000066400000000000000000000304741511561312500161510ustar00rootroot00000000000000/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// #ifndef GSL_POINTERS_H #define GSL_POINTERS_H #include "./assert" // for Ensures, Expects #include "./util" // for GSL_DEPRECATED #include // for ptrdiff_t, nullptr_t, size_t #include // for less, greater #include // for shared_ptr, unique_ptr, hash #include // for enable_if_t, is_convertible, is_assignable #include // for declval, forward #if !defined(GSL_NO_IOSTREAMS) #include // for ostream #endif // !defined(GSL_NO_IOSTREAMS) namespace gsl { namespace details { template struct is_comparable_to_nullptr : std::false_type { }; template struct is_comparable_to_nullptr< T, std::enable_if_t() != nullptr), bool>::value>> : std::true_type { }; // Resolves to the more efficient of `const T` or `const T&`, in the context of returning a const-qualified value // of type T. // // Copied from cppfront's implementation of the CppCoreGuidelines F.16 (https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rf-in) template using value_or_reference_return_t = std::conditional_t< sizeof(T) < 2*sizeof(void*) && std::is_trivially_copy_constructible::value, const T, const T&>; } // namespace details // // GSL.owner: ownership pointers // template using shared_ptr GSL_DEPRECATED("Use std::shared_ptr instead") = std::shared_ptr; template using unique_ptr GSL_DEPRECATED("Use std::unique_ptr instead") = std::unique_ptr; // // owner // // `gsl::owner` is designed as a safety mechanism for code that must deal directly with raw pointers that own memory. // Ideally such code should be restricted to the implementation of low-level abstractions. `gsl::owner` can also be used // as a stepping point in converting legacy code to use more modern RAII constructs, such as smart pointers. // // T must be a pointer type // - disallow construction from any type other than pointer type // template ::value, bool> = true> using owner = T; // // not_null // // Restricts a pointer or smart pointer to only hold non-null values. // // Has zero size overhead over T. // // If T is a pointer (i.e. T == U*) then // - allow construction from U* // - disallow construction from nullptr_t // - disallow default construction // - ensure construction from null U* fails // - allow implicit conversion to U* // template class not_null { public: static_assert(details::is_comparable_to_nullptr::value, "T cannot be compared to nullptr."); using element_type = T; template ::value>> constexpr not_null(U&& u) noexcept(std::is_nothrow_move_constructible::value) : ptr_(std::forward(u)) { Expects(ptr_ != nullptr); } template ::value>> constexpr not_null(T u) noexcept(std::is_nothrow_move_constructible::value) : ptr_(std::move(u)) { Expects(ptr_ != nullptr); } template ::value>> constexpr not_null(const not_null& other) noexcept(std::is_nothrow_move_constructible::value) : not_null(other.get()) {} not_null(const not_null& other) = default; not_null& operator=(const not_null& other) = default; constexpr details::value_or_reference_return_t get() const noexcept(noexcept(details::value_or_reference_return_t(std::declval()))) { return ptr_; } constexpr operator T() const { return get(); } constexpr decltype(auto) operator->() const { return get(); } constexpr decltype(auto) operator*() const { return *get(); } // prevents compilation when someone attempts to assign a null pointer constant not_null(std::nullptr_t) = delete; not_null& operator=(std::nullptr_t) = delete; // unwanted operators...pointers only point to single objects! not_null& operator++() = delete; not_null& operator--() = delete; not_null operator++(int) = delete; not_null operator--(int) = delete; not_null& operator+=(std::ptrdiff_t) = delete; not_null& operator-=(std::ptrdiff_t) = delete; void operator[](std::ptrdiff_t) const = delete; void swap(not_null& other) { std::swap(ptr_, other.ptr_); } private: T ptr_; }; template ::value && std::is_move_constructible::value, bool> = true> void swap(not_null& a, not_null& b) { a.swap(b); } template auto make_not_null(T&& t) noexcept { return not_null>>{std::forward(t)}; } #if !defined(GSL_NO_IOSTREAMS) template std::ostream& operator<<(std::ostream& os, const not_null& val) { os << val.get(); return os; } #endif // !defined(GSL_NO_IOSTREAMS) template auto operator==(const not_null& lhs, const not_null& rhs) noexcept(noexcept(lhs.get() == rhs.get())) -> decltype(lhs.get() == rhs.get()) { return lhs.get() == rhs.get(); } template auto operator!=(const not_null& lhs, const not_null& rhs) noexcept(noexcept(lhs.get() != rhs.get())) -> decltype(lhs.get() != rhs.get()) { return lhs.get() != rhs.get(); } template auto operator<(const not_null& lhs, const not_null& rhs) noexcept(noexcept(std::less<>{}(lhs.get(), rhs.get()))) -> decltype(std::less<>{}(lhs.get(), rhs.get())) { return std::less<>{}(lhs.get(), rhs.get()); } template auto operator<=(const not_null& lhs, const not_null& rhs) noexcept(noexcept(std::less_equal<>{}(lhs.get(), rhs.get()))) -> decltype(std::less_equal<>{}(lhs.get(), rhs.get())) { return std::less_equal<>{}(lhs.get(), rhs.get()); } template auto operator>(const not_null& lhs, const not_null& rhs) noexcept(noexcept(std::greater<>{}(lhs.get(), rhs.get()))) -> decltype(std::greater<>{}(lhs.get(), rhs.get())) { return std::greater<>{}(lhs.get(), rhs.get()); } template auto operator>=(const not_null& lhs, const not_null& rhs) noexcept(noexcept(std::greater_equal<>{}(lhs.get(), rhs.get()))) -> decltype(std::greater_equal<>{}(lhs.get(), rhs.get())) { return std::greater_equal<>{}(lhs.get(), rhs.get()); } // more unwanted operators template std::ptrdiff_t operator-(const not_null&, const not_null&) = delete; template not_null operator-(const not_null&, std::ptrdiff_t) = delete; template not_null operator+(const not_null&, std::ptrdiff_t) = delete; template not_null operator+(std::ptrdiff_t, const not_null&) = delete; template ().get()), bool = std::is_default_constructible>::value> struct not_null_hash { std::size_t operator()(const T& value) const { return std::hash{}(value.get()); } }; template struct not_null_hash { not_null_hash() = delete; not_null_hash(const not_null_hash&) = delete; not_null_hash& operator=(const not_null_hash&) = delete; }; } // namespace gsl namespace std { template struct hash> : gsl::not_null_hash> { }; } // namespace std namespace gsl { // // strict_not_null // // Restricts a pointer or smart pointer to only hold non-null values, // // - provides a strict (i.e. explicit constructor from T) wrapper of not_null // - to be used for new code that wishes the design to be cleaner and make not_null // checks intentional, or in old code that would like to make the transition. // // To make the transition from not_null, incrementally replace not_null // by strict_not_null and fix compilation errors // // Expect to // - remove all unneeded conversions from raw pointer to not_null and back // - make API clear by specifying not_null in parameters where needed // - remove unnecessary asserts // template class strict_not_null : public not_null { public: template ::value>> constexpr explicit strict_not_null(U&& u) noexcept(std::is_nothrow_move_constructible::value) : not_null(std::forward(u)) {} template ::value>> constexpr explicit strict_not_null(T u) noexcept(std::is_nothrow_move_constructible::value) : not_null(std::move(u)) {} template ::value>> constexpr strict_not_null(const not_null& other) noexcept(std::is_nothrow_move_constructible::value) : not_null(other) {} template ::value>> constexpr strict_not_null(const strict_not_null& other) noexcept(std::is_nothrow_move_constructible::value) : not_null(other) {} // To avoid invalidating the "not null" invariant, the contained pointer is actually copied // instead of moved. If it is a custom pointer, its constructor could in theory throw exceptions. strict_not_null(strict_not_null&& other) noexcept(std::is_nothrow_copy_constructible::value) = default; strict_not_null(const strict_not_null& other) = default; strict_not_null& operator=(const strict_not_null& other) = default; strict_not_null& operator=(const not_null& other) { not_null::operator=(other); return *this; } // prevents compilation when someone attempts to assign a null pointer constant strict_not_null(std::nullptr_t) = delete; strict_not_null& operator=(std::nullptr_t) = delete; // unwanted operators...pointers only point to single objects! strict_not_null& operator++() = delete; strict_not_null& operator--() = delete; strict_not_null operator++(int) = delete; strict_not_null operator--(int) = delete; strict_not_null& operator+=(std::ptrdiff_t) = delete; strict_not_null& operator-=(std::ptrdiff_t) = delete; void operator[](std::ptrdiff_t) const = delete; }; // more unwanted operators template std::ptrdiff_t operator-(const strict_not_null&, const strict_not_null&) = delete; template strict_not_null operator-(const strict_not_null&, std::ptrdiff_t) = delete; template strict_not_null operator+(const strict_not_null&, std::ptrdiff_t) = delete; template strict_not_null operator+(std::ptrdiff_t, const strict_not_null&) = delete; template auto make_strict_not_null(T&& t) noexcept { return strict_not_null>>{std::forward(t)}; } #if (defined(__cpp_deduction_guides) && (__cpp_deduction_guides >= 201611L)) // deduction guides to prevent the ctad-maybe-unsupported warning template not_null(T) -> not_null; template strict_not_null(T) -> strict_not_null; #endif // ( defined(__cpp_deduction_guides) && (__cpp_deduction_guides >= 201611L) ) } // namespace gsl namespace std { template struct hash> : gsl::not_null_hash> { }; } // namespace std #endif // GSL_POINTERS_H GSL-4.2.1/include/gsl/span000066400000000000000000000771311511561312500152500ustar00rootroot00000000000000/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// #ifndef GSL_SPAN_H #define GSL_SPAN_H #include "./assert" // for Expects #include "./byte" // for gsl::impl::byte #include "./span_ext" // for span specialization of gsl::at and other span-related extensions #include "./util" // for narrow_cast #include // for array #include // for ptrdiff_t, size_t, nullptr_t #include // for reverse_iterator, distance, random_access_... #include // for pointer_traits #include // for enable_if_t, declval, is_convertible, inte... #if defined(__has_include) && __has_include() #include #endif #if defined(_MSC_VER) && !defined(__clang__) #pragma warning(push) // turn off some warnings that are noisy about our Expects statements #pragma warning(disable : 4127) // conditional expression is constant #pragma warning( \ disable : 4146) // unary minus operator applied to unsigned type, result still unsigned #pragma warning(disable : 4702) // unreachable code // Turn MSVC /analyze rules that generate too much noise. TODO: fix in the tool. #pragma warning(disable : 26495) // uninitialized member when constructor calls constructor #pragma warning(disable : 26446) // parser bug does not allow attributes on some templates #endif // _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)) // GCC 7 does not like the signed unsigned mismatch (size_t ptrdiff_t) // While there is a conversion from signed to unsigned, it happens at // compiletime, so the compiler wouldn't have to warn indiscriminately, but // could check if the source value actually doesn't fit into the target type // and only warn in those cases. #if defined(__GNUC__) && __GNUC__ > 6 #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wsign-conversion" #endif // Turn off clang unsafe buffer warnings as all accessed are guarded by runtime checks #if defined(__clang__) #if __has_warning("-Wunsafe-buffer-usage") #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunsafe-buffer-usage" #endif // __has_warning("-Wunsafe-buffer-usage") #endif // defined(__clang__) namespace gsl { // implementation details namespace details { template struct is_span_oracle : std::false_type { }; template struct is_span_oracle> : std::true_type { }; template struct is_span : public is_span_oracle> { }; template struct is_std_array_oracle : std::false_type { }; template struct is_std_array_oracle> : std::true_type { }; template struct is_std_array : is_std_array_oracle> { }; template struct is_allowed_extent_conversion : std::integral_constant { }; template struct is_allowed_element_type_conversion : std::integral_constant::value> { }; template class span_iterator { public: #if defined(__cpp_lib_ranges) || (defined(_MSVC_STL_VERSION) && defined(__cpp_lib_concepts)) using iterator_concept = std::contiguous_iterator_tag; #endif // __cpp_lib_ranges using iterator_category = std::random_access_iterator_tag; using value_type = std::remove_cv_t; using difference_type = std::ptrdiff_t; using pointer = Type*; using reference = Type&; #ifdef _MSC_VER using _Unchecked_type = pointer; using _Prevent_inheriting_unwrap = span_iterator; #endif // _MSC_VER constexpr span_iterator() = default; constexpr span_iterator(pointer begin, pointer end, pointer current) : begin_(begin), end_(end), current_(current) { Expects(begin_ <= current_ && current <= end_); } constexpr operator span_iterator() const noexcept { return {begin_, end_, current_}; } constexpr reference operator*() const noexcept { Expects(current_ != end_); return *current_; } constexpr pointer operator->() const noexcept { Expects(current_ != end_); return current_; } constexpr span_iterator& operator++() noexcept { Expects(current_ != end_); // clang-format off GSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute // clang-format on ++current_; return *this; } constexpr span_iterator operator++(int) noexcept { span_iterator ret = *this; ++*this; return ret; } constexpr span_iterator& operator--() noexcept { Expects(begin_ != current_); --current_; return *this; } constexpr span_iterator operator--(int) noexcept { span_iterator ret = *this; --*this; return ret; } constexpr span_iterator& operator+=(const difference_type n) noexcept { if (n != 0) Expects(begin_ && current_ && end_); if (n > 0) Expects(end_ - current_ >= n); if (n < 0) Expects(current_ - begin_ >= -n); // clang-format off GSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute // clang-format on current_ += n; return *this; } constexpr span_iterator operator+(const difference_type n) const noexcept { span_iterator ret = *this; ret += n; return ret; } friend constexpr span_iterator operator+(const difference_type n, const span_iterator& rhs) noexcept { return rhs + n; } constexpr span_iterator& operator-=(const difference_type n) noexcept { if (n != 0) Expects(begin_ && current_ && end_); if (n > 0) Expects(current_ - begin_ >= n); if (n < 0) Expects(end_ - current_ >= -n); GSL_SUPPRESS(bounds .1) current_ -= n; return *this; } constexpr span_iterator operator-(const difference_type n) const noexcept { span_iterator ret = *this; ret -= n; return ret; } template < class Type2, std::enable_if_t, value_type>::value, int> = 0> constexpr difference_type operator-(const span_iterator& rhs) const noexcept { Expects(begin_ == rhs.begin_ && end_ == rhs.end_); return current_ - rhs.current_; } constexpr reference operator[](const difference_type n) const noexcept { return *(*this + n); } template < class Type2, std::enable_if_t, value_type>::value, int> = 0> constexpr bool operator==(const span_iterator& rhs) const noexcept { Expects(begin_ == rhs.begin_ && end_ == rhs.end_); return current_ == rhs.current_; } template < class Type2, std::enable_if_t, value_type>::value, int> = 0> constexpr bool operator!=(const span_iterator& rhs) const noexcept { return !(*this == rhs); } template < class Type2, std::enable_if_t, value_type>::value, int> = 0> constexpr bool operator<(const span_iterator& rhs) const noexcept { Expects(begin_ == rhs.begin_ && end_ == rhs.end_); return current_ < rhs.current_; } template < class Type2, std::enable_if_t, value_type>::value, int> = 0> constexpr bool operator>(const span_iterator& rhs) const noexcept { return rhs < *this; } template < class Type2, std::enable_if_t, value_type>::value, int> = 0> constexpr bool operator<=(const span_iterator& rhs) const noexcept { return !(rhs < *this); } template < class Type2, std::enable_if_t, value_type>::value, int> = 0> constexpr bool operator>=(const span_iterator& rhs) const noexcept { return !(*this < rhs); } #ifdef _MSC_VER // MSVC++ iterator debugging support; allows STL algorithms in 15.8+ // to unwrap span_iterator to a pointer type after a range check in STL // algorithm calls friend constexpr void _Verify_range(span_iterator lhs, span_iterator rhs) noexcept { // test that [lhs, rhs) forms a valid range inside an STL algorithm Expects(lhs.begin_ == rhs.begin_ // range spans have to match && lhs.end_ == rhs.end_ && lhs.current_ <= rhs.current_); // range must not be transposed } constexpr void _Verify_offset(const difference_type n) const noexcept { // test that *this + n is within the range of this call if (n != 0) Expects(begin_ && current_ && end_); if (n > 0) Expects(end_ - current_ >= n); if (n < 0) Expects(current_ - begin_ >= -n); } // clang-format off GSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute // clang-format on constexpr pointer _Unwrapped() const noexcept { // after seeking *this to a high water mark, or using one of the // _Verify_xxx functions above, unwrap this span_iterator to a raw // pointer return current_; } // Tell the STL that span_iterator should not be unwrapped if it can't // validate in advance, even in release / optimized builds: #if defined(GSL_USE_STATIC_CONSTEXPR_WORKAROUND) static constexpr const bool _Unwrap_when_unverified = false; #else static constexpr bool _Unwrap_when_unverified = false; #endif // clang-format off GSL_SUPPRESS(con.3) // NO-FORMAT: attribute // TODO: false positive // clang-format on constexpr void _Seek_to(const pointer p) noexcept { // adjust the position of *this to previously verified location p // after _Unwrapped current_ = p; } #endif pointer begin_ = nullptr; pointer end_ = nullptr; pointer current_ = nullptr; template friend struct std::pointer_traits; }; }} // namespace gsl::details namespace std { template struct pointer_traits<::gsl::details::span_iterator> { using pointer = ::gsl::details::span_iterator; using element_type = Type; using difference_type = ptrdiff_t; static constexpr element_type* to_address(const pointer i) noexcept { return i.current_; } }; } // namespace std namespace gsl { namespace details { template class extent_type { public: using size_type = std::size_t; constexpr extent_type() noexcept = default; constexpr explicit extent_type(extent_type); constexpr explicit extent_type(size_type size) { Expects(size == Ext); } constexpr size_type size() const noexcept { return Ext; } private: #if defined(GSL_USE_STATIC_CONSTEXPR_WORKAROUND) static constexpr const size_type size_ = Ext; // static size equal to Ext #else static constexpr size_type size_ = Ext; // static size equal to Ext #endif }; template <> class extent_type { public: using size_type = std::size_t; template constexpr explicit extent_type(extent_type ext) : size_(ext.size()) {} constexpr explicit extent_type(size_type size) : size_(size) { Expects(size != dynamic_extent); } constexpr size_type size() const noexcept { return size_; } private: size_type size_; }; template constexpr extent_type::extent_type(extent_type ext) { Expects(ext.size() == Ext); } template struct calculate_subspan_type { using type = span; }; } // namespace details // [span], class template span template class span { public: // constants and types using element_type = ElementType; using value_type = std::remove_cv_t; using size_type = std::size_t; using pointer = element_type*; using const_pointer = const element_type*; using reference = element_type&; using const_reference = const element_type&; using difference_type = std::ptrdiff_t; using iterator = details::span_iterator; using reverse_iterator = std::reverse_iterator; #if defined(GSL_USE_STATIC_CONSTEXPR_WORKAROUND) static constexpr const size_type extent{Extent}; #else static constexpr size_type extent{Extent}; #endif // [span.cons], span constructors, copy, assignment, and destructor template " SFINAE, since "std::enable_if_t" is ill-formed when Extent is greater than 0. class = std::enable_if_t<(Dependent || details::is_allowed_extent_conversion<0, Extent>::value)>> constexpr span() noexcept : storage_(nullptr, details::extent_type<0>()) {} template = 0> constexpr explicit span(pointer ptr, size_type count) noexcept : storage_(ptr, count) { Expects(count == Extent); } template = 0> constexpr span(pointer ptr, size_type count) noexcept : storage_(ptr, count) {} template = 0> constexpr explicit span(pointer firstElem, pointer lastElem) noexcept : storage_(firstElem, narrow_cast(lastElem - firstElem)) { Expects(lastElem - firstElem == static_cast(Extent)); } template = 0> constexpr span(pointer firstElem, pointer lastElem) noexcept : storage_(firstElem, narrow_cast(lastElem - firstElem)) {} template ::value, int> = 0> constexpr span(element_type (&arr)[N]) noexcept : storage_(KnownNotNull{arr}, details::extent_type()) {} template < class T, std::size_t N, std::enable_if_t<(details::is_allowed_extent_conversion::value && details::is_allowed_element_type_conversion::value), int> = 0> constexpr span(std::array& arr) noexcept : storage_(KnownNotNull{arr.data()}, details::extent_type()) {} template ::value && details::is_allowed_element_type_conversion::value), int> = 0> constexpr span(const std::array& arr) noexcept : storage_(KnownNotNull{arr.data()}, details::extent_type()) {} // NB: the SFINAE on these constructors uses .data() as an incomplete/imperfect proxy for the // requirement on Container to be a contiguous sequence container. template ::value && !details::is_std_array::value && std::is_pointer().data())>::value && std::is_convertible< std::remove_pointer_t().data())> (*)[], element_type (*)[]>::value, int> = 0> constexpr explicit span(Container& cont) noexcept : span(cont.data(), cont.size()) {} template ::value && !details::is_std_array::value && std::is_pointer().data())>::value && std::is_convertible< std::remove_pointer_t().data())> (*)[], element_type (*)[]>::value, int> = 0> constexpr span(Container& cont) noexcept : span(cont.data(), cont.size()) {} template < std::size_t MyExtent = Extent, class Container, std::enable_if_t< MyExtent != dynamic_extent && std::is_const::value && !details::is_span::value && !details::is_std_array::value && std::is_pointer().data())>::value && std::is_convertible< std::remove_pointer_t().data())> (*)[], element_type (*)[]>::value, int> = 0> constexpr explicit span(const Container& cont) noexcept : span(cont.data(), cont.size()) {} template < std::size_t MyExtent = Extent, class Container, std::enable_if_t< MyExtent == dynamic_extent && std::is_const::value && !details::is_span::value && !details::is_std_array::value && std::is_pointer().data())>::value && std::is_convertible< std::remove_pointer_t().data())> (*)[], element_type (*)[]>::value, int> = 0> constexpr span(const Container& cont) noexcept : span(cont.data(), cont.size()) {} constexpr span(const span& other) noexcept = default; template ::value, int> = 0> constexpr span(const span& other) noexcept : storage_(other.data(), details::extent_type(other.size())) {} template ::value, int> = 0> constexpr explicit span(const span& other) noexcept : storage_(other.data(), details::extent_type(other.size())) {} ~span() noexcept = default; constexpr span& operator=(const span& other) noexcept = default; // [span.sub], span subviews template constexpr span first() const noexcept { static_assert(Extent == dynamic_extent || Count <= Extent, "first() cannot extract more elements from a span than it contains."); Expects(Count <= size()); return span{data(), Count}; } template // clang-format off GSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute // clang-format on constexpr span last() const noexcept { static_assert(Extent == dynamic_extent || Count <= Extent, "last() cannot extract more elements from a span than it contains."); Expects(Count <= size()); return span{data() + (size() - Count), Count}; } template // clang-format off GSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute // clang-format on constexpr auto subspan() const noexcept -> typename details::calculate_subspan_type::type { static_assert(Extent == dynamic_extent || (Extent >= Offset && (Count == dynamic_extent || Count <= Extent - Offset)), "subspan() cannot extract more elements from a span than it contains."); Expects((size() >= Offset) && (Count == dynamic_extent || (Count <= size() - Offset))); using type = typename details::calculate_subspan_type::type; return type{data() + Offset, Count == dynamic_extent ? size() - Offset : Count}; } constexpr span first(size_type count) const noexcept { Expects(count <= size()); return {data(), count}; } constexpr span last(size_type count) const noexcept { Expects(count <= size()); return make_subspan(size() - count, dynamic_extent, subspan_selector{}); } constexpr span subspan(size_type offset, size_type count = dynamic_extent) const noexcept { return make_subspan(offset, count, subspan_selector{}); } // [span.obs], span observers constexpr size_type size() const noexcept { return storage_.size(); } constexpr size_type size_bytes() const noexcept { return size() * sizeof(element_type); } constexpr bool empty() const noexcept { return size() == 0; } // [span.elem], span element access // clang-format off GSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute // clang-format on constexpr reference operator[](size_type idx) const noexcept { Expects(idx < size()); return data()[idx]; } constexpr reference front() const noexcept { Expects(size() > 0); return data()[0]; } constexpr reference back() const noexcept { Expects(size() > 0); return data()[size() - 1]; } constexpr pointer data() const noexcept { return storage_.data(); } // [span.iter], span iterator support constexpr iterator begin() const noexcept { const auto data = storage_.data(); // clang-format off GSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute // clang-format on return {data, data + size(), data}; } constexpr iterator end() const noexcept { const auto data = storage_.data(); // clang-format off GSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute // clang-format on const auto endData = data + storage_.size(); return {data, endData, endData}; } constexpr reverse_iterator rbegin() const noexcept { return reverse_iterator{end()}; } constexpr reverse_iterator rend() const noexcept { return reverse_iterator{begin()}; } #ifdef _MSC_VER // Tell MSVC how to unwrap spans in range-based-for constexpr pointer _Unchecked_begin() const noexcept { return data(); } constexpr pointer _Unchecked_end() const noexcept { // clang-format off GSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute // clang-format on return data() + size(); } #endif // _MSC_VER private: // Needed to remove unnecessary null check in subspans struct KnownNotNull { pointer p; }; // this implementation detail class lets us take advantage of the // empty base class optimization to pay for only storage of a single // pointer in the case of fixed-size spans template class storage_type : public ExtentType { public: // KnownNotNull parameter is needed to remove unnecessary null check // in subspans and constructors from arrays template constexpr storage_type(KnownNotNull data, OtherExtentType ext) : ExtentType(ext), data_(data.p) {} template constexpr storage_type(pointer data, OtherExtentType ext) : ExtentType(ext), data_(data) { Expects(data || ExtentType::size() == 0); } constexpr pointer data() const noexcept { return data_; } private: pointer data_; }; storage_type> storage_; // The rest is needed to remove unnecessary null check // in subspans and constructors from arrays constexpr span(KnownNotNull ptr, size_type count) noexcept : storage_(ptr, count) {} template class subspan_selector { }; template constexpr span make_subspan(size_type offset, size_type count, subspan_selector) const noexcept { const span tmp(*this); return tmp.subspan(offset, count); } // clang-format off GSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute // clang-format on constexpr span make_subspan(size_type offset, size_type count, subspan_selector) const noexcept { Expects(size() >= offset); if (count == dynamic_extent) { return {KnownNotNull{data() + offset}, size() - offset}; } Expects(size() - offset >= count); return {KnownNotNull{data() + offset}, count}; } }; #if (defined(__cpp_deduction_guides) && (__cpp_deduction_guides >= 201611L)) // Deduction Guides template span(Type (&)[Extent]) -> span; template span(std::array&) -> span; template span(const std::array&) -> span; template ().data())>> span(Container&) -> span; template ().data())>> span(const Container&) -> span; #endif // ( defined(__cpp_deduction_guides) && (__cpp_deduction_guides >= 201611L) ) #if defined(GSL_USE_STATIC_CONSTEXPR_WORKAROUND) #if defined(__clang__) && defined(_MSC_VER) && defined(__cplusplus) && (__cplusplus < 201703L) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated" // Bug in clang-cl.exe which raises a C++17 -Wdeprecated warning about this static constexpr workaround in C++14 mode. #endif // defined(__clang__) && defined(_MSC_VER) && defined(__cplusplus) && (__cplusplus < 201703L) template constexpr const typename span::size_type span::extent; #if defined(__clang__) && defined(_MSC_VER) && defined(__cplusplus) && (__cplusplus < 201703L) #pragma clang diagnostic pop #endif // defined(__clang__) && defined(_MSC_VER) && defined(__cplusplus) && (__cplusplus < 201703L) #endif namespace details { // if we only supported compilers with good constexpr support then // this pair of classes could collapse down to a constexpr function // we should use a narrow_cast<> to go to std::size_t, but older compilers may not see it as // constexpr // and so will fail compilation of the template template struct calculate_byte_size : std::integral_constant { static_assert(Extent < dynamic_extent / sizeof(ElementType), "Size is too big."); }; template struct calculate_byte_size : std::integral_constant { }; } // namespace details // [span.objectrep], views of object representation template span::value> as_bytes(span s) noexcept { using type = span::value>; // clang-format off GSL_SUPPRESS(type.1) // NO-FORMAT: attribute // clang-format on return type{reinterpret_cast(s.data()), s.size_bytes()}; } template ::value, int> = 0> span::value> as_writable_bytes(span s) noexcept { using type = span::value>; // clang-format off GSL_SUPPRESS(type.1) // NO-FORMAT: attribute // clang-format on return type{reinterpret_cast(s.data()), s.size_bytes()}; } } // namespace gsl #if defined(_MSC_VER) && !defined(__clang__) #pragma warning(pop) #endif // _MSC_VER #if defined(__GNUC__) && __GNUC__ > 6 #pragma GCC diagnostic pop #endif // __GNUC__ > 6 #if defined(__clang__) #if __has_warning("-Wunsafe-buffer-usage") #pragma clang diagnostic pop #endif // __has_warning("-Wunsafe-buffer-usage") #endif // defined(__clang__) #endif // GSL_SPAN_H GSL-4.2.1/include/gsl/span_ext000066400000000000000000000151501511561312500161210ustar00rootroot00000000000000/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// #ifndef GSL_SPAN_EXT_H #define GSL_SPAN_EXT_H /////////////////////////////////////////////////////////////////////////////// // // File: span_ext // Purpose: continue offering features that have been cut from the official // implementation of span. // While modernizing gsl::span a number of features needed to be removed to // be compliant with the design of std::span // /////////////////////////////////////////////////////////////////////////////// #include "./assert" // GSL_KERNEL_MODE #include "./util" // for narrow_cast, narrow #include // for ptrdiff_t, size_t #include #ifndef GSL_KERNEL_MODE #include // for lexicographical_compare #endif // GSL_KERNEL_MODE namespace gsl { // [span.views.constants], constants GSL_INLINE constexpr const std::size_t dynamic_extent = narrow_cast(-1); template class span; // std::equal and std::lexicographical_compare are not /kernel compatible // so all comparison operators must be removed for kernel mode. #ifndef GSL_KERNEL_MODE // [span.comparison], span comparison operators template constexpr bool operator==(span l, span r) { return std::equal(l.begin(), l.end(), r.begin(), r.end()); } template constexpr bool operator!=(span l, span r) { return !(l == r); } template constexpr bool operator<(span l, span r) { return std::lexicographical_compare(l.begin(), l.end(), r.begin(), r.end()); } template constexpr bool operator<=(span l, span r) { return !(l > r); } template constexpr bool operator>(span l, span r) { return r < l; } template constexpr bool operator>=(span l, span r) { return !(l < r); } #endif // GSL_KERNEL_MODE // // make_span() - Utility functions for creating spans // template constexpr span make_span(ElementType* ptr, typename span::size_type count) { return span(ptr, count); } template constexpr span make_span(ElementType* firstElem, ElementType* lastElem) { return span(firstElem, lastElem); } template constexpr span make_span(ElementType (&arr)[N]) noexcept { return span(arr); } template constexpr span make_span(Container& cont) { return span(cont); } template constexpr span make_span(const Container& cont) { return span(cont); } template GSL_DEPRECATED("This function is deprecated. See GSL issue #1092.") constexpr span make_span(Ptr& cont, std::size_t count) { return span(cont, count); } template GSL_DEPRECATED("This function is deprecated. See GSL issue #1092.") constexpr span make_span(Ptr& cont) { return span(cont); } // Specialization of gsl::at for span template constexpr ElementType& at(span s, index i) { // No bounds checking here because it is done in span::operator[] called below Ensures(i >= 0); return s[narrow_cast(i)]; } // [span.obs] Free observer functions template constexpr std::ptrdiff_t ssize(const span& s) noexcept { return static_cast(s.size()); } // [span.iter] Free functions for begin/end functions template constexpr typename span::iterator begin(const span& s) noexcept { return s.begin(); } template constexpr typename span::iterator end(const span& s) noexcept { return s.end(); } template constexpr typename span::reverse_iterator rbegin(const span& s) noexcept { return s.rbegin(); } template constexpr typename span::reverse_iterator rend(const span& s) noexcept { return s.rend(); } template constexpr typename span::iterator cbegin(const span& s) noexcept { return s.begin(); } template constexpr typename span::iterator cend(const span& s) noexcept { return s.end(); } template constexpr typename span::reverse_iterator crbegin(const span& s) noexcept { return s.rbegin(); } template constexpr typename span::reverse_iterator crend(const span& s) noexcept { return s.rend(); } } // namespace gsl #endif // GSL_SPAN_EXT_H GSL-4.2.1/include/gsl/util000066400000000000000000000140151511561312500152540ustar00rootroot00000000000000/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// #ifndef GSL_UTIL_H #define GSL_UTIL_H #include "./assert" // for Expects #include #include // for ptrdiff_t, size_t #include // for numeric_limits #include // for initializer_list #include // for is_signed, integral_constant #include // for exchange, forward #if defined(__has_include) && __has_include() #include #if defined(__cpp_lib_span) && __cpp_lib_span >= 202002L #include #endif // __cpp_lib_span >= 202002L #endif //__has_include() #if defined(_MSC_VER) && !defined(__clang__) #pragma warning(push) #pragma warning(disable : 4127) // conditional expression is constant #endif // _MSC_VER // Turn off clang unsafe buffer warnings as all accessed are guarded by runtime checks #if defined(__clang__) #if __has_warning("-Wunsafe-buffer-usage") #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunsafe-buffer-usage" #endif // __has_warning("-Wunsafe-buffer-usage") #endif // defined(__clang__) #if defined(__cplusplus) && (__cplusplus >= 201703L) #define GSL_NODISCARD [[nodiscard]] #else #define GSL_NODISCARD #endif // defined(__cplusplus) && (__cplusplus >= 201703L) #if defined(__cpp_inline_variables) #define GSL_INLINE inline #else #define GSL_INLINE #endif #if defined(__has_cpp_attribute) #if __has_cpp_attribute(deprecated) #define GSL_DEPRECATED(msg) [[deprecated(msg)]] #endif // __has_cpp_attribute(deprecated) #endif // defined(__has_cpp_attribute) #if !defined(GSL_DEPRECATED) #if defined(__cplusplus) #if __cplusplus >= 201309L #define GSL_DEPRECATED(msg) [[deprecated(msg)]] #endif // __cplusplus >= 201309L #endif // defined(__cplusplus) #endif // !defined(GSL_DEPRECATED) #if !defined(GSL_DEPRECATED) #if defined(_MSC_VER) #define GSL_DEPRECATED(msg) __declspec(deprecated(msg)) #elif defined(__GNUC__) #define GSL_DEPRECATED(msg) __attribute__((deprecated(msg))) #endif // defined(_MSC_VER) #endif // !defined(GSL_DEPRECATED) #if !defined(GSL_DEPRECATED) #define GSL_DEPRECATED(msg) #endif // !defined(GSL_DEPRECATED) namespace gsl { // // GSL.util: utilities // // index type for all container indexes/subscripts/sizes using index = std::ptrdiff_t; // final_action allows you to ensure something gets run at the end of a scope template class final_action { public: explicit final_action(const F& ff) noexcept : f{ff} { } explicit final_action(F&& ff) noexcept : f{std::move(ff)} { } ~final_action() noexcept { if (invoke) f(); } final_action(final_action&& other) noexcept : f(std::move(other.f)), invoke(std::exchange(other.invoke, false)) { } final_action(const final_action&) = delete; void operator=(const final_action&) = delete; void operator=(final_action&&) = delete; private: F f; bool invoke = true; }; // finally() - convenience function to generate a final_action template GSL_NODISCARD auto finally(F&& f) noexcept { return final_action>{std::forward(f)}; } // narrow_cast(): a searchable way to do narrowing casts of values template // clang-format off GSL_SUPPRESS(type.1) // NO-FORMAT: attribute // clang-format on constexpr T narrow_cast(U&& u) noexcept { return static_cast(std::forward(u)); } // // at() - Bounds-checked way of accessing builtin arrays, std::array, std::vector // template // clang-format off GSL_SUPPRESS(bounds.4) // NO-FORMAT: attribute GSL_SUPPRESS(bounds.2) // NO-FORMAT: attribute // clang-format on constexpr T& at(T (&arr)[N], const index i) { static_assert(N <= static_cast((std::numeric_limits::max)()), "We only support arrays up to PTRDIFF_MAX bytes."); Expects(i >= 0 && i < narrow_cast(N)); return arr[narrow_cast(i)]; } template // clang-format off GSL_SUPPRESS(bounds.4) // NO-FORMAT: attribute GSL_SUPPRESS(bounds.2) // NO-FORMAT: attribute // clang-format on constexpr auto at(Cont& cont, const index i) -> decltype(cont[cont.size()]) { Expects(i >= 0 && i < narrow_cast(cont.size())); using size_type = decltype(cont.size()); return cont[narrow_cast(i)]; } template // clang-format off GSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute // clang-format on constexpr T at(const std::initializer_list cont, const index i) { Expects(i >= 0 && i < narrow_cast(cont.size())); return *(cont.begin() + i); } template ::value && std::is_move_constructible::value>> void swap(T& a, T& b) { std::swap(a, b); } #if defined(__cpp_lib_span) && __cpp_lib_span >= 202002L template constexpr auto at(std::span sp, const index i) -> decltype(sp[sp.size()]) { Expects(i >= 0 && i < narrow_cast(sp.size())); return sp[gsl::narrow_cast(i)]; } #endif // __cpp_lib_span >= 202002L } // namespace gsl #if defined(_MSC_VER) && !defined(__clang__) #pragma warning(pop) #endif // _MSC_VER #if defined(__clang__) #if __has_warning("-Wunsafe-buffer-usage") #pragma clang diagnostic pop #endif // __has_warning("-Wunsafe-buffer-usage") #endif // defined(__clang__) #endif // GSL_UTIL_H GSL-4.2.1/include/gsl/zstring000066400000000000000000000036721511561312500160060ustar00rootroot00000000000000/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// #ifndef GSL_ZSTRING_H #define GSL_ZSTRING_H #include "./span_ext" // for dynamic_extent #include // for size_t, nullptr_t namespace gsl { // // czstring and wzstring // // These are "tag" typedefs for C-style strings (i.e. null-terminated character arrays) // that allow static analysis to help find bugs. // // There are no additional features/semantics that we can find a way to add inside the // type system for these types that will not either incur significant runtime costs or // (sometimes needlessly) break existing programs when introduced. // template using basic_zstring = CharT*; using czstring = basic_zstring; using cwzstring = basic_zstring; using cu16zstring = basic_zstring; using cu32zstring = basic_zstring; using zstring = basic_zstring; using wzstring = basic_zstring; using u16zstring = basic_zstring; using u32zstring = basic_zstring; } // namespace gsl #endif // GSL_ZSTRING_H GSL-4.2.1/tests/000077500000000000000000000000001511561312500133055ustar00rootroot00000000000000GSL-4.2.1/tests/CMakeLists.txt000066400000000000000000000256341511561312500160570ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.14...3.16) project(GSLTests LANGUAGES CXX) set(GSL_CXX_STANDARD "14" CACHE STRING "Use c++ standard") set(CMAKE_CXX_STANDARD ${GSL_CXX_STANDARD}) set(CMAKE_CXX_EXTENSIONS OFF) set(CMAKE_CXX_STANDARD_REQUIRED ON) include(FindPkgConfig) include(ExternalProject) # will make visual studio generated project group files set_property(GLOBAL PROPERTY USE_FOLDERS ON) if(CI_TESTING AND GSL_CXX_STANDARD EQUAL 20) add_compile_definitions(FORCE_STD_SPAN_TESTS=1) endif() if(IOS) add_compile_definitions(GTEST_HAS_DEATH_TEST=1 IOS_PROCESS_DELAY_WORKAROUND=1) endif() pkg_search_module(GTestMain gtest_main) if (NOT GTestMain_FOUND) # No pre-installed GTest is available, try to download it using Git. find_package(Git REQUIRED QUIET) configure_file(CMakeLists.txt.in googletest-download/CMakeLists.txt) execute_process( COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" . RESULT_VARIABLE result WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/googletest-download ) if(result) message(FATAL_ERROR "CMake step for googletest failed: ${result}") endif() execute_process( COMMAND ${CMAKE_COMMAND} --build . RESULT_VARIABLE result WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/googletest-download ) if(result) message(FATAL_ERROR "CMake step for googletest failed: ${result}") endif() set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) set(GTestMain_LIBRARIES gtest_main) add_subdirectory( ${CMAKE_CURRENT_BINARY_DIR}/googletest-src ${CMAKE_CURRENT_BINARY_DIR}/googletest-build EXCLUDE_FROM_ALL ) endif() if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) find_package(Microsoft.GSL CONFIG REQUIRED) enable_testing() if (NOT DEFINED Microsoft.GSL_VERSION) message(FATAL_ERROR "Microsoft.GSL_VERSION not defined!") endif() message(STATUS "Microsoft.GSL_VERSION = ${Microsoft.GSL_VERSION}") endif() if (MSVC AND (GSL_CXX_STANDARD GREATER_EQUAL 17)) set(GSL_CPLUSPLUS_OPT -Zc:__cplusplus -permissive-) endif() include(CheckCXXCompilerFlag) # this interface adds compile options to how the tests are run # please try to keep entries ordered =) add_library(gsl_tests_config INTERFACE) if(MSVC) # MSVC or simulating MSVC target_compile_options(gsl_tests_config INTERFACE ${GSL_CPLUSPLUS_OPT} /EHsc /W4 /WX $<$: /wd4996 # Use of function or classes marked [[deprecated]] /wd26409 # CppCoreCheck - GTest /wd26426 # CppCoreCheck - GTest /wd26440 # CppCoreCheck - GTest /wd26446 # CppCoreCheck - prefer gsl::at() /wd26472 # CppCoreCheck - use gsl::narrow(_cast) /wd26481 # CppCoreCheck - use span instead of pointer arithmetic $<$,1920>: # VS2015 /wd4189 # variable is initialized but not referenced $<$>: # Release, RelWithDebInfo /wd4702 # Unreachable code > > > $<$: -Weverything -Wfloat-equal -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-covered-switch-default # GTest -Wno-deprecated-declarations # Allow tests for [[deprecated]] elements -Wno-global-constructors # GTest -Wno-language-extension-token # GTest gtest-port.h -Wno-missing-braces -Wno-missing-prototypes -Wno-shift-sign-overflow # GTest gtest-port.h -Wno-undef # GTest -Wno-used-but-marked-unused # GTest EXPECT_DEATH -Wno-switch-default # GTest EXPECT_DEATH $<$: # no support for [[maybe_unused]] -Wno-unused-member-function -Wno-unused-variable $<$,15.0.1>: -Wno-deprecated # False positive in MSVC Clang 15.0.1 raises a C++17 warning > > > ) check_cxx_compiler_flag("-Wno-reserved-identifier" WARN_RESERVED_ID) if (WARN_RESERVED_ID) target_compile_options(gsl_tests_config INTERFACE "-Wno-reserved-identifier") endif() else() target_compile_options(gsl_tests_config INTERFACE -fno-strict-aliasing -Wall -Wcast-align -Wconversion -Wctor-dtor-privacy -Werror -Wextra -Wpedantic -Wshadow -Wsign-conversion -Wfloat-equal -Wno-deprecated-declarations # Allow tests for [[deprecated]] elements $<$,$>: -Weverything -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-missing-braces -Wno-covered-switch-default # GTest -Wno-global-constructors # GTest -Wno-missing-prototypes -Wno-padded -Wno-switch-default -Wno-unknown-attributes -Wno-used-but-marked-unused # GTest EXPECT_DEATH -Wno-weak-vtables $<$: # no support for [[maybe_unused]] -Wno-unused-member-function -Wno-unused-variable > > $<$: $<$,4.99>,$,6>>: $<$:-Wno-undefined-func-template> > $<$,$,$>>: -Wno-zero-as-null-pointer-constant # failing Clang Ubuntu 20.04 tests, seems to be a bug with clang 10.0.0 # and clang 11.0.0. (operator< is being re-written by the compiler # as operator<=> and raising the warning) > > $<$: $<$,9.1>,$,10>>: $<$:-Wno-undefined-func-template> > > $<$: -Wdouble-promotion # float implicit to double -Wlogical-op # suspicious uses of logical operators $<$,6>>: -Wduplicated-cond # duplicated if-else conditions -Wmisleading-indentation -Wnull-dereference $<$: # no support for [[maybe_unused]] -Wno-unused-variable > > $<$,7>>: -Wduplicated-branches # identical if-else branches > > ) endif(MSVC) check_cxx_compiler_flag("-Wno-unsafe-buffer-usage" WARN_UNSAFE_BUFFER) if (WARN_UNSAFE_BUFFER) # This test uses very greedy heuristics such as "no pointer arithmetic on raw buffer" target_compile_options(gsl_tests_config INTERFACE "-Wno-unsafe-buffer-usage") endif() # for tests to find the gtest header target_include_directories(gsl_tests_config SYSTEM INTERFACE googletest/googletest/include ) add_executable(gsl_tests algorithm_tests.cpp assertion_tests.cpp at_tests.cpp byte_tests.cpp notnull_tests.cpp owner_tests.cpp pointers_tests.cpp span_compatibility_tests.cpp span_ext_tests.cpp span_tests.cpp strict_notnull_tests.cpp utils_tests.cpp ) target_link_libraries(gsl_tests Microsoft.GSL::GSL gsl_tests_config ${GTestMain_LIBRARIES} ) add_test(gsl_tests gsl_tests) # No exception tests foreach(flag_var CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO) STRING (REGEX REPLACE "/EHsc" "" ${flag_var} "${${flag_var}}") endforeach(flag_var) # this interface adds compile options to how the tests are run # please try to keep entries ordered =) add_library(gsl_tests_config_noexcept INTERFACE) if(MSVC) # MSVC or simulating MSVC target_compile_definitions(gsl_tests_config_noexcept INTERFACE _HAS_EXCEPTIONS=0 # disable exceptions in the Microsoft STL ) target_compile_options(gsl_tests_config_noexcept INTERFACE ${GSL_CPLUSPLUS_OPT} /W4 /WX $<$: /wd4577 /wd4702 /wd26440 # CppCoreCheck - GTest /wd26446 # CppCoreCheck - prefer gsl::at() > $<$: -Weverything -Wfloat-equal -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-missing-prototypes -Wno-unknown-attributes $<$: $<$,15.0.1>: -Wno-deprecated # False positive in MSVC Clang 15.0.1 raises a C++17 warning > > > ) check_cxx_compiler_flag("-Wno-reserved-identifier" WARN_RESERVED_ID) if (WARN_RESERVED_ID) target_compile_options(gsl_tests_config_noexcept INTERFACE "-Wno-reserved-identifier") endif() else() target_compile_options(gsl_tests_config_noexcept INTERFACE -fno-exceptions -fno-strict-aliasing -Wall -Wcast-align -Wconversion -Wctor-dtor-privacy -Werror -Wextra -Wpedantic -Wshadow -Wsign-conversion -Wfloat-equal $<$,$>: -Weverything -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-missing-prototypes -Wno-unknown-attributes -Wno-weak-vtables > $<$: -Wdouble-promotion # float implicit to double -Wlogical-op # suspicious uses of logical operators -Wuseless-cast # casting to its own type $<$,6>>: -Wduplicated-cond # duplicated if-else conditions -Wmisleading-indentation -Wnull-dereference > $<$,7>>: -Wduplicated-branches # identical if-else branches > $<$,8>>: -Wcast-align=strict # increase alignment (i.e. char* to int*) > > ) endif(MSVC) check_cxx_compiler_flag("-Wno-unsafe-buffer-usage" WARN_UNSAFE_BUFFER) if (WARN_UNSAFE_BUFFER) # This test uses very greedy heuristics such as "no pointer arithmetic on raw buffer" target_compile_options(gsl_tests_config_noexcept INTERFACE "-Wno-unsafe-buffer-usage") endif() add_executable(gsl_noexcept_tests no_exception_ensure_tests.cpp) target_link_libraries(gsl_noexcept_tests Microsoft.GSL::GSL gsl_tests_config_noexcept ) add_test(gsl_noexcept_tests gsl_noexcept_tests) GSL-4.2.1/tests/CMakeLists.txt.in000066400000000000000000000006731511561312500164600ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.13) project(googletest-download NONE) include(ExternalProject) ExternalProject_Add(googletest GIT_REPOSITORY https://github.com/google/googletest.git GIT_TAG v1.14.0 SOURCE_DIR "${CMAKE_CURRENT_BINARY_DIR}/googletest-src" BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/googletest-build" CONFIGURE_COMMAND "" BUILD_COMMAND "" INSTALL_COMMAND "" TEST_COMMAND "" ) GSL-4.2.1/tests/algorithm_tests.cpp000066400000000000000000000144241511561312500172260ustar00rootroot00000000000000/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// #include // for array #include // for size_t #include // for copy #include // for span #include #include "deathTestCommon.h" namespace gsl { struct fail_fast; } // namespace gsl using namespace gsl; TEST(algorithm_tests, same_type) { // dynamic source and destination span { std::array src{1, 2, 3, 4, 5}; std::array dst{}; const span src_span(src); const span dst_span(dst); copy(src_span, dst_span); copy(src_span, dst_span.subspan(src_span.size())); for (std::size_t i = 0; i < src.size(); ++i) { EXPECT_TRUE(dst[i] == src[i]); EXPECT_TRUE(dst[i + src.size()] == src[i]); } } // static source and dynamic destination span { std::array src{1, 2, 3, 4, 5}; std::array dst{}; const span src_span(src); const span dst_span(dst); copy(src_span, dst_span); copy(src_span, dst_span.subspan(src_span.size())); for (std::size_t i = 0; i < src.size(); ++i) { EXPECT_TRUE(dst[i] == src[i]); EXPECT_TRUE(dst[i + src.size()] == src[i]); } } // dynamic source and static destination span { std::array src{1, 2, 3, 4, 5}; std::array dst{}; const gsl::span src_span(src); const gsl::span dst_span(dst); copy(src_span, dst_span); copy(src_span, dst_span.subspan(src_span.size())); for (std::size_t i = 0; i < src.size(); ++i) { EXPECT_TRUE(dst[i] == src[i]); EXPECT_TRUE(dst[i + src.size()] == src[i]); } } // static source and destination span { std::array src{1, 2, 3, 4, 5}; std::array dst{}; const span src_span(src); const span dst_span(dst); copy(src_span, dst_span); copy(src_span, dst_span.subspan(src_span.size())); for (std::size_t i = 0; i < src.size(); ++i) { EXPECT_TRUE(dst[i] == src[i]); EXPECT_TRUE(dst[i + src.size()] == src[i]); } } } TEST(algorithm_tests, compatible_type) { // dynamic source and destination span { std::array src{1, 2, 3, 4, 5}; std::array dst{}; const span src_span(src); const span dst_span(dst); copy(src_span, dst_span); copy(src_span, dst_span.subspan(src_span.size())); for (std::size_t i = 0; i < src.size(); ++i) { EXPECT_TRUE(dst[i] == src[i]); EXPECT_TRUE(dst[i + src.size()] == src[i]); } } // static source and dynamic destination span { std::array src{1, 2, 3, 4, 5}; std::array dst{}; const span src_span(src); const span dst_span(dst); copy(src_span, dst_span); copy(src_span, dst_span.subspan(src_span.size())); for (std::size_t i = 0; i < src.size(); ++i) { EXPECT_TRUE(dst[i] == src[i]); EXPECT_TRUE(dst[i + src.size()] == src[i]); } } // dynamic source and static destination span { std::array src{1, 2, 3, 4, 5}; std::array dst{}; const span src_span(src); const span dst_span(dst); copy(src_span, dst_span); copy(src_span, dst_span.subspan(src_span.size())); for (std::size_t i = 0; i < src.size(); ++i) { EXPECT_TRUE(dst[i] == src[i]); EXPECT_TRUE(dst[i + src.size()] == src[i]); } } // static source and destination span { std::array src{1, 2, 3, 4, 5}; std::array dst{}; const span src_span(src); const span dst_span(dst); copy(src_span, dst_span); copy(src_span, dst_span.subspan(src_span.size())); for (std::size_t i = 0; i < src.size(); ++i) { EXPECT_TRUE(dst[i] == src[i]); EXPECT_TRUE(dst[i + src.size()] == src[i]); } } } #ifdef CONFIRM_COMPILATION_ERRORS TEST(algorithm_tests, incompatible_type) { std::array src{1, 2, 3, 4}; std::array dst{}; span src_span_dyn(src); span src_span_static(src); span dst_span_dyn(dst); span dst_span_static(gsl::make_span(dst)); // every line should produce a compilation error copy(src_span_dyn, dst_span_dyn); copy(src_span_dyn, dst_span_static); copy(src_span_static, dst_span_dyn); copy(src_span_static, dst_span_static); } #endif TEST(algorithm_tests, small_destination_span) { const auto terminateHandler = std::set_terminate([] { std::cerr << "Expected Death. small_destination_span"; std::abort(); }); const auto expected = GetExpectedDeathString(terminateHandler); std::array src{1, 2, 3, 4}; std::array dst{}; const span src_span_dyn(src); const span src_span_static(src); const span dst_span_dyn(dst); const span dst_span_static(dst); EXPECT_DEATH(copy(src_span_dyn, dst_span_dyn), expected); EXPECT_DEATH(copy(src_span_dyn, dst_span_static), expected); EXPECT_DEATH(copy(src_span_static, dst_span_dyn), expected); #ifdef CONFIRM_COMPILATION_ERRORS copy(src_span_static, dst_span_static); #endif } GSL-4.2.1/tests/assertion_tests.cpp000066400000000000000000000030711511561312500172430ustar00rootroot00000000000000/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// #include "deathTestCommon.h" #include // for Ensures, Expects #include using namespace gsl; namespace { int f(int i) { Expects(i > 0 && i < 10); return i; } int g(int i) { i++; Ensures(i > 0 && i < 10); return i; } } // namespace TEST(assertion_tests, expects) { const auto terminateHandler = std::set_terminate([] { std::cerr << "Expected Death. expects"; std::abort(); }); EXPECT_TRUE(f(2) == 2); EXPECT_DEATH(f(10), GetExpectedDeathString(terminateHandler)); } TEST(assertion_tests, ensures) { const auto terminateHandler = std::set_terminate([] { std::cerr << "Expected Death. ensures"; std::abort(); }); EXPECT_TRUE(g(2) == 3); EXPECT_DEATH(g(9), GetExpectedDeathString(terminateHandler)); } GSL-4.2.1/tests/at_tests.cpp000066400000000000000000000127441511561312500156470ustar00rootroot00000000000000/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// #include #include // for at #include // for array #include // for size_t #include // for terminate #include // for initializer_list #include // for vector #if defined(__cplusplus) && __cplusplus >= 202002L #include #endif // __cplusplus >= 202002L #include "deathTestCommon.h" TEST(at_tests, static_array) { int a[4] = {1, 2, 3, 4}; const int(&c_a)[4] = a; for (int i = 0; i < 4; ++i) { EXPECT_TRUE(&gsl::at(a, i) == &a[i]); EXPECT_TRUE(&gsl::at(c_a, i) == &a[i]); } const auto terminateHandler = std::set_terminate([] { std::cerr << "Expected Death. static_array"; std::abort(); }); const auto expected = GetExpectedDeathString(terminateHandler); EXPECT_DEATH(gsl::at(a, -1), expected); EXPECT_DEATH(gsl::at(a, 4), expected); EXPECT_DEATH(gsl::at(c_a, -1), expected); EXPECT_DEATH(gsl::at(c_a, 4), expected); } TEST(at_tests, std_array) { std::array a = {1, 2, 3, 4}; const std::array& c_a = a; for (int i = 0; i < 4; ++i) { EXPECT_TRUE(&gsl::at(a, i) == &a[static_cast(i)]); EXPECT_TRUE(&gsl::at(c_a, i) == &a[static_cast(i)]); } const auto terminateHandler = std::set_terminate([] { std::cerr << "Expected Death. std_array"; std::abort(); }); const auto expected = GetExpectedDeathString(terminateHandler); EXPECT_DEATH(gsl::at(a, -1), expected); EXPECT_DEATH(gsl::at(a, 4), expected); EXPECT_DEATH(gsl::at(c_a, -1), expected); EXPECT_DEATH(gsl::at(c_a, 4), expected); } TEST(at_tests, std_vector) { std::vector a = {1, 2, 3, 4}; const std::vector& c_a = a; for (int i = 0; i < 4; ++i) { EXPECT_TRUE(&gsl::at(a, i) == &a[static_cast(i)]); EXPECT_TRUE(&gsl::at(c_a, i) == &a[static_cast(i)]); } const auto terminateHandler = std::set_terminate([] { std::cerr << "Expected Death. std_vector"; std::abort(); }); const auto expected = GetExpectedDeathString(terminateHandler); EXPECT_DEATH(gsl::at(a, -1), expected); EXPECT_DEATH(gsl::at(a, 4), expected); EXPECT_DEATH(gsl::at(c_a, -1), expected); EXPECT_DEATH(gsl::at(c_a, 4), expected); } TEST(at_tests, InitializerList) { const std::initializer_list a = {1, 2, 3, 4}; for (int i = 0; i < 4; ++i) { EXPECT_TRUE(gsl::at(a, i) == i + 1); EXPECT_TRUE(gsl::at({1, 2, 3, 4}, i) == i + 1); } const auto terminateHandler = std::set_terminate([] { std::cerr << "Expected Death. InitializerList"; std::abort(); }); const auto expected = GetExpectedDeathString(terminateHandler); EXPECT_DEATH(gsl::at(a, -1), expected); EXPECT_DEATH(gsl::at(a, 4), expected); EXPECT_DEATH(gsl::at({1, 2, 3, 4}, -1), expected); EXPECT_DEATH(gsl::at({1, 2, 3, 4}, 4), expected); } #if defined(FORCE_STD_SPAN_TESTS) || defined(__cpp_lib_span) && __cpp_lib_span >= 202002L TEST(at_tests, std_span) { std::vector vec{1, 2, 3, 4, 5}; std::span sp{vec}; std::vector cvec{1, 2, 3, 4, 5}; std::span csp{cvec}; for (gsl::index i = 0; i < gsl::narrow_cast(vec.size()); ++i) { EXPECT_TRUE(&gsl::at(sp, i) == &vec[gsl::narrow_cast(i)]); EXPECT_TRUE(&gsl::at(csp, i) == &cvec[gsl::narrow_cast(i)]); } const auto terminateHandler = std::set_terminate([] { std::cerr << "Expected Death. std_span"; std::abort(); }); const auto expected = GetExpectedDeathString(terminateHandler); EXPECT_DEATH(gsl::at(sp, -1), expected); EXPECT_DEATH(gsl::at(sp, gsl::narrow_cast(sp.size())), expected); EXPECT_DEATH(gsl::at(csp, -1), expected); EXPECT_DEATH(gsl::at(csp, gsl::narrow_cast(sp.size())), expected); } #endif // defined(FORCE_STD_SPAN_TESTS) || defined(__cpp_lib_span) && __cpp_lib_span >= 202002L #if !defined(_MSC_VER) || defined(__clang__) || _MSC_VER >= 1910 static constexpr bool test_constexpr() { int a1[4] = {1, 2, 3, 4}; const int(&c_a1)[4] = a1; std::array a2 = {1, 2, 3, 4}; const std::array& c_a2 = a2; for (int i = 0; i < 4; ++i) { if (&gsl::at(a1, i) != &a1[i]) return false; if (&gsl::at(c_a1, i) != &a1[i]) return false; // requires C++17: // if (&gsl::at(a2, i) != &a2[static_cast(i)]) return false; if (&gsl::at(c_a2, i) != &c_a2[static_cast(i)]) return false; if (gsl::at({1, 2, 3, 4}, i) != i + 1) return false; } return true; } static_assert(test_constexpr(), "FAIL"); #endif GSL-4.2.1/tests/byte_tests.cpp000066400000000000000000000123621511561312500162020ustar00rootroot00000000000000/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// #include #define GSL_USE_STD_BYTE 0 #include // for to_byte, to_integer, byte, operator&, ope... #include #include using namespace std; using namespace gsl; namespace { int modify_both(gsl::byte& b, int& i) { i = 10; b = to_byte<5>(); return i; } TEST(byte_tests, construction) { { const gsl::byte b = static_cast(4); EXPECT_TRUE(static_cast(b) == 4); } { const gsl::byte b = gsl::byte(12); EXPECT_TRUE(static_cast(b) == 12); } { const gsl::byte b = to_byte<12>(); EXPECT_TRUE(static_cast(b) == 12); } { const unsigned char uc = 12; const gsl::byte b = to_byte(uc); EXPECT_TRUE(static_cast(b) == 12); } #if defined(__cplusplus) && (__cplusplus >= 201703L) { const gsl::byte b{14}; EXPECT_TRUE(static_cast(b) == 14); } #endif #ifdef CONFIRM_COMPILATION_ERRORS to_byte(char{}); to_byte(3); to_byte(3u); to_byte<-1>(); to_byte<256u>(); #endif } TEST(byte_tests, bitwise_operations) { const gsl::byte b = to_byte<0xFF>(); gsl::byte a = to_byte<0x00>(); EXPECT_TRUE((b | a) == to_byte<0xFF>()); EXPECT_TRUE(a == to_byte<0x00>()); a |= b; EXPECT_TRUE(a == to_byte<0xFF>()); a = to_byte<0x01>(); EXPECT_TRUE((b & a) == to_byte<0x01>()); a &= b; EXPECT_TRUE(a == to_byte<0x01>()); EXPECT_TRUE((b ^ a) == to_byte<0xFE>()); EXPECT_TRUE(a == to_byte<0x01>()); a ^= b; EXPECT_TRUE(a == to_byte<0xFE>()); a = to_byte<0x01>(); EXPECT_TRUE(~a == to_byte<0xFE>()); a = to_byte<0xFF>(); EXPECT_TRUE((a << 4) == to_byte<0xF0>()); EXPECT_TRUE((a >> 4) == to_byte<0x0F>()); a <<= 4; EXPECT_TRUE(a == to_byte<0xF0>()); a >>= 4; EXPECT_TRUE(a == to_byte<0x0F>()); } TEST(byte_tests, to_integer) { const gsl::byte b = to_byte<0x12>(); EXPECT_TRUE(0x12 == gsl::to_integer(b)); EXPECT_TRUE(0x12 == gsl::to_integer(b)); EXPECT_TRUE(0x12 == gsl::to_integer(b)); EXPECT_TRUE(0x12 == gsl::to_integer(b)); EXPECT_TRUE(0x12 == gsl::to_integer(b)); EXPECT_TRUE(0x12 == gsl::to_integer(b)); EXPECT_TRUE(0x12 == gsl::to_integer(b)); EXPECT_TRUE(0x12 == gsl::to_integer(b)); // EXPECT_TRUE(0x12 == gsl::to_integer(b)); // expect compile-time error // EXPECT_TRUE(0x12 == gsl::to_integer(b)); // expect compile-time error } TEST(byte_tests, aliasing) { int i{0}; const int res = modify_both(reinterpret_cast(i), i); EXPECT_TRUE(res == i); } #if __cplusplus >= 201703l using std::void_t; #else // __cplusplus >= 201703l template using void_t = void; #endif // __cplusplus < 201703l template static constexpr bool LShiftCompilesFor = false; template static constexpr bool LShiftCompilesFor< U, void_t(declval(), declval()))>> = true; static_assert(!LShiftCompilesFor, "!LShiftCompilesFor"); template static constexpr bool RShiftCompilesFor = false; template static constexpr bool RShiftCompilesFor< U, void_t> (declval(), declval()))>> = true; static_assert(!RShiftCompilesFor, "!RShiftCompilesFor"); template static constexpr bool LShiftAssignCompilesFor = false; template static constexpr bool LShiftAssignCompilesFor< U, void_t(declval(), declval()))>> = true; static_assert(!LShiftAssignCompilesFor, "!LShiftAssignCompilesFor"); template static constexpr bool RShiftAssignCompilesFor = false; template static constexpr bool RShiftAssignCompilesFor< U, void_t>= (declval(), declval()))>> = true; static_assert(!RShiftAssignCompilesFor, "!RShiftAssignCompilesFor"); template static constexpr bool ToIntegerCompilesFor = false; template static constexpr bool ToIntegerCompilesFor(gsl::byte{}))>> = true; static_assert(!ToIntegerCompilesFor, "!ToIntegerCompilesFor"); } // namespace GSL-4.2.1/tests/deathTestCommon.h000066400000000000000000000005741511561312500165620ustar00rootroot00000000000000#pragma once #include constexpr char deathstring[] = "Expected Death"; constexpr char failed_set_terminate_deathstring[] = ".*"; // This prevents a failed call to set_terminate from failing the test suite. constexpr const char* GetExpectedDeathString(std::terminate_handler handle) { return handle ? deathstring : failed_set_terminate_deathstring; } GSL-4.2.1/tests/no_exception_ensure_tests.cpp000066400000000000000000000031541511561312500213110ustar00rootroot00000000000000/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// #include #include // for std::exit #include // for span #include #include int operator_subscript_no_throw() noexcept { int arr[10]; const gsl::span sp{arr}; return sp[11]; } [[noreturn]] void test_terminate() { std::exit(0); } void setup_termination_handler() noexcept { #if defined(GSL_MSVC_USE_STL_NOEXCEPTION_WORKAROUND) auto& handler = gsl::details::get_terminate_handler(); handler = &test_terminate; #else std::set_terminate(test_terminate); #endif } int main() noexcept { std::cout << "Running main() from " __FILE__ "\n"; #if defined(IOS_PROCESS_DELAY_WORKAROUND) std::this_thread::sleep_for(std::chrono::seconds(1)); #endif setup_termination_handler(); operator_subscript_no_throw(); return -1; } GSL-4.2.1/tests/notnull_tests.cpp000066400000000000000000000550411511561312500167330ustar00rootroot00000000000000/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// #include #include // for not_null, operator<, operator<=, operator> #include // for addressof #include // for uint16_t #include // for shared_ptr, make_shared, operator<, opera... #include // for operator<<, ostringstream, basic_ostream:... #include // for basic_string, operator==, string, operator<< #include // for declval #include // for type_info #include // for variant, monostate, get #include "deathTestCommon.h" using namespace gsl; #if __cplusplus >= 201703l using std::void_t; #else // __cplusplus >= 201703l template using void_t = void; #endif // __cplusplus < 201703l struct MyBase { }; struct MyDerived : public MyBase { }; struct Unrelated { }; // stand-in for a user-defined ref-counted class template struct RefCounted { RefCounted(T* p) : p_(p) {} operator T*() { return p_; } T* p_; }; // user defined smart pointer with comparison operators returning non bool value template struct CustomPtr { CustomPtr(T* p) : p_(p) {} operator T*() const { return p_; } bool operator!=(std::nullptr_t) const { return p_ != nullptr; } T* p_ = nullptr; }; template std::string operator==(CustomPtr const& lhs, CustomPtr const& rhs) { // clang-format off GSL_SUPPRESS(type.1) // NO-FORMAT: attribute // clang-format on return reinterpret_cast(lhs.p_) == reinterpret_cast(rhs.p_) ? "true" : "false"; } template std::string operator!=(CustomPtr const& lhs, CustomPtr const& rhs) { // clang-format off GSL_SUPPRESS(type.1) // NO-FORMAT: attribute // clang-format on return reinterpret_cast(lhs.p_) != reinterpret_cast(rhs.p_) ? "true" : "false"; } template std::string operator<(CustomPtr const& lhs, CustomPtr const& rhs) { // clang-format off GSL_SUPPRESS(type.1) // NO-FORMAT: attribute // clang-format on return reinterpret_cast(lhs.p_) < reinterpret_cast(rhs.p_) ? "true" : "false"; } template std::string operator>(CustomPtr const& lhs, CustomPtr const& rhs) { // clang-format off GSL_SUPPRESS(type.1) // NO-FORMAT: attribute // clang-format on return reinterpret_cast(lhs.p_) > reinterpret_cast(rhs.p_) ? "true" : "false"; } template std::string operator<=(CustomPtr const& lhs, CustomPtr const& rhs) { // clang-format off GSL_SUPPRESS(type.1) // NO-FORMAT: attribute // clang-format on return reinterpret_cast(lhs.p_) <= reinterpret_cast(rhs.p_) ? "true" : "false"; } template std::string operator>=(CustomPtr const& lhs, CustomPtr const& rhs) { // clang-format off GSL_SUPPRESS(type.1) // NO-FORMAT: attribute // clang-format on return reinterpret_cast(lhs.p_) >= reinterpret_cast(rhs.p_) ? "true" : "false"; } struct NonCopyableNonMovable { NonCopyableNonMovable() = default; NonCopyableNonMovable(const NonCopyableNonMovable&) = delete; NonCopyableNonMovable& operator=(const NonCopyableNonMovable&) = delete; NonCopyableNonMovable(NonCopyableNonMovable&&) = delete; NonCopyableNonMovable& operator=(NonCopyableNonMovable&&) = delete; }; namespace { // clang-format off GSL_SUPPRESS(f .4) // NO-FORMAT: attribute // clang-format on bool helper(not_null p) { return *p == 12; } // clang-format off GSL_SUPPRESS(f .4) // NO-FORMAT: attribute // clang-format on bool helper_const(not_null p) { return *p == 12; } int* return_pointer() { return nullptr; } } // namespace template static constexpr bool CtorCompilesFor_A = false; template static constexpr bool CtorCompilesFor_A{std::declval()})>> = true; template static constexpr bool CtorCompilesFor_B = false; template static constexpr bool CtorCompilesFor_B{N})>> = true; template static constexpr bool DefaultCtorCompilesFor = false; template static constexpr bool DefaultCtorCompilesFor{})>> = true; template static constexpr bool CtorCompilesFor_C = false; template static constexpr bool CtorCompilesFor_C{std::declval>()})>> = true; TEST(notnull_tests, TestNotNullConstructors) { { static_assert(CtorCompilesFor_A, "CtorCompilesFor_A"); static_assert(!CtorCompilesFor_A, "!CtorCompilesFor_A"); static_assert(!CtorCompilesFor_B, "!CtorCompilesFor_B"); static_assert(!DefaultCtorCompilesFor, "!DefaultCtorCompilesFor"); static_assert(!CtorCompilesFor_C, "CtorCompilesFor_C"); #ifdef CONFIRM_COMPILATION_ERRORS // Forbid non-nullptr assignable types not_null> f(std::vector{1}); not_null z(10); not_null> y({1, 2}); #endif } const auto terminateHandler = std::set_terminate([] { std::cerr << "Expected Death. TestNotNullConstructors"; std::abort(); }); const auto expected = GetExpectedDeathString(terminateHandler); { // from shared pointer int i = 12; auto rp = RefCounted(&i); not_null p(rp); EXPECT_TRUE(p.get() == &i); not_null> x( std::make_shared(10)); // shared_ptr is nullptr assignable int* pi = nullptr; EXPECT_DEATH((not_null(pi)), expected); } { // from unique pointer not_null> x( std::make_unique(10)); // unique_ptr is nullptr assignable EXPECT_DEATH((not_null>(std::unique_ptr{})), expected); } { // from pointer to local int t = 42; not_null x = &t; helper(&t); helper_const(&t); EXPECT_TRUE(*x == 42); } { // from raw pointer // from not_null pointer int t = 42; int* p = &t; not_null x = p; helper(p); helper_const(p); helper(x); helper_const(x); EXPECT_TRUE(*x == 42); } { // from raw const pointer // from not_null const pointer int t = 42; const int* cp = &t; not_null x = cp; helper_const(cp); helper_const(x); EXPECT_TRUE(*x == 42); } { // from not_null const pointer, using auto int t = 42; const int* cp = &t; auto x = not_null{cp}; EXPECT_TRUE(*x == 42); } { // from returned pointer EXPECT_DEATH(helper(return_pointer()), expected); EXPECT_DEATH(helper_const(return_pointer()), expected); } } template void ostream_helper(T v) { not_null p(&v); { std::ostringstream os; std::ostringstream ref; os << static_cast(p); ref << static_cast(&v); EXPECT_TRUE(os.str() == ref.str()); } { std::ostringstream os; std::ostringstream ref; os << *p; ref << v; EXPECT_TRUE(os.str() == ref.str()); } } TEST(notnull_tests, TestNotNullostream) { ostream_helper(17); ostream_helper(21.5f); ostream_helper(3.4566e-7); ostream_helper('c'); ostream_helper(0x0123u); ostream_helper("cstring"); ostream_helper("string"); } template static constexpr bool AssignmentCompilesFor = false; template static constexpr bool AssignmentCompilesFor&>().operator=( std::declval&>()))>> = true; template static constexpr bool SCastCompilesFor = false; template static constexpr bool SCastCompilesFor(std::declval&>()))>> = true; template static constexpr bool RCastCompilesFor = false; template static constexpr bool RCastCompilesFor< U, V, void_t(std::declval&>()))>> = true; TEST(notnull_tests, TestNotNullCasting) { MyBase base; MyDerived derived; Unrelated unrelated; not_null u{&unrelated}; (void) u; not_null p{&derived}; not_null q(&base); q = p; // allowed with heterogeneous copy ctor EXPECT_TRUE(q == p); static_assert(AssignmentCompilesFor, "AssignmentCompilesFor"); static_assert(!AssignmentCompilesFor, "!AssignmentCompilesFor"); static_assert(!AssignmentCompilesFor, "!AssignmentCompilesFor"); static_assert(!AssignmentCompilesFor, "!AssignmentCompilesFor"); static_assert(SCastCompilesFor, "SCastCompilesFor"); static_assert(SCastCompilesFor, "SCastCompilesFor"); static_assert(!SCastCompilesFor, "!SCastCompilesFor"); static_assert(!SCastCompilesFor, "!SCastCompilesFor"); static_assert(!RCastCompilesFor, "!SCastCompilesFor"); static_assert(!RCastCompilesFor, "!SCastCompilesFor"); not_null t(reinterpret_cast(p.get())); EXPECT_TRUE(reinterpret_cast(p.get()) == reinterpret_cast(t.get())); (void) static_cast(p); (void) static_cast(p); } TEST(notnull_tests, TestNotNullAssignment) { const auto terminateHandler = std::set_terminate([] { std::cerr << "Expected Death. TestNotNullAssignmentd"; std::abort(); }); const auto expected = GetExpectedDeathString(terminateHandler); int i = 12; not_null p(&i); EXPECT_TRUE(helper(p)); int* q = nullptr; EXPECT_DEATH(p = not_null(q), expected); } TEST(notnull_tests, TestNotNullRawPointerComparison) { int ints[2] = {42, 43}; int* p1 = &ints[0]; const int* p2 = &ints[1]; using NotNull1 = not_null; using NotNull2 = not_null; EXPECT_TRUE((NotNull1(p1) == NotNull1(p1)) == true); EXPECT_TRUE((NotNull1(p1) == NotNull2(p2)) == false); EXPECT_TRUE((NotNull1(p1) != NotNull1(p1)) == false); EXPECT_TRUE((NotNull1(p1) != NotNull2(p2)) == true); EXPECT_TRUE((NotNull1(p1) < NotNull1(p1)) == false); EXPECT_TRUE((NotNull1(p1) < NotNull2(p2)) == (p1 < p2)); EXPECT_TRUE((NotNull2(p2) < NotNull1(p1)) == (p2 < p1)); EXPECT_TRUE((NotNull1(p1) > NotNull1(p1)) == false); EXPECT_TRUE((NotNull1(p1) > NotNull2(p2)) == (p1 > p2)); EXPECT_TRUE((NotNull2(p2) > NotNull1(p1)) == (p2 > p1)); EXPECT_TRUE((NotNull1(p1) <= NotNull1(p1)) == true); EXPECT_TRUE((NotNull1(p1) <= NotNull2(p2)) == (p1 <= p2)); EXPECT_TRUE((NotNull2(p2) <= NotNull1(p1)) == (p2 <= p1)); } TEST(notnull_tests, TestNotNullDereferenceOperator) { { auto sp1 = std::make_shared(); using NotNullSp1 = not_null; EXPECT_TRUE(typeid(*sp1) == typeid(*NotNullSp1(sp1))); EXPECT_TRUE(std::addressof(*NotNullSp1(sp1)) == std::addressof(*sp1)); } { int ints[1] = {42}; CustomPtr p1(&ints[0]); using NotNull1 = not_null; EXPECT_TRUE(typeid(*NotNull1(p1)) == typeid(*p1)); EXPECT_TRUE(*NotNull1(p1) == 42); *NotNull1(p1) = 43; EXPECT_TRUE(ints[0] == 43); } { int v = 42; gsl::not_null p(&v); EXPECT_TRUE(typeid(*p) == typeid(*(&v))); *p = 43; EXPECT_TRUE(v == 43); } } TEST(notnull_tests, TestNotNullSharedPtrComparison) { auto sp1 = std::make_shared(42); auto sp2 = std::make_shared(43); using NotNullSp1 = not_null; using NotNullSp2 = not_null; EXPECT_TRUE((NotNullSp1(sp1) == NotNullSp1(sp1)) == true); EXPECT_TRUE((NotNullSp1(sp1) == NotNullSp2(sp2)) == false); EXPECT_TRUE((NotNullSp1(sp1) != NotNullSp1(sp1)) == false); EXPECT_TRUE((NotNullSp1(sp1) != NotNullSp2(sp2)) == true); EXPECT_TRUE((NotNullSp1(sp1) < NotNullSp1(sp1)) == false); EXPECT_TRUE((NotNullSp1(sp1) < NotNullSp2(sp2)) == (sp1 < sp2)); EXPECT_TRUE((NotNullSp2(sp2) < NotNullSp1(sp1)) == (sp2 < sp1)); EXPECT_TRUE((NotNullSp1(sp1) > NotNullSp1(sp1)) == false); EXPECT_TRUE((NotNullSp1(sp1) > NotNullSp2(sp2)) == (sp1 > sp2)); EXPECT_TRUE((NotNullSp2(sp2) > NotNullSp1(sp1)) == (sp2 > sp1)); EXPECT_TRUE((NotNullSp1(sp1) <= NotNullSp1(sp1)) == true); EXPECT_TRUE((NotNullSp1(sp1) <= NotNullSp2(sp2)) == (sp1 <= sp2)); EXPECT_TRUE((NotNullSp2(sp2) <= NotNullSp1(sp1)) == (sp2 <= sp1)); EXPECT_TRUE((NotNullSp1(sp1) >= NotNullSp1(sp1)) == true); EXPECT_TRUE((NotNullSp1(sp1) >= NotNullSp2(sp2)) == (sp1 >= sp2)); EXPECT_TRUE((NotNullSp2(sp2) >= NotNullSp1(sp1)) == (sp2 >= sp1)); } TEST(notnull_tests, TestNotNullCustomPtrComparison) { int ints[2] = {42, 43}; CustomPtr p1(&ints[0]); CustomPtr p2(&ints[1]); using NotNull1 = not_null; using NotNull2 = not_null; EXPECT_TRUE((NotNull1(p1) == NotNull1(p1)) == "true"); EXPECT_TRUE((NotNull1(p1) == NotNull2(p2)) == "false"); EXPECT_TRUE((NotNull1(p1) != NotNull1(p1)) == "false"); EXPECT_TRUE((NotNull1(p1) != NotNull2(p2)) == "true"); EXPECT_TRUE((NotNull1(p1) < NotNull1(p1)) == "false"); EXPECT_TRUE((NotNull1(p1) < NotNull2(p2)) == (p1 < p2)); EXPECT_TRUE((NotNull2(p2) < NotNull1(p1)) == (p2 < p1)); EXPECT_TRUE((NotNull1(p1) > NotNull1(p1)) == "false"); EXPECT_TRUE((NotNull1(p1) > NotNull2(p2)) == (p1 > p2)); EXPECT_TRUE((NotNull2(p2) > NotNull1(p1)) == (p2 > p1)); EXPECT_TRUE((NotNull1(p1) <= NotNull1(p1)) == "true"); EXPECT_TRUE((NotNull1(p1) <= NotNull2(p2)) == (p1 <= p2)); EXPECT_TRUE((NotNull2(p2) <= NotNull1(p1)) == (p2 <= p1)); EXPECT_TRUE((NotNull1(p1) >= NotNull1(p1)) == "true"); EXPECT_TRUE((NotNull1(p1) >= NotNull2(p2)) == (p1 >= p2)); EXPECT_TRUE((NotNull2(p2) >= NotNull1(p1)) == (p2 >= p1)); } #if defined(__cplusplus) && (__cplusplus >= 201703L) template static constexpr bool TypeDeductionCtorCompilesFor = false; template static constexpr bool TypeDeductionCtorCompilesFor()})>> = true; template static constexpr bool TypeDeductionHelperCompilesFor = false; template static constexpr bool TypeDeductionHelperCompilesFor()}))>> = true; TEST(notnull_tests, TestNotNullConstructorTypeDeduction) { { int i = 42; not_null x{&i}; helper(not_null{&i}); helper_const(not_null{&i}); EXPECT_TRUE(*x == 42); } { const int i = 42; not_null x{&i}; static_assert(TypeDeductionHelperCompilesFor, "TypeDeductionHelperCompilesFor"); static_assert(!TypeDeductionHelperCompilesFor, "!TypeDeductionHelperCompilesFor"); helper_const(not_null{&i}); EXPECT_TRUE(*x == 42); } { int i = 42; int* p = &i; not_null x{p}; helper(not_null{p}); helper_const(not_null{p}); EXPECT_TRUE(*x == 42); } { const int i = 42; const int* p = &i; not_null x{p}; helper_const(not_null{p}); EXPECT_TRUE(*x == 42); } const auto terminateHandler = std::set_terminate([] { std::cerr << "Expected Death. TestNotNullConstructorTypeDeduction"; std::abort(); }); const auto expected = GetExpectedDeathString(terminateHandler); { auto workaround_macro = []() { int* p1 = nullptr; const not_null x{p1}; }; EXPECT_DEATH(workaround_macro(), expected); } { auto workaround_macro = []() { const int* p1 = nullptr; const not_null x{p1}; }; EXPECT_DEATH(workaround_macro(), expected); } { int* p = nullptr; EXPECT_DEATH(helper(not_null{p}), expected); EXPECT_DEATH(helper_const(not_null{p}), expected); } static_assert(TypeDeductionCtorCompilesFor, "TypeDeductionCtorCompilesFor"); #if defined(_MSC_VER) && !defined(__clang__) // Fails on gcc, clang, xcode, VS clang with // "error : no type named 'type' in 'std::enable_if'; 'enable_if' cannot be used to // disable this declaration" static_assert(!TypeDeductionCtorCompilesFor, "!TypeDeductionCtorCompilesFor"); static_assert(!TypeDeductionHelperCompilesFor, "!TypeDeductionHelperCompilesFor"); #endif } TEST(notnull_tests, TestVariantEmplace) { int i = 0; std::variant> v; v.emplace>(&i); EXPECT_FALSE(v.valueless_by_exception()); EXPECT_TRUE(v.index() == 1); EXPECT_TRUE(std::get>(v) == &i); } #endif // #if defined(__cplusplus) && (__cplusplus >= 201703L) template static constexpr bool HelperCompilesFor = false; template static constexpr bool HelperCompilesFor()))>> = true; TEST(notnull_tests, TestMakeNotNull) { { int i = 42; const auto x = make_not_null(&i); helper(make_not_null(&i)); helper_const(make_not_null(&i)); EXPECT_TRUE(*x == 42); } { const int i = 42; const auto x = make_not_null(&i); static_assert(HelperCompilesFor>, "HelperCompilesFor>"); helper_const(make_not_null(&i)); EXPECT_TRUE(*x == 42); } { int i = 42; int* p = &i; const auto x = make_not_null(p); helper(make_not_null(p)); helper_const(make_not_null(p)); EXPECT_TRUE(*x == 42); } { const int i = 42; const int* p = &i; const auto x = make_not_null(p); static_assert(!HelperCompilesFor>, "!HelperCompilesFor>"); helper_const(make_not_null(p)); EXPECT_TRUE(*x == 42); } const auto terminateHandler = std::set_terminate([] { std::cerr << "Expected Death. TestMakeNotNull"; std::abort(); }); const auto expected = GetExpectedDeathString(terminateHandler); { const auto workaround_macro = []() { int* p1 = nullptr; const auto x = make_not_null(p1); EXPECT_TRUE(*x == 42); }; EXPECT_DEATH(workaround_macro(), expected); } { const auto workaround_macro = []() { const int* p1 = nullptr; const auto x = make_not_null(p1); EXPECT_TRUE(*x == 42); }; EXPECT_DEATH(workaround_macro(), expected); } { int* p = nullptr; EXPECT_DEATH(helper(make_not_null(p)), expected); EXPECT_DEATH(helper_const(make_not_null(p)), expected); } #ifdef CONFIRM_COMPILATION_ERRORS { EXPECT_DEATH(make_not_null(nullptr), expected); EXPECT_DEATH(helper(make_not_null(nullptr)), expected); EXPECT_DEATH(helper_const(make_not_null(nullptr)), expected); } #endif } TEST(notnull_tests, TestStdHash) { { int x = 42; int y = 99; not_null nn{&x}; const not_null cnn{&x}; std::hash> hash_nn; std::hash hash_intptr; EXPECT_TRUE(hash_nn(nn) == hash_intptr(&x)); EXPECT_FALSE(hash_nn(nn) == hash_intptr(&y)); EXPECT_FALSE(hash_nn(nn) == hash_intptr(nullptr)); } { const int x = 42; const int y = 99; not_null nn{&x}; const not_null cnn{&x}; std::hash> hash_nn; std::hash hash_intptr; EXPECT_TRUE(hash_nn(nn) == hash_intptr(&x)); EXPECT_FALSE(hash_nn(nn) == hash_intptr(&y)); EXPECT_FALSE(hash_nn(nn) == hash_intptr(nullptr)); } } GSL-4.2.1/tests/owner_tests.cpp000066400000000000000000000032521511561312500163670ustar00rootroot00000000000000/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// #include #include // for owner #include // for declval using namespace gsl; GSL_SUPPRESS(f .23) // NO-FORMAT: attribute void f(int* i) { *i += 1; } TEST(owner_tests, basic_test) { owner p = new int(120); EXPECT_TRUE(*p == 120); f(p); EXPECT_TRUE(*p == 121); delete p; } #if __cplusplus >= 201703l using std::void_t; #else // __cplusplus >= 201703l template using void_t = void; #endif // __cplusplus < 201703l template static constexpr bool OwnerCompilesFor = false; template static constexpr bool OwnerCompilesFor{})>> = true; static_assert(OwnerCompilesFor, "OwnerCompilesFor"); static_assert(!OwnerCompilesFor, "!OwnerCompilesFor"); static_assert(!OwnerCompilesFor>, "!OwnerCompilesFor>"); GSL-4.2.1/tests/pointers_tests.cpp000066400000000000000000000055211511561312500171010ustar00rootroot00000000000000#include #include #include #include #include #if __cplusplus >= 201703l using std::void_t; #else // __cplusplus >= 201703l template using void_t = void; #endif // __cplusplus < 201703l namespace { // Custom pointer type that can be used for gsl::not_null, but for which these cannot be swapped. struct NotMoveAssignableCustomPtr { NotMoveAssignableCustomPtr() = default; NotMoveAssignableCustomPtr(const NotMoveAssignableCustomPtr&) = default; NotMoveAssignableCustomPtr& operator=(const NotMoveAssignableCustomPtr&) = default; NotMoveAssignableCustomPtr(NotMoveAssignableCustomPtr&&) = default; NotMoveAssignableCustomPtr& operator=(NotMoveAssignableCustomPtr&&) = delete; bool operator!=(std::nullptr_t) const { return true; } int dummy{}; // Without this clang warns, that NotMoveAssignableCustomPtr() is unneeded }; template static constexpr bool SwapCompilesFor = false; template static constexpr bool SwapCompilesFor(std::declval&>(), std::declval&>()))>> = true; TEST(pointers_test, swap) { // taken from gh-1129: { gsl::not_null> a(std::make_unique(0)); gsl::not_null> b(std::make_unique(1)); EXPECT_TRUE(*a == 0); EXPECT_TRUE(*b == 1); gsl::swap(a, b); EXPECT_TRUE(*a == 1); EXPECT_TRUE(*b == 0); // Make sure our custom ptr can be used with not_null. The shared_pr is to prevent "unused" // compiler warnings. const auto shared_custom_ptr{std::make_shared()}; gsl::not_null c{*shared_custom_ptr}; EXPECT_TRUE(c.get() != nullptr); } { gsl::strict_not_null> a{std::make_unique(0)}; gsl::strict_not_null> b{std::make_unique(1)}; EXPECT_TRUE(*a == 0); EXPECT_TRUE(*b == 1); gsl::swap(a, b); EXPECT_TRUE(*a == 1); EXPECT_TRUE(*b == 0); } { gsl::not_null> a{std::make_unique(0)}; gsl::strict_not_null> b{std::make_unique(1)}; EXPECT_TRUE(*a == 0); EXPECT_TRUE(*b == 1); gsl::swap(a, b); EXPECT_TRUE(*a == 1); EXPECT_TRUE(*b == 0); } static_assert(!SwapCompilesFor, "!SwapCompilesFor"); } TEST(pointers_test, member_types) { static_assert(std::is_same::element_type, int*>::value, "check member type: element_type"); } } // namespace GSL-4.2.1/tests/span_compatibility_tests.cpp000066400000000000000000001662451511561312500211430ustar00rootroot00000000000000/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// #include #include // for byte #include // for span, span_iterator, operator==, operator!= #include // for array #include // for ptrdiff_t #include // for reverse_iterator, operator-, operator== #include // for integral_constant<>::value, is_default_co... #include #include // for vector using namespace std; using namespace gsl; // Below are tests that verify the gsl interface support the same things as the std // Ranges and Concepts support need to be added later. struct Base { }; struct Derived : Base { }; static_assert(std::is_convertible::value, "std::is_convertible"); static_assert(!std::is_convertible::value, "!std::is_convertible"); // int*(*) [], int const* const(*)[] was identified as an issue in CWG330 and the resolution was // provided with N4261. template void ArrayConvertibilityCheck() { #if __cplusplus >= 201703l if constexpr (std::is_convertible::value) { std::array stl_nullptr{{nullptr, nullptr, nullptr}}; gsl::span sp_const_nullptr_1{stl_nullptr}; EXPECT_TRUE(sp_const_nullptr_1.data() == stl_nullptr.data()); EXPECT_TRUE(sp_const_nullptr_1.size() == 3); gsl::span sp_const_nullptr_2{std::as_const(stl_nullptr)}; EXPECT_TRUE(sp_const_nullptr_2.data() == stl_nullptr.data()); EXPECT_TRUE(sp_const_nullptr_2.size() == 3); static_assert(std::is_same>::value, "std::is_same< decltype(span{stl_nullptr}), span>::value"); static_assert( std::is_same>::value, "std::is_same< decltype(span{std::as_const(stl_nullptr)}), span>::value"); } #endif } TEST(span_compatibility_tests, assertion_tests) { int arr[3]{10, 20, 30}; std::array stl{{100, 200, 300}}; ArrayConvertibilityCheck(); { gsl::span sp_dyn; EXPECT_TRUE(sp_dyn.data() == nullptr); EXPECT_TRUE(sp_dyn.size() == 0); EXPECT_TRUE(sp_dyn.empty()); } { gsl::span sp_zero; EXPECT_TRUE(sp_zero.data() == nullptr); EXPECT_TRUE(sp_zero.size() == 0); EXPECT_TRUE(sp_zero.empty()); gsl::span sp_dyn_a(arr, 3); gsl::span sp_dyn_b(begin(arr), 3); EXPECT_TRUE(sp_dyn_a.data() == std::begin(arr)); EXPECT_TRUE(sp_dyn_b.data() == std::begin(arr)); EXPECT_TRUE(sp_dyn_a.size() == 3); EXPECT_TRUE(sp_dyn_b.size() == 3); gsl::span sp_three_a(arr, 3); gsl::span sp_three_b(begin(arr), 3); EXPECT_TRUE(sp_three_a.data() == std::begin(arr)); EXPECT_TRUE(sp_three_b.data() == std::begin(arr)); EXPECT_TRUE(sp_three_a.size() == 3); EXPECT_TRUE(sp_three_b.size() == 3); gsl::span sp_const_a(arr, 3); gsl::span sp_const_b(begin(arr), 3); EXPECT_TRUE(sp_const_a.data() == std::begin(arr)); EXPECT_TRUE(sp_const_b.data() == std::begin(arr)); EXPECT_TRUE(sp_const_a.size() == 3); EXPECT_TRUE(sp_const_b.size() == 3); #if __cplusplus >= 201703l gsl::span sp_const_c(std::as_const(arr), 3); EXPECT_TRUE(sp_const_c.data() == std::begin(arr)); EXPECT_TRUE(sp_const_c.size() == 3); #endif // __cplusplus >= 201703l gsl::span sp_const_d(cbegin(arr), 3); EXPECT_TRUE(sp_const_d.data() == std::begin(arr)); EXPECT_TRUE(sp_const_d.size() == 3); } { gsl::span sp_dyn_a(begin(arr), std::end(arr)); EXPECT_TRUE(sp_dyn_a.data() == std::begin(arr)); EXPECT_TRUE(sp_dyn_a.size() == 3); gsl::span sp_three_a(begin(arr), std::end(arr)); EXPECT_TRUE(sp_three_a.data() == std::begin(arr)); EXPECT_TRUE(sp_three_a.size() == 3); gsl::span sp_const_a(begin(arr), std::end(arr)); gsl::span sp_const_b(begin(arr), std::cend(arr)); gsl::span sp_const_c(cbegin(arr), std::end(arr)); gsl::span sp_const_d(cbegin(arr), std::cend(arr)); EXPECT_TRUE(sp_const_a.data() == std::begin(arr)); EXPECT_TRUE(sp_const_b.data() == std::begin(arr)); EXPECT_TRUE(sp_const_c.data() == std::begin(arr)); EXPECT_TRUE(sp_const_d.data() == std::begin(arr)); EXPECT_TRUE(sp_const_a.size() == 3); EXPECT_TRUE(sp_const_b.size() == 3); EXPECT_TRUE(sp_const_c.size() == 3); EXPECT_TRUE(sp_const_d.size() == 3); } { gsl::span sp_dyn_a(arr); gsl::span sp_dyn_b(stl); gsl::span sp_dyn_c{stl}; gsl::span sp_dyn_d{stl}; EXPECT_TRUE(sp_dyn_a.data() == std::begin(arr)); EXPECT_TRUE(sp_dyn_b.data() == stl.data()); EXPECT_TRUE(sp_dyn_a.size() == 3); EXPECT_TRUE(sp_dyn_b.size() == 3); gsl::span sp_three_a(arr); gsl::span sp_three_b(stl); EXPECT_TRUE(sp_three_a.data() == std::begin(arr)); EXPECT_TRUE(sp_three_b.data() == stl.data()); EXPECT_TRUE(sp_three_a.size() == 3); EXPECT_TRUE(sp_three_b.size() == 3); gsl::span sp_const_w(arr); gsl::span sp_const_y(stl); EXPECT_TRUE(sp_const_w.data() == std::begin(arr)); EXPECT_TRUE(sp_const_y.data() == stl.data()); EXPECT_TRUE(sp_const_w.size() == 3); EXPECT_TRUE(sp_const_y.size() == 3); #if __cplusplus >= 201703l gsl::span sp_const_x(std::as_const(arr)); EXPECT_TRUE(sp_const_x.data() == std::begin(arr)); EXPECT_TRUE(sp_const_x.size() == 3); gsl::span sp_const_z(std::as_const(stl)); EXPECT_TRUE(sp_const_z.data() == stl.data()); EXPECT_TRUE(sp_const_z.size() == 3); #endif // __cplusplus >= 201703l } { const gsl::span orig_dyn(arr); const gsl::span orig_three(arr); const gsl::span orig_const_dyn(arr); const gsl::span orig_const_three(arr); gsl::span sp_a(orig_dyn); gsl::span sp_b(orig_three); gsl::span sp_c(orig_three); gsl::span sp_d(orig_dyn); gsl::span sp_e(orig_three); gsl::span sp_f(orig_const_dyn); gsl::span sp_g(orig_const_three); gsl::span sp_h(orig_three); gsl::span sp_i(orig_const_three); EXPECT_TRUE(sp_a.data() == std::begin(arr)); EXPECT_TRUE(sp_b.data() == std::begin(arr)); EXPECT_TRUE(sp_c.data() == std::begin(arr)); EXPECT_TRUE(sp_d.data() == std::begin(arr)); EXPECT_TRUE(sp_e.data() == std::begin(arr)); EXPECT_TRUE(sp_f.data() == std::begin(arr)); EXPECT_TRUE(sp_g.data() == std::begin(arr)); EXPECT_TRUE(sp_h.data() == std::begin(arr)); EXPECT_TRUE(sp_i.data() == std::begin(arr)); EXPECT_TRUE(sp_a.size() == 3); EXPECT_TRUE(sp_b.size() == 3); EXPECT_TRUE(sp_c.size() == 3); EXPECT_TRUE(sp_d.size() == 3); EXPECT_TRUE(sp_e.size() == 3); EXPECT_TRUE(sp_f.size() == 3); EXPECT_TRUE(sp_g.size() == 3); EXPECT_TRUE(sp_h.size() == 3); EXPECT_TRUE(sp_i.size() == 3); } { gsl::span sp_dyn(arr); gsl::span sp_three(arr); gsl::span sp_const_dyn(arr); gsl::span sp_const_three(arr); EXPECT_TRUE(sp_dyn.data() == std::begin(arr)); EXPECT_TRUE(sp_three.data() == std::begin(arr)); EXPECT_TRUE(sp_const_dyn.data() == std::begin(arr)); EXPECT_TRUE(sp_const_three.data() == std::begin(arr)); EXPECT_TRUE(sp_dyn.size() == 3); EXPECT_TRUE(sp_three.size() == 3); EXPECT_TRUE(sp_const_dyn.size() == 3); EXPECT_TRUE(sp_const_three.size() == 3); int other[4]{12, 34, 56, 78}; sp_dyn = gsl::span{other}; sp_three = gsl::span{stl}; sp_const_dyn = gsl::span{other}; sp_const_three = gsl::span{stl}; EXPECT_TRUE(sp_dyn.data() == std::begin(other)); EXPECT_TRUE(sp_three.data() == stl.data()); EXPECT_TRUE(sp_const_dyn.data() == std::begin(other)); EXPECT_TRUE(sp_const_three.data() == stl.data()); EXPECT_TRUE(sp_dyn.size() == 4); EXPECT_TRUE(sp_three.size() == 3); EXPECT_TRUE(sp_const_dyn.size() == 4); EXPECT_TRUE(sp_const_three.size() == 3); } { gsl::span::iterator it_dyn{}; { gsl::span sp_dyn(arr); it_dyn = sp_dyn.begin(); } EXPECT_TRUE(*it_dyn == arr[0]); EXPECT_TRUE(it_dyn[2] == arr[2]); gsl::span::iterator it_three{}; { gsl::span sp_three(stl); it_three = sp_three.begin(); } EXPECT_TRUE(*it_three == stl[0]); EXPECT_TRUE(it_three[2] == stl[2]); } { int sequence[9]{10, 20, 30, 40, 50, 60, 70, 80, 90}; const gsl::span sp_dyn(sequence); const gsl::span sp_nine(sequence); auto first_3 = sp_dyn.first<3>(); auto first_4 = sp_nine.first<4>(); auto first_5 = sp_dyn.first(5); auto first_6 = sp_nine.first(6); static_assert(noexcept(sp_dyn.first<3>()), "noexcept(sp_dyn.first<3>())"); // strengthened static_assert(noexcept(sp_nine.first<4>()), "noexcept(sp_nine.first<4>())"); // strengthened static_assert(noexcept(sp_dyn.first(5)), "noexcept(sp_dyn.first(5))"); // strengthened static_assert(noexcept(sp_nine.first(6)), "noexcept(sp_nine.first(6))"); // strengthened static_assert(is_same>::value, "is_same>::value"); static_assert(is_same>::value, "is_same>::value"); static_assert(is_same>::value, "is_same>::value"); static_assert(is_same>::value, "is_same>::value"); EXPECT_TRUE(first_3.data() == std::begin(sequence)); EXPECT_TRUE(first_4.data() == std::begin(sequence)); EXPECT_TRUE(first_5.data() == std::begin(sequence)); EXPECT_TRUE(first_6.data() == std::begin(sequence)); EXPECT_TRUE(first_3.size() == 3); EXPECT_TRUE(first_4.size() == 4); EXPECT_TRUE(first_5.size() == 5); EXPECT_TRUE(first_6.size() == 6); auto last_3 = sp_dyn.last<3>(); auto last_4 = sp_nine.last<4>(); auto last_5 = sp_dyn.last(5); auto last_6 = sp_nine.last(6); static_assert(noexcept(sp_dyn.last<3>()), "noexcept(sp_dyn.last<3>())"); // strengthened static_assert(noexcept(sp_nine.last<4>()), "noexcept(sp_nine.last<4>())"); // strengthened static_assert(noexcept(sp_dyn.last(5)), "noexcept(sp_dyn.last(5))"); // strengthened static_assert(noexcept(sp_nine.last(6)), "noexcept(sp_nine.last(6))"); // strengthened static_assert(is_same>::value, "is_same>::value"); static_assert(is_same>::value, "is_same>::value"); static_assert(is_same>::value, "is_same>::value"); static_assert(is_same>::value, "is_same>::value"); EXPECT_TRUE(last_3.data() == std::begin(sequence) + 6); EXPECT_TRUE(last_4.data() == std::begin(sequence) + 5); EXPECT_TRUE(last_5.data() == std::begin(sequence) + 4); EXPECT_TRUE(last_6.data() == std::begin(sequence) + 3); EXPECT_TRUE(last_3.size() == 3); EXPECT_TRUE(last_4.size() == 4); EXPECT_TRUE(last_5.size() == 5); EXPECT_TRUE(last_6.size() == 6); auto offset_3 = sp_dyn.subspan<3>(); auto offset_4 = sp_nine.subspan<4>(); auto offset_5 = sp_dyn.subspan(5); auto offset_6 = sp_nine.subspan(6); static_assert(noexcept(sp_dyn.subspan<3>()), "noexcept(sp_dyn.subspan<3>())"); // strengthened static_assert(noexcept(sp_nine.subspan<4>()), "noexcept(sp_nine.subspan<4>())"); // strengthened static_assert(noexcept(sp_dyn.subspan(5)), "noexcept(sp_dyn.subspan(5))"); // strengthened static_assert(noexcept(sp_nine.subspan(6)), "noexcept(sp_nine.subspan(6))"); // strengthened static_assert(is_same>::value, "is_same>::value"); static_assert(is_same>::value, "is_same>::value"); static_assert(is_same>::value, "is_same>::value"); static_assert(is_same>::value, "is_same>::value"); EXPECT_TRUE(offset_3.data() == std::begin(sequence) + 3); EXPECT_TRUE(offset_4.data() == std::begin(sequence) + 4); EXPECT_TRUE(offset_5.data() == std::begin(sequence) + 5); EXPECT_TRUE(offset_6.data() == std::begin(sequence) + 6); EXPECT_TRUE(offset_3.size() == 6); EXPECT_TRUE(offset_4.size() == 5); EXPECT_TRUE(offset_5.size() == 4); EXPECT_TRUE(offset_6.size() == 3); auto subspan_3 = sp_dyn.subspan<3, 2>(); auto subspan_4 = sp_nine.subspan<4, 2>(); auto subspan_5 = sp_dyn.subspan(5, 2); auto subspan_6 = sp_nine.subspan(6, 2); static_assert(noexcept(sp_dyn.subspan<3, 2>()), "noexcept(sp_dyn.subspan<3, 2>())"); // strengthened static_assert(noexcept(sp_nine.subspan<4, 2>()), "noexcept(sp_nine.subspan<4, 2>())"); // strengthened static_assert(noexcept(sp_dyn.subspan(5, 2)), "noexcept(sp_dyn.subspan(5, 2))"); // strengthened static_assert(noexcept(sp_nine.subspan(6, 2)), "noexcept(sp_nine.subspan(6, 2))"); // strengthened static_assert(is_same>::value, "is_same>::value"); static_assert(is_same>::value, "is_same>::value"); static_assert(is_same>::value, "is_same>::value"); static_assert(is_same>::value, "is_same>::value"); EXPECT_TRUE(subspan_3.data() == std::begin(sequence) + 3); EXPECT_TRUE(subspan_4.data() == std::begin(sequence) + 4); EXPECT_TRUE(subspan_5.data() == std::begin(sequence) + 5); EXPECT_TRUE(subspan_6.data() == std::begin(sequence) + 6); EXPECT_TRUE(subspan_3.size() == 2); EXPECT_TRUE(subspan_4.size() == 2); EXPECT_TRUE(subspan_5.size() == 2); EXPECT_TRUE(subspan_6.size() == 2); static_assert(noexcept(sp_dyn.size()), "noexcept(sp_dyn.size())"); static_assert(noexcept(sp_dyn.size_bytes()), "noexcept(sp_dyn.size_bytes())"); static_assert(noexcept(sp_dyn.empty()), "noexcept(sp_dyn.empty())"); static_assert(noexcept(sp_dyn[0]), "noexcept(sp_dyn[0])"); // strengthened static_assert(noexcept(sp_dyn.front()), "noexcept(sp_dyn.front())"); // strengthened static_assert(noexcept(sp_dyn.back()), "noexcept(sp_dyn.back())"); // strengthened static_assert(noexcept(sp_dyn.data()), "noexcept(sp_dyn.data())"); static_assert(noexcept(sp_dyn.begin()), "noexcept(sp_dyn.begin())"); static_assert(noexcept(sp_dyn.end()), "noexcept(sp_dyn.end())"); static_assert(noexcept(sp_dyn.rbegin()), "noexcept(sp_dyn.rbegin())"); static_assert(noexcept(sp_dyn.rend()), "noexcept(sp_dyn.rend())"); static_assert(noexcept(sp_nine.size()), "noexcept(sp_nine.size())"); static_assert(noexcept(sp_nine.size_bytes()), "noexcept(sp_nine.size_bytes())"); static_assert(noexcept(sp_nine.empty()), "noexcept(sp_nine.empty())"); static_assert(noexcept(sp_nine[0]), "noexcept(sp_nine[0])"); // strengthened static_assert(noexcept(sp_nine.front()), "noexcept(sp_nine.front())"); // strengthened static_assert(noexcept(sp_nine.back()), "noexcept(sp_nine.back())"); // strengthened static_assert(noexcept(sp_nine.data()), "noexcept(sp_nine.data())"); static_assert(noexcept(sp_nine.begin()), "noexcept(sp_nine.begin())"); static_assert(noexcept(sp_nine.end()), "noexcept(sp_nine.end())"); static_assert(noexcept(sp_nine.rbegin()), "noexcept(sp_nine.rbegin())"); static_assert(noexcept(sp_nine.rend()), "noexcept(sp_nine.rend())"); EXPECT_TRUE(sp_dyn.size() == 9); EXPECT_TRUE(sp_nine.size() == 9); EXPECT_TRUE(sp_dyn.size_bytes() == 9 * sizeof(int)); EXPECT_TRUE(sp_nine.size_bytes() == 9 * sizeof(int)); EXPECT_TRUE(!sp_dyn.empty()); EXPECT_TRUE(!sp_nine.empty()); EXPECT_TRUE(sp_dyn[0] == 10); EXPECT_TRUE(sp_nine[0] == 10); EXPECT_TRUE(sp_dyn[8] == 90); EXPECT_TRUE(sp_nine[8] == 90); EXPECT_TRUE(sp_dyn.front() == 10); EXPECT_TRUE(sp_nine.front() == 10); EXPECT_TRUE(sp_dyn.back() == 90); EXPECT_TRUE(sp_nine.back() == 90); EXPECT_TRUE(&sp_dyn.front() == std::begin(sequence)); EXPECT_TRUE(&sp_nine.front() == std::begin(sequence)); EXPECT_TRUE(&sp_dyn[4] == std::begin(sequence) + 4); EXPECT_TRUE(&sp_nine[4] == std::begin(sequence) + 4); EXPECT_TRUE(&sp_dyn.back() == std::begin(sequence) + 8); EXPECT_TRUE(&sp_nine.back() == std::begin(sequence) + 8); EXPECT_TRUE(sp_dyn.data() == std::begin(sequence)); EXPECT_TRUE(sp_nine.data() == std::begin(sequence)); EXPECT_TRUE(*sp_dyn.begin() == 10); EXPECT_TRUE(*sp_nine.begin() == 10); EXPECT_TRUE(sp_dyn.end()[-2] == 80); EXPECT_TRUE(sp_nine.end()[-2] == 80); EXPECT_TRUE(*sp_dyn.rbegin() == 90); EXPECT_TRUE(*sp_nine.rbegin() == 90); EXPECT_TRUE(sp_dyn.rend()[-2] == 20); EXPECT_TRUE(sp_nine.rend()[-2] == 20); static_assert(is_same::iterator>::value, "is_same::iterator>::value"); static_assert(is_same::iterator>::value, "is_same::iterator>::value"); static_assert(is_same::iterator>::value, "is_same::iterator>::value"); static_assert(is_same::iterator>::value, "is_same::iterator>::value"); static_assert( is_same::reverse_iterator>::value, "is_same::reverse_iterator>::value"); static_assert( is_same::reverse_iterator>::value, "is_same::reverse_iterator>::value"); static_assert(is_same::reverse_iterator>::value, "is_same::reverse_iterator>::value"); static_assert( is_same::reverse_iterator>::value, "is_same::reverse_iterator>::value"); } { int sequence[9]{10, 20, 30, 40, 50, 60, 70, 80, 90}; constexpr size_t SizeBytes = sizeof(sequence); const gsl::span sp_dyn(sequence); const gsl::span sp_nine(sequence); const gsl::span sp_const_dyn(sequence); const gsl::span sp_const_nine(sequence); static_assert(noexcept(as_bytes(sp_dyn)), "noexcept(as_bytes(sp_dyn))"); static_assert(noexcept(as_bytes(sp_nine)), "noexcept(as_bytes(sp_nine))"); static_assert(noexcept(as_bytes(sp_const_dyn)), "noexcept(as_bytes(sp_const_dyn))"); static_assert(noexcept(as_bytes(sp_const_nine)), "noexcept(as_bytes(sp_const_nine))"); static_assert(noexcept(as_writable_bytes(sp_dyn)), "noexcept(as_writable_bytes(sp_dyn))"); static_assert(noexcept(as_writable_bytes(sp_nine)), "noexcept(as_writable_bytes(sp_nine))"); auto sp_1 = as_bytes(sp_dyn); auto sp_2 = as_bytes(sp_nine); auto sp_3 = as_bytes(sp_const_dyn); auto sp_4 = as_bytes(sp_const_nine); auto sp_5 = as_writable_bytes(sp_dyn); auto sp_6 = as_writable_bytes(sp_nine); static_assert(is_same>::value, "is_same>::value"); static_assert(is_same>::value, "is_same>::value"); static_assert(is_same>::value, "is_same>::value"); static_assert(is_same>::value, "is_same>::value"); static_assert(is_same>::value, "is_same>::value"); static_assert(is_same>::value, "is_same>::value"); EXPECT_TRUE(sp_1.data() == reinterpret_cast(begin(sequence))); EXPECT_TRUE(sp_2.data() == reinterpret_cast(begin(sequence))); EXPECT_TRUE(sp_3.data() == reinterpret_cast(begin(sequence))); EXPECT_TRUE(sp_4.data() == reinterpret_cast(begin(sequence))); EXPECT_TRUE(sp_5.data() == reinterpret_cast(begin(sequence))); EXPECT_TRUE(sp_6.data() == reinterpret_cast(begin(sequence))); EXPECT_TRUE(sp_1.size() == SizeBytes); EXPECT_TRUE(sp_2.size() == SizeBytes); EXPECT_TRUE(sp_3.size() == SizeBytes); EXPECT_TRUE(sp_4.size() == SizeBytes); EXPECT_TRUE(sp_5.size() == SizeBytes); EXPECT_TRUE(sp_6.size() == SizeBytes); } } // assertions for span's definition static_assert(std::is_same::value, "gsl::dynamic_extent must be represented as std::size_t"); static_assert(gsl::dynamic_extent == static_cast(-1), "gsl::dynamic_extent must be defined as the max value of std::size_t"); static_assert(std::is_same::extent), const std::size_t>::value, "Ensure that the type of gsl::span::extent is std::size_t"); static_assert(gsl::span::extent == gsl::dynamic_extent, "gsl::span::extent should be equivalent to gsl::dynamic_extent"); static_assert(std::is_same::extent), const std::size_t>::value, "Ensure that the type of gsl::span::extent is std::size_t"); static_assert(gsl::span::extent == 3, "Ensure that span::extent is equal to 3"); static_assert(std::is_same::element_type, int>::value, "span::element_type should be int"); static_assert(std::is_same::value_type, int>::value, "span::value_type should be int"); static_assert(std::is_same::size_type, std::size_t>::value, "span::size_type should be std::size_t"); static_assert(std::is_same::difference_type, ptrdiff_t>::value, "span::difference_type should be std::ptrdiff_t"); static_assert(std::is_same::pointer, int*>::value, "span::pointer should be int*"); static_assert(std::is_same::const_pointer, const int*>::value, "span::const_pointer should be const int*"); static_assert(std::is_same::reference, int&>::value, "span::reference should be int&"); static_assert(std::is_same::const_reference, const int&>::value, "span::const_reference should be const int&"); static_assert(std::is_same::element_type, int>::value, "span::element_type should be int"); static_assert(std::is_same::value_type, int>::value, "span::value_type should be int"); static_assert(std::is_same::size_type, std::size_t>::value, "span::size_type should be std::size_t"); static_assert(std::is_same::difference_type, ptrdiff_t>::value, "span::difference_type should be std::ptrdiff_t"); static_assert(std::is_same::pointer, int*>::value, "span::pointer should be int*"); static_assert(std::is_same::const_pointer, const int*>::value, "span::const_pointer should be const int*"); static_assert(std::is_same::reference, int&>::value, "span::reference should be int&"); static_assert(std::is_same::const_reference, const int&>::value, "span::const_reference should be const int&"); static_assert(std::is_same::element_type, const int>::value, "span::element_type should be const int"); static_assert(std::is_same::value_type, int>::value, "span::value_type should be int"); static_assert(std::is_same::size_type, std::size_t>::value, "span::size_type should be size_t"); static_assert(std::is_same::difference_type, ptrdiff_t>::value, "span::difference_type should be ptrdiff_t"); static_assert(std::is_same::pointer, const int*>::value, "span::pointer should be const int*"); static_assert(std::is_same::const_pointer, const int*>::value, "span::const_pointer should be const int*"); static_assert(std::is_same::reference, const int&>::value, "span::reference should be const int&"); static_assert(std::is_same::const_reference, const int&>::value, "span::const_reference should be const int&"); static_assert(std::is_same::element_type, const int>::value, "span::element_type should be const int"); static_assert(std::is_same::value_type, int>::value, "span::value_type should be int"); static_assert(std::is_same::size_type, std::size_t>::value, "span::size_type should be size_t"); static_assert(std::is_same::difference_type, ptrdiff_t>::value, "span::difference_type should be ptrdiff_t"); static_assert(std::is_same::pointer, const int*>::value, "span::pointer should be const int*"); static_assert(std::is_same::const_pointer, const int*>::value, "span::const_pointer should be const int*"); static_assert(std::is_same::reference, const int&>::value, "span::reference should be const int&"); static_assert(std::is_same::const_reference, const int&>::value, "span::const_reference should be const int&"); // assertions for span_iterator static_assert(std::is_same::iterator>::pointer, int*>::value, "span::iterator's pointer should be int*"); static_assert( std::is_same::reverse_iterator, std::reverse_iterator::iterator>>::value, "span::reverse_iterator should equal std::reverse_iterator::iterator>"); static_assert(std::is_same::iterator>::pointer, int*>::value, "span::iterator's pointer should be int*"); static_assert( std::is_same::reverse_iterator, std::reverse_iterator::iterator>>::value, "span::reverse_iterator should equal std::reverse_iterator::iterator>"); static_assert( std::is_same::iterator>::pointer, const int*>::value, "span::iterator's pointer should be int*"); static_assert(std::is_same::reverse_iterator, std::reverse_iterator::iterator>>::value, "span::reverse_iterator should equal std::reverse_iterator::iterator>"); static_assert(std::is_same::iterator>::pointer, const int*>::value, "span::iterator's pointer should be int*"); static_assert(std::is_same::reverse_iterator, std::reverse_iterator::iterator>>::value, "span::reverse_iterator should equal std::reverse_iterator::iterator>"); // copyability assertions static_assert(std::is_trivially_copyable>::value, "span should be trivially copyable"); static_assert(std::is_trivially_copyable::iterator>::value, "span::iterator should be trivially copyable"); static_assert(std::is_trivially_copyable>::value, "span should be trivially copyable"); static_assert(std::is_trivially_copyable::iterator>::value, "span::iterator should be trivially copyable"); static_assert(std::is_trivially_copyable>::value, "span should be trivially copyable"); static_assert(std::is_trivially_copyable::iterator>::value, "span::iterator should be trivially copyable"); static_assert(std::is_trivially_copyable>::value, "span should be trivially copyable"); static_assert(std::is_trivially_copyable::iterator>::value, "span::iterator should be trivially copyable"); // nothrow constructible assertions static_assert(std::is_nothrow_constructible, int*, std::size_t>::value, "std::is_nothrow_constructible, int*, std::size_t>"); static_assert(std::is_nothrow_constructible, int*, std::uint16_t>::value, "std::is_nothrow_constructible, int*, std::uint16_t>"); static_assert(std::is_nothrow_constructible, int*, int*>::value, "std::is_nothrow_constructible, int*, int*>"); static_assert(std::is_nothrow_constructible, int (&)[3]>::value, "std::is_nothrow_constructible, int(&)[3]>"); static_assert(std::is_nothrow_constructible, const gsl::span&>::value, "std::is_nothrow_constructible, const gsl::span&>"); static_assert(std::is_nothrow_constructible, const gsl::span&>::value, "std::is_nothrow_constructible, const gsl::span&>"); static_assert(std::is_nothrow_constructible, const gsl::span&>::value, "std::is_nothrow_constructible, const gsl::span&>"); static_assert(std::is_nothrow_constructible, std::array&>::value, "std::is_nothrow_constructible, std::array&>"); static_assert(std::is_nothrow_constructible, int*, std::size_t>::value, "std::is_nothrow_constructible, int*, std::size_t>"); static_assert(std::is_nothrow_constructible, int*, std::uint16_t>::value, "std::is_nothrow_constructible, int*, std::uint16_t>"); static_assert(std::is_nothrow_constructible, int*, int*>::value, "std::is_nothrow_constructible, int*, int*>"); static_assert(std::is_nothrow_constructible, int (&)[3]>::value, "std::is_nothrow_constructible, int(&)[3]>"); static_assert(std::is_nothrow_constructible, const gsl::span&>::value, "std::is_nothrow_constructible, const gsl::span&>"); static_assert(std::is_nothrow_constructible, std::array&>::value, "std::is_nothrow_constructible, std::array&>"); static_assert(std::is_nothrow_constructible, int*, std::size_t>::value, "std::is_nothrow_constructible, int*, std::size_t>"); static_assert(std::is_nothrow_constructible, int*, int*>::value, "std::is_nothrow_constructible, int*, int*>"); static_assert(std::is_nothrow_constructible, int*, const int*>::value, "std::is_nothrow_constructible, int*, const int*>"); static_assert(std::is_nothrow_constructible, int (&)[3]>::value, "std::is_nothrow_constructible, int(&)[3]>"); static_assert(std::is_nothrow_constructible, const int*, int*>::value, "std::is_nothrow_constructible, const int*, int*>"); static_assert(std::is_nothrow_constructible, const int*, const int*>::value, "std::is_nothrow_constructible, const int*, const int*>"); static_assert(std::is_nothrow_constructible, const int*, std::size_t>::value, "std::is_nothrow_constructible, const int*, std::size_t>"); static_assert(std::is_nothrow_constructible, const int (&)[3]>::value, "std::is_nothrow_constructible, const int(&)[3]>"); static_assert(std::is_nothrow_constructible, const gsl::span&>::value, "std::is_nothrow_constructible, const gsl::span&>"); static_assert(std::is_nothrow_constructible, const gsl::span&>::value, "std::is_nothrow_constructible, const gsl::span&>"); static_assert( std::is_nothrow_constructible, const gsl::span&>::value, "std::is_nothrow_constructible, const gsl::span&>"); static_assert( std::is_nothrow_constructible, const gsl::span&>::value, "std::is_nothrow_constructible, const gsl::span&>"); static_assert( std::is_nothrow_constructible, const gsl::span&>::value, "std::is_nothrow_constructible, const gsl::span&>"); static_assert( std::is_nothrow_constructible, const gsl::span&>::value, "std::is_nothrow_constructible, const gsl::span&>"); static_assert(std::is_nothrow_constructible, std::array&>::value, "std::is_nothrow_constructible, std::array&>"); static_assert(std::is_nothrow_constructible, const std::array&>::value, "std::is_nothrow_constructible, const std::array&>"); static_assert( std::is_nothrow_constructible, const gsl::span&>::value, "std::is_nothrow_constructible, const gsl::span&>"); static_assert( std::is_nothrow_constructible, const gsl::span&>::value, "std::is_nothrow_constructible, const gsl::span&>"); static_assert(std::is_nothrow_constructible, Base (&)[3]>::value, "std::is_nothrow_constructible, Base(&)[3]>"); static_assert(std::is_nothrow_constructible, const gsl::span&>::value, "std::is_nothrow_constructible, const gsl::span&>"); static_assert(std::is_nothrow_constructible, const gsl::span&>::value, "std::is_nothrow_constructible, const gsl::span&>"); static_assert(std::is_nothrow_constructible, std::array&>::value, "std::is_nothrow_constructible, std::array&>"); static_assert(std::is_nothrow_constructible, Base (&)[3]>::value, "std::is_nothrow_constructible, Base(&)[3]>"); static_assert(std::is_nothrow_constructible, const gsl::span&>::value, "std::is_nothrow_constructible, const gsl::span&>"); static_assert(std::is_nothrow_constructible, std::array&>::value, "std::is_nothrow_constructible, std::array&>"); static_assert(std::is_nothrow_constructible, Base (&)[3]>::value, "std::is_nothrow_constructible, Base(&)[3]>"); static_assert(std::is_nothrow_constructible, const Base (&)[3]>::value, "std::is_nothrow_constructible, const Base(&)[3]>"); static_assert(std::is_nothrow_constructible, const gsl::span&>::value, "std::is_nothrow_constructible, const gsl::span&>"); static_assert( std::is_nothrow_constructible, const gsl::span&>::value, "std::is_nothrow_constructible, const gsl::span&>"); static_assert( std::is_nothrow_constructible, const gsl::span&>::value, "std::is_nothrow_constructible, const gsl::span&>"); static_assert( std::is_nothrow_constructible, const gsl::span&>::value, "std::is_nothrow_constructible, const gsl::span&>"); static_assert(std::is_nothrow_constructible, std::array&>::value, "std::is_nothrow_constructible, std::array&>"); static_assert( std::is_nothrow_constructible, const std::array&>::value, "std::is_nothrow_constructible, const std::array&>"); static_assert( std::is_nothrow_constructible, const gsl::span&>::value, "std::is_nothrow_constructible, const gsl::span&>"); static_assert( std::is_nothrow_constructible, const gsl::span&>::value, "std::is_nothrow_constructible, const gsl::span&>"); // non-constructible assertions static_assert(!std::is_constructible, const int*, int*>::value, "!std::is_constructible, const int*, int*>"); static_assert(!std::is_constructible, const int*, const int*>::value, "!std::is_constructible, const int*, const int*>"); static_assert(!std::is_constructible, const int*, double*>::value, "!std::is_constructible, const int*, double*>"); static_assert(!std::is_constructible, const int*, std::size_t>::value, "!std::is_constructible, const int*, std::size_t>"); static_assert(!std::is_constructible, const int (&)[3]>::value, "!std::is_constructible, const int(&)[3]>"); static_assert(!std::is_constructible, double*, int*>::value, "!std::is_constructible, double*, int*>"); static_assert(!std::is_constructible, double*, const int*>::value, "!std::is_constructible, double*, const int*>"); static_assert(!std::is_constructible, double*, double*>::value, "!std::is_constructible, double*, double*>"); static_assert(!std::is_constructible, double*, std::size_t>::value, "!std::is_constructible, double*, std::size_t>"); static_assert(!std::is_constructible, double (&)[3]>::value, "!std::is_constructible, double(&)[3]>"); static_assert(!std::is_constructible, int*, double*>::value, "!std::is_constructible, int*, double*>"); static_assert(!std::is_constructible, std::size_t, int*>::value, "!std::is_constructible, std::size_t, int*>"); static_assert(!std::is_constructible, std::size_t, std::size_t>::value, "!std::is_constructible, std::size_t, std::size_t>"); static_assert(!std::is_constructible, const gsl::span&>::value, "!std::is_constructible, const gsl::span&>"); static_assert(!std::is_constructible, const gsl::span&>::value, "!std::is_constructible, const gsl::span&>"); static_assert(!std::is_constructible, const gsl::span&>::value, "!std::is_constructible, const gsl::span&>"); static_assert(!std::is_constructible, const gsl::span&>::value, "!std::is_constructible, const gsl::span&>"); static_assert(!std::is_constructible, std::array&>::value, "!std::is_constructible, std::array&>"); static_assert(!std::is_constructible, const std::array&>::value, "!std::is_constructible, const std::array&>"); static_assert(!std::is_constructible, int*, double*>::value, "!std::is_constructible, int*, double*>"); static_assert(!std::is_constructible, int (&)[500]>::value, "!std::is_constructible, int(&)[500]>"); static_assert(!std::is_constructible, const int*, int*>::value, "!std::is_constructible, const int*, int*>"); static_assert(!std::is_constructible, const int*, const int*>::value, "!std::is_constructible, const int*, const int*>"); static_assert(!std::is_constructible, const int*, std::size_t>::value, "!std::is_constructible, const int*, std::size_t>"); static_assert(!std::is_constructible, const int*, double*>::value, "!std::is_constructible, const int*, double*>"); static_assert(!std::is_constructible, const int (&)[3]>::value, "!std::is_constructible, const int(&)[3]>"); static_assert(!std::is_constructible, double*, std::size_t>::value, "!std::is_constructible, double*, std::size_t>"); static_assert(!std::is_constructible, double*, int*>::value, "!std::is_constructible, double*, int*>"); static_assert(!std::is_constructible, double*, const int*>::value, "!std::is_constructible, double*, const int*>"); static_assert(!std::is_constructible, double*, double*>::value, "!std::is_constructible, double*, double*>"); static_assert(!std::is_constructible, double (&)[3]>::value, "!std::is_constructible, double(&)[3]>"); static_assert(!std::is_constructible, std::size_t, int*>::value, "!std::is_constructible, std::size_t, int*>"); static_assert(!std::is_constructible, std::size_t, std::size_t>::value, "!std::is_constructible, std::size_t, std::size_t>"); static_assert(!std::is_constructible, std::array&>::value, "!std::is_constructible, std::array&>"); static_assert(!std::is_constructible, std::array&>::value, "!std::is_constructible, std::array&>"); static_assert(!std::is_constructible, const std::array&>::value, "!std::is_constructible, const std::array&>"); static_assert(!std::is_constructible, const gsl::span&>::value, "!std::is_constructible, const gsl::span&>"); static_assert(!std::is_constructible, const gsl::span&>::value, "!std::is_constructible, const gsl::span&>"); static_assert(!std::is_constructible, const gsl::span&>::value, "!std::is_constructible, const gsl::span&>"); static_assert(!std::is_constructible, const gsl::span&>::value, "!std::is_constructible, const gsl::span&>"); static_assert(!std::is_constructible, const gsl::span&>::value, "!std::is_constructible, const gsl::span&>"); static_assert(!std::is_constructible, double (&)[3]>::value, "!std::is_constructible, double(&)[3]>"); static_assert(!std::is_constructible, std::array&>::value, "!std::is_constructible, std::array&>"); static_assert(!std::is_constructible, const gsl::span&>::value, "!std::is_constructible, const gsl::span&>"); static_assert(!std::is_constructible, const gsl::span&>::value, "!std::is_constructible, const gsl::span&>"); static_assert( !std::is_constructible, const gsl::span&>::value, "!std::is_constructible, const gsl::span&>"); static_assert(!std::is_constructible, const gsl::span&>::value, "!std::is_constructible, const gsl::span&>"); static_assert(!std::is_constructible, Derived (&)[3]>::value, "!std::is_constructible, Derived(&)[3]>"); static_assert(!std::is_constructible, std::array&>::value, "!std::is_constructible, std::array&>"); static_assert(!std::is_constructible, std::vector&>::value, "!std::is_constructible, std::vector&>"); static_assert(!std::is_constructible, const gsl::span&>::value, "!std::is_constructible, const gsl::span&>"); static_assert(!std::is_constructible, const gsl::span&>::value, "!std::is_constructible, const gsl::span&>"); static_assert(!std::is_constructible, const gsl::span&>::value, "!std::is_constructible, const gsl::span&>"); static_assert(!std::is_constructible, Derived (&)[3]>::value, "!std::is_constructible, Derived(&)[3]>"); static_assert(!std::is_constructible, std::array&>::value, "!std::is_constructible, std::array&>"); static_assert(!std::is_constructible, Derived (&)[3]>::value, "!std::is_constructible, Derived(&)[3]>"); static_assert(!std::is_constructible, const Derived (&)[3]>::value, "!std::is_constructible, const Derived(&)[3]>"); static_assert(!std::is_constructible, std::array&>::value, "!std::is_constructible, std::array&>"); static_assert(!std::is_constructible, const std::array&>::value, "!std::is_constructible, const std::array&>"); static_assert(!std::is_constructible, const gsl::span&>::value, "!std::is_constructible, const gsl::span&>"); static_assert(!std::is_constructible, const gsl::span&>::value, "!std::is_constructible, const gsl::span&>"); static_assert(!std::is_constructible, const gsl::span&>::value, "!std::is_constructible, const gsl::span&>"); static_assert( !std::is_constructible, const gsl::span&>::value, "!std::is_constructible, const gsl::span&>"); static_assert(!std::is_constructible, const gsl::span&>::value, "!std::is_constructible, const gsl::span&>"); static_assert( !std::is_constructible, const gsl::span&>::value, "!std::is_constructible, const gsl::span&>"); static_assert(!std::is_constructible, std::array&>::value, "!std::is_constructible, std::array&>"); static_assert(!std::is_constructible, const std::array&>::value, "!std::is_constructible, const std::array&>"); // Explicit construction enabled in P1976R2 static_assert(std::is_constructible, const gsl::span&>::value, "std::is_constructible, const gsl::span&>"); static_assert(std::is_constructible, const gsl::span&>::value, "std::is_constructible, const gsl::span&>"); static_assert(std::is_constructible, const gsl::span&>::value, "std::is_constructible, const gsl::span&>"); // no throw copy constructor static_assert(std::is_nothrow_copy_constructible>::value, "std::is_nothrow_copy_constructible>"); static_assert(std::is_nothrow_copy_constructible>::value, "std::is_nothrow_copy_constructible>"); static_assert(std::is_nothrow_copy_constructible>::value, "std::is_nothrow_copy_constructible>"); static_assert(std::is_nothrow_copy_constructible>::value, "std::is_nothrow_copy_constructible>"); // no throw copy assignment static_assert(std::is_nothrow_copy_assignable>::value, "std::is_nothrow_copy_assignable>"); static_assert(std::is_nothrow_copy_assignable>::value, "std::is_nothrow_copy_assignable>"); static_assert(std::is_nothrow_copy_assignable>::value, "std::is_nothrow_copy_assignable>"); static_assert(std::is_nothrow_copy_assignable>::value, "std::is_nothrow_copy_assignable>"); // no throw destruction static_assert(std::is_nothrow_destructible>::value, "std::is_nothrow_destructible>"); static_assert(std::is_nothrow_destructible>::value, "std::is_nothrow_destructible>"); static_assert(std::is_nothrow_destructible>::value, "std::is_nothrow_destructible>"); // conversions static_assert(std::is_convertible>::value, "std::is_convertible>"); static_assert(std::is_convertible>::value, "std::is_convertible>"); static_assert(std::is_convertible>::value, "std::is_convertible>"); static_assert(std::is_convertible>::value, "std::is_convertible>"); static_assert(std::is_convertible&, gsl::span>::value, "std::is_convertible&, gsl::span>"); static_assert(std::is_convertible&, gsl::span>::value, "std::is_convertible&, gsl::span>"); static_assert(std::is_convertible&, gsl::span>::value, "std::is_convertible&, gsl::span>"); static_assert(std::is_convertible&, gsl::span>::value, "std::is_convertible&, gsl::span>"); static_assert(std::is_convertible&, gsl::span>::value, "std::is_convertible&, gsl::span>"); static_assert(std::is_convertible&, gsl::span>::value, "std::is_convertible&, gsl::span>"); static_assert(std::is_convertible&, gsl::span>::value, "std::is_convertible&, gsl::span>"); static_assert(std::is_convertible&, gsl::span>::value, "std::is_convertible&, gsl::span>"); static_assert(std::is_convertible&, gsl::span>::value, "std::is_convertible&, gsl::span>"); static_assert(std::is_convertible&, gsl::span>::value, "std::is_convertible&, gsl::span>"); static_assert(std::is_convertible&, gsl::span>::value, "std::is_convertible&, gsl::span>"); static_assert(std::is_convertible&, gsl::span>::value, "std::is_convertible&, gsl::span>"); static_assert(std::is_convertible&, gsl::span>::value, "std::is_convertible&, gsl::span>"); static_assert(std::is_convertible&, gsl::span>::value, "std::is_convertible&, gsl::span>"); static_assert(std::is_convertible&, gsl::span>::value, "std::is_convertible&, gsl::span>"); static_assert(std::is_convertible&, gsl::span>::value, "std::is_convertible&, gsl::span>"); #if __cplusplus >= 201703l using std::void_t; #else // __cplusplus >= 201703l template using void_t = void; #endif // __cplusplus < 201703l template static constexpr bool AsWritableBytesCompilesFor = false; template static constexpr bool AsWritableBytesCompilesFor()))>> = true; static_assert(AsWritableBytesCompilesFor>, "AsWritableBytesCompilesFor>"); static_assert(AsWritableBytesCompilesFor>, "AsWritableBytesCompilesFor>"); static_assert(!AsWritableBytesCompilesFor>, "!AsWritableBytesCompilesFor>"); static_assert(!AsWritableBytesCompilesFor>, "!AsWritableBytesCompilesFor>"); GSL-4.2.1/tests/span_ext_tests.cpp000066400000000000000000000253741511561312500170670ustar00rootroot00000000000000/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// #include #include // for span and span_ext #include // for narrow_cast, at #include // for array #include // for terminate #include // for cerr #include // for vector using namespace std; using namespace gsl; #include "deathTestCommon.h" TEST(span_ext_test, make_span_from_pointer_length_constructor) { const auto terminateHandler = std::set_terminate([] { std::cerr << "Expected Death. from_pointer_length_constructor"; std::abort(); }); const auto expected = GetExpectedDeathString(terminateHandler); int arr[4] = {1, 2, 3, 4}; { auto s = make_span(&arr[0], 2); EXPECT_TRUE(s.size() == 2); EXPECT_TRUE(s.data() == &arr[0]); EXPECT_TRUE(s[0] == 1); EXPECT_TRUE(s[1] == 2); } { int* p = nullptr; auto s = make_span(p, narrow_cast::size_type>(0)); EXPECT_TRUE(s.size() == 0); EXPECT_TRUE(s.data() == nullptr); } { int* p = nullptr; auto workaround_macro = [=]() { make_span(p, 2); }; EXPECT_DEATH(workaround_macro(), expected); } } TEST(span_ext_test, make_span_from_pointer_pointer_construction) { int arr[4] = {1, 2, 3, 4}; { auto s = make_span(&arr[0], &arr[2]); EXPECT_TRUE(s.size() == 2); EXPECT_TRUE(s.data() == &arr[0]); EXPECT_TRUE(s[0] == 1); EXPECT_TRUE(s[1] == 2); } { auto s = make_span(&arr[0], &arr[0]); EXPECT_TRUE(s.size() == 0); EXPECT_TRUE(s.data() == &arr[0]); } { int* p = nullptr; auto s = make_span(p, p); EXPECT_TRUE(s.size() == 0); EXPECT_TRUE(s.data() == nullptr); } } TEST(span_ext_test, make_span_from_array_constructor) { int arr[5] = {1, 2, 3, 4, 5}; int arr2d[2][3] = {1, 2, 3, 4, 5, 6}; int arr3d[2][3][2] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; { const auto s = make_span(arr); EXPECT_TRUE(s.size() == 5); EXPECT_TRUE(s.data() == std::addressof(arr[0])); } { const auto s = make_span(std::addressof(arr2d[0]), 1); EXPECT_TRUE(s.size() == 1); EXPECT_TRUE(s.data() == std::addressof(arr2d[0])); } { const auto s = make_span(std::addressof(arr3d[0]), 1); EXPECT_TRUE(s.size() == 1); EXPECT_TRUE(s.data() == std::addressof(arr3d[0])); } } TEST(span_ext_test, make_span_from_dynamic_array_constructor) { double(*arr)[3][4] = new double[100][3][4]; { auto s = make_span(&arr[0][0][0], 10); EXPECT_TRUE(s.size() == 10); EXPECT_TRUE(s.data() == &arr[0][0][0]); } delete[] arr; } TEST(span_ext_test, make_span_from_std_array_constructor) { std::array arr = {1, 2, 3, 4}; { auto s = make_span(arr); EXPECT_TRUE(s.size() == arr.size()); EXPECT_TRUE(s.data() == arr.data()); } // This test checks for the bug found in gcc 6.1, 6.2, 6.3, 6.4, 6.5 7.1, 7.2, 7.3 - issue #590 { gsl::span s1 = make_span(arr); static gsl::span s2; s2 = s1; #if defined(__GNUC__) && __GNUC__ == 6 && (__GNUC_MINOR__ == 4 || __GNUC_MINOR__ == 5) && \ __GNUC_PATCHLEVEL__ == 0 && defined(__OPTIMIZE__) // Known to be broken in gcc 6.4 and 6.5 with optimizations // Issue in gcc: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=83116 EXPECT_TRUE(s1.size() == 4); EXPECT_TRUE(s2.size() == 0); #else EXPECT_TRUE(s1.size() == s2.size()); #endif } } TEST(span_ext_test, make_span_from_const_std_array_constructor) { const std::array arr = {1, 2, 3, 4}; { auto s = make_span(arr); EXPECT_TRUE(s.size() == arr.size()); EXPECT_TRUE(s.data() == arr.data()); } } TEST(span_ext_test, make_span_from_std_array_const_constructor) { std::array arr = {1, 2, 3, 4}; { auto s = make_span(arr); EXPECT_TRUE(s.size() == arr.size()); EXPECT_TRUE(s.data() == arr.data()); } } TEST(span_ext_test, make_span_from_container_constructor) { std::vector v = {1, 2, 3}; const std::vector cv = v; { auto s = make_span(v); EXPECT_TRUE(s.size() == v.size()); EXPECT_TRUE(s.data() == v.data()); auto cs = make_span(cv); EXPECT_TRUE(cs.size() == cv.size()); EXPECT_TRUE(cs.data() == cv.data()); } } TEST(span_test, interop_with_gsl_at) { std::vector vec{1, 2, 3, 4, 5}; gsl::span sp{vec}; std::vector cvec{1, 2, 3, 4, 5}; gsl::span csp{cvec}; for (gsl::index i = 0; i < gsl::narrow_cast(vec.size()); ++i) { EXPECT_TRUE(&gsl::at(sp, i) == &vec[gsl::narrow_cast(i)]); EXPECT_TRUE(&gsl::at(csp, i) == &cvec[gsl::narrow_cast(i)]); } const auto terminateHandler = std::set_terminate([] { std::cerr << "Expected Death. interop_with_gsl_at"; std::abort(); }); const auto expected = GetExpectedDeathString(terminateHandler); EXPECT_DEATH(gsl::at(sp, -1), expected); EXPECT_DEATH(gsl::at(sp, gsl::narrow_cast(sp.size())), expected); EXPECT_DEATH(gsl::at(csp, -1), expected); EXPECT_DEATH(gsl::at(csp, gsl::narrow_cast(sp.size())), expected); } TEST(span_ext_test, iterator_free_functions) { int a[] = {1, 2, 3, 4}; gsl::span s{a}; EXPECT_TRUE((std::is_same::value)); EXPECT_TRUE((std::is_same::value)); EXPECT_TRUE((std::is_same::value)); EXPECT_TRUE((std::is_same::value)); EXPECT_TRUE((std::is_same::value)); EXPECT_TRUE((std::is_same::value)); EXPECT_TRUE((std::is_same::value)); EXPECT_TRUE((std::is_same::value)); EXPECT_TRUE(s.begin() == begin(s)); EXPECT_TRUE(s.end() == end(s)); EXPECT_TRUE(s.rbegin() == rbegin(s)); EXPECT_TRUE(s.rend() == rend(s)); EXPECT_TRUE(s.begin() == cbegin(s)); EXPECT_TRUE(s.end() == cend(s)); EXPECT_TRUE(s.rbegin() == crbegin(s)); EXPECT_TRUE(s.rend() == crend(s)); } TEST(span_ext_test, ssize_free_function) { int a[] = {1, 2, 3, 4}; gsl::span s{a}; EXPECT_FALSE((std::is_same::value)); EXPECT_TRUE(s.size() == static_cast(ssize(s))); } #ifndef GSL_KERNEL_MODE TEST(span_ext_test, comparison_operators) { { gsl::span s1; gsl::span s2; EXPECT_TRUE(s1 == s2); EXPECT_FALSE(s1 != s2); EXPECT_FALSE(s1 < s2); EXPECT_TRUE(s1 <= s2); EXPECT_FALSE(s1 > s2); EXPECT_TRUE(s1 >= s2); EXPECT_TRUE(s2 == s1); EXPECT_FALSE(s2 != s1); EXPECT_FALSE(s2 != s1); EXPECT_TRUE(s2 <= s1); EXPECT_FALSE(s2 > s1); EXPECT_TRUE(s2 >= s1); } { int arr[] = {2, 1}; gsl::span s1 = arr; gsl::span s2 = arr; EXPECT_TRUE(s1 == s2); EXPECT_FALSE(s1 != s2); EXPECT_FALSE(s1 < s2); EXPECT_TRUE(s1 <= s2); EXPECT_FALSE(s1 > s2); EXPECT_TRUE(s1 >= s2); EXPECT_TRUE(s2 == s1); EXPECT_FALSE(s2 != s1); EXPECT_FALSE(s2 < s1); EXPECT_TRUE(s2 <= s1); EXPECT_FALSE(s2 > s1); EXPECT_TRUE(s2 >= s1); } { int arr[] = {2, 1}; // bigger gsl::span s1; gsl::span s2 = arr; EXPECT_TRUE(s1 != s2); EXPECT_TRUE(s2 != s1); EXPECT_FALSE(s1 == s2); EXPECT_FALSE(s2 == s1); EXPECT_TRUE(s1 < s2); EXPECT_FALSE(s2 < s1); EXPECT_TRUE(s1 <= s2); EXPECT_FALSE(s2 <= s1); EXPECT_TRUE(s2 > s1); EXPECT_FALSE(s1 > s2); EXPECT_TRUE(s2 >= s1); EXPECT_FALSE(s1 >= s2); } { int arr1[] = {1, 2}; int arr2[] = {1, 2}; gsl::span s1 = arr1; gsl::span s2 = arr2; EXPECT_TRUE(s1 == s2); EXPECT_FALSE(s1 != s2); EXPECT_FALSE(s1 < s2); EXPECT_TRUE(s1 <= s2); EXPECT_FALSE(s1 > s2); EXPECT_TRUE(s1 >= s2); EXPECT_TRUE(s2 == s1); EXPECT_FALSE(s2 != s1); EXPECT_FALSE(s2 < s1); EXPECT_TRUE(s2 <= s1); EXPECT_FALSE(s2 > s1); EXPECT_TRUE(s2 >= s1); } { int arr[] = {1, 2, 3}; gsl::span s1 = {&arr[0], 2}; // shorter gsl::span s2 = arr; // longer EXPECT_TRUE(s1 != s2); EXPECT_TRUE(s2 != s1); EXPECT_FALSE(s1 == s2); EXPECT_FALSE(s2 == s1); EXPECT_TRUE(s1 < s2); EXPECT_FALSE(s2 < s1); EXPECT_TRUE(s1 <= s2); EXPECT_FALSE(s2 <= s1); EXPECT_TRUE(s2 > s1); EXPECT_FALSE(s1 > s2); EXPECT_TRUE(s2 >= s1); EXPECT_FALSE(s1 >= s2); } { int arr1[] = {1, 2}; // smaller int arr2[] = {2, 1}; // bigger gsl::span s1 = arr1; gsl::span s2 = arr2; EXPECT_TRUE(s1 != s2); EXPECT_TRUE(s2 != s1); EXPECT_FALSE(s1 == s2); EXPECT_FALSE(s2 == s1); EXPECT_TRUE(s1 < s2); EXPECT_FALSE(s2 < s1); EXPECT_TRUE(s1 <= s2); EXPECT_FALSE(s2 <= s1); EXPECT_TRUE(s2 > s1); EXPECT_FALSE(s1 > s2); EXPECT_TRUE(s2 >= s1); EXPECT_FALSE(s1 >= s2); } } #endif // GSL_KERNEL_MODE GSL-4.2.1/tests/span_tests.cpp000066400000000000000000001255331511561312500162050ustar00rootroot00000000000000/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// #include #include // for byte #include // for span, span_iterator, operator==, operator!= #include // for narrow_cast, at #include // for array #include // for ptrdiff_t #include // for ptrdiff_t #include // for reverse_iterator, operator-, operator== #include // for unique_ptr, shared_ptr, make_unique, allo... #include // for match_results, sub_match, match_results<>... #include // for string #include // for integral_constant<>::value, is_default_co... #include #include // for vector // the string_view include and macro are used in the deduction guide verification #if (defined(__cpp_deduction_guides) && (__cpp_deduction_guides >= 201611L)) #ifdef __has_include #if __has_include() #include #define HAS_STRING_VIEW #endif // __has_include() #endif // __has_include #endif // (defined(__cpp_deduction_guides) && (__cpp_deduction_guides >= 201611L)) #if defined(__cplusplus) && __cplusplus >= 202002L #include #endif // __cplusplus >= 202002L #include "deathTestCommon.h" using namespace gsl; #if __cplusplus >= 201703l using std::void_t; #else // __cplusplus >= 201703l template using void_t = void; #endif // __cplusplus < 201703l namespace { struct BaseClass { }; struct DerivedClass : BaseClass { }; struct AddressOverloaded { #if (__cplusplus > 201402L) [[maybe_unused]] #endif AddressOverloaded operator&() const { return {}; } }; } // namespace TEST(span_test, constructors) { span s; EXPECT_TRUE(s.size() == 0); EXPECT_TRUE(s.data() == nullptr); span cs; EXPECT_TRUE(cs.size() == 0); EXPECT_TRUE(cs.data() == nullptr); } TEST(span_test, constructors_with_extent) { span s; EXPECT_TRUE(s.size() == 0); EXPECT_TRUE(s.data() == nullptr); span cs; EXPECT_TRUE(cs.size() == 0); EXPECT_TRUE(cs.data() == nullptr); } TEST(span_test, constructors_with_bracket_init) { span s{}; EXPECT_TRUE(s.size() == 0); EXPECT_TRUE(s.data() == nullptr); span cs{}; EXPECT_TRUE(cs.size() == 0); EXPECT_TRUE(cs.data() == nullptr); } TEST(span_test, size_optimization) { span s; EXPECT_TRUE(sizeof(s) == sizeof(int*) + sizeof(ptrdiff_t)); span se; EXPECT_TRUE(sizeof(se) == sizeof(int*)); } TEST(span_test, from_nullptr_size_constructor) { const auto terminateHandler = std::set_terminate([] { std::cerr << "Expected Death. from_nullptr_size_constructor"; std::abort(); }); const auto expected = GetExpectedDeathString(terminateHandler); { span s{nullptr, narrow_cast::size_type>(0)}; EXPECT_TRUE(s.size() == 0); EXPECT_TRUE(s.data() == nullptr); span cs{nullptr, narrow_cast::size_type>(0)}; EXPECT_TRUE(cs.size() == 0); EXPECT_TRUE(cs.data() == nullptr); } { auto workaround_macro = []() { const span s{nullptr, narrow_cast::size_type>(0)}; }; EXPECT_DEATH(workaround_macro(), expected); } { auto workaround_macro = []() { const span s{nullptr, 1}; }; EXPECT_DEATH(workaround_macro(), expected); auto const_workaround_macro = []() { const span s{nullptr, 1}; }; EXPECT_DEATH(const_workaround_macro(), expected); } { auto workaround_macro = []() { const span s{nullptr, 1}; }; EXPECT_DEATH(workaround_macro(), expected); auto const_workaround_macro = []() { const span s{nullptr, 1}; }; EXPECT_DEATH(const_workaround_macro(), expected); } { span s{nullptr, narrow_cast::size_type>(0)}; EXPECT_TRUE(s.size() == 0); EXPECT_TRUE(s.data() == nullptr); span cs{nullptr, narrow_cast::size_type>(0)}; EXPECT_TRUE(cs.size() == 0); EXPECT_TRUE(cs.data() == nullptr); } } TEST(span_test, from_pointer_length_constructor) { const auto terminateHandler = std::set_terminate([] { std::cerr << "Expected Death. from_pointer_length_constructor"; std::abort(); }); const auto expected = GetExpectedDeathString(terminateHandler); int arr[4] = {1, 2, 3, 4}; { for (int i = 0; i < 4; ++i) { { span s = {&arr[0], narrow_cast(i)}; EXPECT_TRUE(s.size() == narrow_cast(i)); EXPECT_TRUE(s.data() == &arr[0]); EXPECT_TRUE(s.empty() == (i == 0)); for (int j = 0; j < i; ++j) EXPECT_TRUE(arr[j] == s[narrow_cast(j)]); } { span s = {&arr[i], 4 - narrow_cast(i)}; EXPECT_TRUE(s.size() == 4 - narrow_cast(i)); EXPECT_TRUE(s.data() == &arr[i]); EXPECT_TRUE(s.empty() == ((4 - i) == 0)); for (int j = 0; j < 4 - i; ++j) EXPECT_TRUE(arr[j + i] == s[narrow_cast(j)]); } } } { span s{&arr[0], 2}; EXPECT_TRUE(s.size() == 2); EXPECT_TRUE(s.data() == &arr[0]); EXPECT_TRUE(s[0] == 1); EXPECT_TRUE(s[1] == 2); } { int* p = nullptr; span s{p, narrow_cast::size_type>(0)}; EXPECT_TRUE(s.size() == 0); EXPECT_TRUE(s.data() == nullptr); } { int* p = nullptr; auto workaround_macro = [=]() { const span s{p, 2}; }; EXPECT_DEATH(workaround_macro(), expected); } } TEST(span_test, from_pointer_pointer_construction) { // const auto terminateHandler = std::set_terminate([] { // std::cerr << "Expected Death. from_pointer_pointer_construction"; // std::abort(); // }); // const auto expected = GetExpectedDeathString(terminateHandler); int arr[4] = {1, 2, 3, 4}; { span s{&arr[0], &arr[2]}; EXPECT_TRUE(s.size() == 2); EXPECT_TRUE(s.data() == &arr[0]); EXPECT_TRUE(s[0] == 1); EXPECT_TRUE(s[1] == 2); } { span s{&arr[0], &arr[2]}; EXPECT_TRUE(s.size() == 2); EXPECT_TRUE(s.data() == &arr[0]); EXPECT_TRUE(s[0] == 1); EXPECT_TRUE(s[1] == 2); } { span s{&arr[0], &arr[0]}; EXPECT_TRUE(s.size() == 0); EXPECT_TRUE(s.data() == &arr[0]); } { span s{&arr[0], &arr[0]}; EXPECT_TRUE(s.size() == 0); EXPECT_TRUE(s.data() == &arr[0]); } //{ // this test succeeds on all platforms, gsl::span is more relaxed than std::span where this would be UB // auto workaround_macro = [&]() { span s{&arr[1], &arr[0]}; }; // EXPECT_DEATH(workaround_macro(), expected); //} { int* p = nullptr; span s{p, p}; EXPECT_TRUE(s.size() == 0); EXPECT_TRUE(s.data() == nullptr); } { int* p = nullptr; span s{p, p}; EXPECT_TRUE(s.size() == 0); EXPECT_TRUE(s.data() == nullptr); } } template static constexpr bool CtorCompilesFor = false; template static constexpr bool CtorCompilesFor()})>> = true; TEST(span_test, from_array_constructor) { int arr[5] = {1, 2, 3, 4, 5}; static_assert(!CtorCompilesFor, int[5]>, "!CtorCompilesFor, int[5]>"); static_assert(!CtorCompilesFor, int[5]>, "!CtorCompilesFor, int[5]>"); static_assert(!CtorCompilesFor, int[2][3]>, "!CtorCompilesFor, int[2][3]>"); { const span s{arr}; EXPECT_TRUE(s.size() == 5); EXPECT_TRUE(s.data() == &arr[0]); } { const span s{arr}; EXPECT_TRUE(s.size() == 5); EXPECT_TRUE(s.data() == &arr[0]); } int arr2d[2][3] = {1, 2, 3, 4, 5, 6}; static_assert(!CtorCompilesFor, int[2][3]>, "!CtorCompilesFor, int[2][3]>"); static_assert(!CtorCompilesFor, int[2][3]>, "!CtorCompilesFor, int[2][3]>"); { const span s{std::addressof(arr2d[0]), 1}; EXPECT_TRUE(s.size() == 1); EXPECT_TRUE(s.data() == std::addressof(arr2d[0])); } int arr3d[2][3][2] = {{{1, 2}, {3, 4}, {5, 6}}, {{7, 8}, {9, 10}, {11, 12}}}; static_assert(!CtorCompilesFor, int[2][3][2]>, "!CtorCompilesFor, int[2][3][2]>"); static_assert(!CtorCompilesFor, int[2][3][2]>, "!CtorCompilesFor, int[2][3][2]>"); static_assert(!CtorCompilesFor, int[2][3][2]>, "!CtorCompilesFor, int[2][3][2]>"); static_assert(!CtorCompilesFor, int[2][3][2]>, "!CtorCompilesFor, int[2][3][2]>"); { const span s{std::addressof(arr3d[0]), 1}; EXPECT_TRUE(s.size() == 1); } AddressOverloaded ao_arr[5] = {}; { const span s{ao_arr}; EXPECT_TRUE(s.size() == 5); EXPECT_TRUE(s.data() == std::addressof(ao_arr[0])); } } TEST(span_test, from_dynamic_array_constructor) { double(*arr)[3][4] = new double[100][3][4]; { span s(&arr[0][0][0], 10); EXPECT_TRUE(s.size() == 10); EXPECT_TRUE(s.data() == &arr[0][0][0]); } delete[] arr; } template static constexpr bool ConversionCompilesFor = false; template static constexpr bool ConversionCompilesFor()(std::declval()))>> = true; TEST(span_test, from_std_array_constructor) { std::array arr = {1, 2, 3, 4}; { span s{arr}; EXPECT_TRUE(s.size() == arr.size()); EXPECT_TRUE(s.data() == arr.data()); span cs{arr}; EXPECT_TRUE(cs.size() == arr.size()); EXPECT_TRUE(cs.data() == arr.data()); } { span s{arr}; EXPECT_TRUE(s.size() == arr.size()); EXPECT_TRUE(s.data() == arr.data()); span cs{arr}; EXPECT_TRUE(cs.size() == arr.size()); EXPECT_TRUE(cs.data() == arr.data()); } { std::array empty_arr{}; span s{empty_arr}; EXPECT_TRUE(s.size() == 0); EXPECT_TRUE(s.empty()); } std::array ao_arr{}; { span fs{ao_arr}; EXPECT_TRUE(fs.size() == ao_arr.size()); EXPECT_TRUE(ao_arr.data() == fs.data()); } static_assert(!CtorCompilesFor, std::array&>, "!CtorCompilesFor, std::array&>"); static_assert(!CtorCompilesFor, std::array&>, "!CtorCompilesFor, std::array&>"); static_assert(!CtorCompilesFor, std::array&>, "!CtorCompilesFor, std::array&>"); static_assert(!CtorCompilesFor, std::array&>, "!CtorCompilesFor, std::array&>"); static_assert(!CtorCompilesFor, std::array&>, "!CtorCompilesFor, std::array&>"); #if !defined(_MSC_VER) || (_MSC_VER > 1943) || (__cplusplus >= 201703L) // Fails on "Visual Studio 16 2019/Visual Studio 17 2022, windows-2019/2022, Debug/Release, 14". static_assert(!ConversionCompilesFor, std::array>, "!ConversionCompilesFor, std::array>"); #endif { auto get_an_array = []() -> std::array { return {1, 2, 3, 4}; }; auto take_a_span = [](span) {}; // try to take a temporary std::array static_assert(ConversionCompilesFor, std::array>, "ConversionCompilesFor, std::array>"); take_a_span(get_an_array()); } } TEST(span_test, from_const_std_array_constructor) { const std::array arr = {1, 2, 3, 4}; { span s{arr}; EXPECT_TRUE(s.size() == arr.size()); EXPECT_TRUE(s.data() == arr.data()); } { span s{arr}; EXPECT_TRUE(s.size() == arr.size()); EXPECT_TRUE(s.data() == arr.data()); } const std::array ao_arr{}; { span s{ao_arr}; EXPECT_TRUE(s.size() == ao_arr.size()); EXPECT_TRUE(s.data() == ao_arr.data()); } static_assert(!CtorCompilesFor, std::array&>, "!CtorCompilesFor, std::array&>"); static_assert(!CtorCompilesFor, std::array&>, "!CtorCompilesFor, std::array&>"); static_assert(!CtorCompilesFor, std::array&>, "!CtorCompilesFor, std::array&>"); { auto get_an_array = []() -> const std::array { return {1, 2, 3, 4}; }; auto take_a_span = [](span s) { static_cast(s); }; // try to take a temporary std::array take_a_span(get_an_array()); } } TEST(span_test, from_std_array_const_constructor) { std::array arr = {1, 2, 3, 4}; { span s{arr}; EXPECT_TRUE(s.size() == arr.size()); EXPECT_TRUE(s.data() == arr.data()); } { span s{arr}; EXPECT_TRUE(s.size() == arr.size()); EXPECT_TRUE(s.data() == arr.data()); } static_assert(!CtorCompilesFor, const std::array&>, "!CtorCompilesFor, const std::array&>"); static_assert(!CtorCompilesFor, const std::array&>, "!CtorCompilesFor, const std::array&>"); static_assert(!CtorCompilesFor, const std::array&>, "!CtorCompilesFor, const std::array&>"); static_assert(!CtorCompilesFor, const std::array&>, "!CtorCompilesFor, const std::array&>"); } TEST(span_test, from_container_constructor) { std::vector v = {1, 2, 3}; const std::vector cv = v; { span s{v}; EXPECT_TRUE(s.size() == v.size()); EXPECT_TRUE(s.data() == v.data()); span cs{v}; EXPECT_TRUE(cs.size() == v.size()); EXPECT_TRUE(cs.data() == v.data()); } std::string str = "hello"; const std::string cstr = "hello"; { static_assert(CtorCompilesFor, std::string&> == (__cplusplus >= 201703L), "CtorCompilesFor, std::string&> == (__cplusplus >= 201703L)"); span cs{str}; EXPECT_TRUE(cs.size() == str.size()); EXPECT_TRUE(cs.data() == str.data()); } { static_assert(!CtorCompilesFor, const std::string&>, "!CtorCompilesFor, const std::string&>"); span cs{cstr}; EXPECT_TRUE(cs.size() == cstr.size()); EXPECT_TRUE(cs.data() == cstr.data()); } #if !defined(_MSC_VER) || (_MSC_VER > 1943) || (__cplusplus >= 201703L) // Fails on "Visual Studio 16 2019/Visual Studio 17 2022, windows-2019/2022, Debug/Release, 14". static_assert(!ConversionCompilesFor, std::vector>, "!ConversionCompilesFor, std::vector>"); #endif // !defined(_MSC_VER) || (_MSC_VER > 1942) || (__cplusplus >= 201703L) { auto get_temp_vector = []() -> std::vector { return {}; }; auto use_span = [](span s) { static_cast(s); }; use_span(get_temp_vector()); } static_assert(!ConversionCompilesFor, std::string>, "!ConversionCompilesFor, std::string>"); { auto get_temp_string = []() -> std::string { return {}; }; auto use_span = [](span s) { static_cast(s); }; use_span(get_temp_string()); } static_assert(!ConversionCompilesFor, const std::vector>, "!ConversionCompilesFor, const std::vector>"); static_assert(!ConversionCompilesFor, const std::string>, "!ConversionCompilesFor, const std::string>"); { auto get_temp_string = []() -> const std::string { return {}; }; auto use_span = [](span s) { static_cast(s); }; use_span(get_temp_string()); } static_assert(!CtorCompilesFor, std::map&>, "!CtorCompilesFor, std::map&>"); } TEST(span_test, from_convertible_span_constructor) { const auto terminateHandler = std::set_terminate([] { std::cerr << "Expected Death. from_convertible_span_constructor"; std::abort(); }); const auto expected = GetExpectedDeathString(terminateHandler); { span avd; span avcd = avd; static_cast(avcd); } { std::array arr{}; span avd{arr}; span avcd = avd; static_cast(avcd); } { std::array arr{}; span avd{arr}; span avcd = avd; static_cast(avcd); } { std::array arr{}; span avd{arr}; span avcd{avd}; static_cast(avcd); } { std::array arr{}; span avd{arr}; using T = span; EXPECT_DEATH(T{avd}, expected); } { std::array arr{}; span avd{arr}; using T = span; EXPECT_DEATH(T{avd}, expected); } static_assert(!ConversionCompilesFor, span&>, "!ConversionCompilesFor, span&>"); static_assert(!ConversionCompilesFor, span&>, "!ConversionCompilesFor, span&>"); static_assert(!ConversionCompilesFor, span&>, "!ConversionCompilesFor, span&>"); static_assert(!ConversionCompilesFor, span&>, "!ConversionCompilesFor, span&>"); static_assert(!ConversionCompilesFor, span&>, "!ConversionCompilesFor, span&>"); static_assert(!ConversionCompilesFor, span&>, "!ConversionCompilesFor, span&>"); static_assert(!ConversionCompilesFor, span&>, "!ConversionCompilesFor, span&>"); } TEST(span_test, copy_move_and_assignment) { span s1; EXPECT_TRUE(s1.empty()); int arr[] = {3, 4, 5}; span s2 = arr; EXPECT_TRUE(s2.size() == 3); EXPECT_TRUE(s2.data() == &arr[0]); s2 = s1; EXPECT_TRUE(s2.empty()); auto get_temp_span = [&]() -> span { return {&arr[1], 2}; }; auto use_span = [&](span s) { EXPECT_TRUE(s.size() == 2); EXPECT_TRUE(s.data() == &arr[1]); }; use_span(get_temp_span()); s1 = get_temp_span(); EXPECT_TRUE(s1.size() == 2); EXPECT_TRUE(s1.data() == &arr[1]); } TEST(span_test, first) { const auto terminateHandler = std::set_terminate([] { std::cerr << "Expected Death. first"; std::abort(); }); const auto expected = GetExpectedDeathString(terminateHandler); int arr[5] = {1, 2, 3, 4, 5}; { span av = arr; EXPECT_TRUE(av.first<2>().size() == 2); EXPECT_TRUE(av.first(2).size() == 2); } { span av = arr; EXPECT_TRUE(av.first<0>().size() == 0); EXPECT_TRUE(av.first(0).size() == 0); } { span av = arr; EXPECT_TRUE(av.first<5>().size() == 5); EXPECT_TRUE(av.first(5).size() == 5); } { span av = arr; #ifdef CONFIRM_COMPILATION_ERRORS (void) av.first<6>(); #endif EXPECT_DEATH(av.first(6), expected); } { span av; EXPECT_TRUE(av.first<0>().size() == 0); EXPECT_TRUE(av.first(0).size() == 0); } } TEST(span_test, last) { const auto terminateHandler = std::set_terminate([] { std::cerr << "Expected Death. last"; std::abort(); }); const auto expected = GetExpectedDeathString(terminateHandler); int arr[5] = {1, 2, 3, 4, 5}; { span av = arr; EXPECT_TRUE(av.last<2>().size() == 2); EXPECT_TRUE(av.last(2).size() == 2); } { span av = arr; EXPECT_TRUE(av.last<0>().size() == 0); EXPECT_TRUE(av.last(0).size() == 0); } { span av = arr; EXPECT_TRUE(av.last<5>().size() == 5); EXPECT_TRUE(av.last(5).size() == 5); } { span av = arr; #ifdef CONFIRM_COMPILATION_ERRORS (void) av.last<6>(); #endif EXPECT_DEATH(av.last(6), expected); } { span av; EXPECT_TRUE(av.last<0>().size() == 0); EXPECT_TRUE(av.last(0).size() == 0); } } TEST(span_test, subspan) { const auto terminateHandler = std::set_terminate([] { std::cerr << "Expected Death. subspan"; std::abort(); }); const auto expected = GetExpectedDeathString(terminateHandler); int arr[5] = {1, 2, 3, 4, 5}; { span av = arr; EXPECT_TRUE((av.subspan<2, 2>().size()) == 2); EXPECT_TRUE(decltype(av.subspan<2, 2>())::extent == 2); EXPECT_TRUE(av.subspan(2, 2).size() == 2); EXPECT_TRUE((av.subspan<2, 3>().size()) == 3); EXPECT_TRUE(decltype(av.subspan<2, 3>())::extent == 3); EXPECT_TRUE(av.subspan(2, 3).size() == 3); } { span av = arr; EXPECT_TRUE((av.subspan<0, 0>().size()) == 0); EXPECT_TRUE(decltype(av.subspan<0, 0>())::extent == 0); EXPECT_TRUE(av.subspan(0, 0).size() == 0); } { span av = arr; EXPECT_TRUE((av.subspan<0, 5>().size()) == 5); EXPECT_TRUE(decltype(av.subspan<0, 5>())::extent == 5); EXPECT_TRUE(av.subspan(0, 5).size() == 5); #ifdef CONFIRM_COMPILATION_ERRORS (void) av.subspan<0, 6>(); (void) av.subspan<1, 5>(); #endif EXPECT_DEATH(av.subspan(0, 6), expected); EXPECT_DEATH(av.subspan(1, 5), expected); } { span av = arr; EXPECT_TRUE((av.subspan<4, 0>().size()) == 0); EXPECT_TRUE(decltype(av.subspan<4, 0>())::extent == 0); EXPECT_TRUE(av.subspan(4, 0).size() == 0); EXPECT_TRUE((av.subspan<5, 0>().size()) == 0); EXPECT_TRUE(decltype(av.subspan<5, 0>())::extent == 0); EXPECT_TRUE(av.subspan(5, 0).size() == 0); #ifdef CONFIRM_COMPILATION_ERRORS (void) av.subspan<6, 0>(); #endif EXPECT_DEATH(av.subspan(6, 0), expected); } { span av = arr; EXPECT_TRUE(av.subspan<1>().size() == 4); EXPECT_TRUE(decltype(av.subspan<1>())::extent == 4); EXPECT_TRUE(av.subspan(1).size() == 4); } { span av; EXPECT_TRUE((av.subspan<0, 0>().size()) == 0); EXPECT_TRUE(decltype(av.subspan<0, 0>())::extent == 0); EXPECT_TRUE(av.subspan(0, 0).size() == 0); EXPECT_DEATH((av.subspan<1, 0>()), expected); EXPECT_DEATH((av.subspan(1, 0)), expected); } { span av; EXPECT_TRUE((av.subspan<0>().size()) == 0); EXPECT_TRUE(decltype(av.subspan<0>())::extent == dynamic_extent); EXPECT_TRUE(av.subspan(0).size() == 0); EXPECT_DEATH(av.subspan<1>(), expected); EXPECT_TRUE(decltype(av.subspan<1>())::extent == dynamic_extent); EXPECT_DEATH(av.subspan(1), expected); } { span av = arr; EXPECT_TRUE(av.subspan(0).size() == 5); EXPECT_TRUE(av.subspan<0>().size() == 5); EXPECT_TRUE(av.subspan(1).size() == 4); EXPECT_TRUE(av.subspan<1>().size() == 4); EXPECT_TRUE(av.subspan(4).size() == 1); EXPECT_TRUE(av.subspan<4>().size() == 1); EXPECT_TRUE(av.subspan(5).size() == 0); EXPECT_TRUE(av.subspan<5>().size() == 0); EXPECT_DEATH(av.subspan(6), expected); EXPECT_DEATH(av.subspan<6>(), expected); const auto av2 = av.subspan(1); for (std::size_t i = 0; i < 4; ++i) EXPECT_TRUE(av2[i] == static_cast(i) + 2); const auto av3 = av.subspan<1>(); for (std::size_t i = 0; i < 4; ++i) EXPECT_TRUE(av3[i] == static_cast(i) + 2); } { span av = arr; EXPECT_TRUE(av.subspan(0).size() == 5); EXPECT_TRUE(av.subspan<0>().size() == 5); EXPECT_TRUE(av.subspan(1).size() == 4); EXPECT_TRUE(av.subspan<1>().size() == 4); EXPECT_TRUE(av.subspan(4).size() == 1); EXPECT_TRUE(av.subspan<4>().size() == 1); EXPECT_TRUE(av.subspan(5).size() == 0); EXPECT_TRUE(av.subspan<5>().size() == 0); EXPECT_DEATH(av.subspan(6), expected); #ifdef CONFIRM_COMPILATION_ERRORS EXPECT_DEATH(av.subspan<6>(), expected); #endif const auto av2 = av.subspan(1); for (std::size_t i = 0; i < 4; ++i) EXPECT_TRUE(av2[i] == static_cast(i) + 2); const auto av3 = av.subspan<1>(); for (std::size_t i = 0; i < 4; ++i) EXPECT_TRUE(av3[i] == static_cast(i) + 2); } } TEST(span_test, iterator_default_init) { span::iterator it1; span::iterator it2; EXPECT_TRUE(it1 == it2); } TEST(span_test, iterator_comparisons) { int a[] = {1, 2, 3, 4}; { span s = a; span::iterator it = s.begin(); auto it2 = it + 1; EXPECT_TRUE(it == it); EXPECT_TRUE(it == s.begin()); EXPECT_TRUE(s.begin() == it); EXPECT_TRUE(it != it2); EXPECT_TRUE(it2 != it); EXPECT_TRUE(it != s.end()); EXPECT_TRUE(it2 != s.end()); EXPECT_TRUE(s.end() != it); EXPECT_TRUE(it < it2); EXPECT_TRUE(it <= it2); EXPECT_TRUE(it2 <= s.end()); EXPECT_TRUE(it < s.end()); EXPECT_TRUE(it2 > it); EXPECT_TRUE(it2 >= it); EXPECT_TRUE(s.end() > it2); EXPECT_TRUE(s.end() >= it2); } } TEST(span_test, incomparable_iterators) { const auto terminateHandler = std::set_terminate([] { std::cerr << "Expected Death. incomparable_iterators"; std::abort(); }); const auto expected = GetExpectedDeathString(terminateHandler); int a[] = {1, 2, 3, 4}; int b[] = {1, 2, 3, 4}; { span s = a; span s2 = b; #if (__cplusplus > 201402L) EXPECT_DEATH([[maybe_unused]] bool _ = (s.begin() == s2.begin()), expected); EXPECT_DEATH([[maybe_unused]] bool _ = (s.begin() <= s2.begin()), expected); #else EXPECT_DEATH(bool _ = (s.begin() == s2.begin()), expected); EXPECT_DEATH(bool _ = (s.begin() <= s2.begin()), expected); #endif } } TEST(span_test, begin_end) { const auto terminateHandler = std::set_terminate([] { std::cerr << "Expected Death. begin_end"; std::abort(); }); const auto expected = GetExpectedDeathString(terminateHandler); { int a[] = {1, 2, 3, 4}; span s = a; span::iterator it = s.begin(); span::iterator it2 = std::begin(s); EXPECT_TRUE(it == it2); it = s.end(); it2 = std::end(s); EXPECT_TRUE(it == it2); } { int a[] = {1, 2, 3, 4}; span s = a; auto it = s.begin(); auto first = it; EXPECT_TRUE(it == first); EXPECT_TRUE(*it == 1); auto beyond = s.end(); EXPECT_TRUE(it != beyond); EXPECT_DEATH(*beyond, expected); EXPECT_TRUE(beyond - first == 4); EXPECT_TRUE(first - first == 0); EXPECT_TRUE(beyond - beyond == 0); ++it; EXPECT_TRUE(it - first == 1); EXPECT_TRUE(*it == 2); *it = 22; EXPECT_TRUE(*it == 22); EXPECT_TRUE(beyond - it == 3); it = first; EXPECT_TRUE(it == first); while (it != s.end()) { *it = 5; ++it; } EXPECT_TRUE(it == beyond); EXPECT_TRUE(it - beyond == 0); for (const auto& n : s) { EXPECT_TRUE(n == 5); } } } TEST(span_test, rbegin_rend) { const auto terminateHandler = std::set_terminate([] { std::cerr << "Expected Death. rbegin_rend"; std::abort(); }); const auto expected = GetExpectedDeathString(terminateHandler); { int a[] = {1, 2, 3, 4}; span s = a; auto it = s.rbegin(); auto first = it; EXPECT_TRUE(it == first); EXPECT_TRUE(*it == 4); auto beyond = s.rend(); EXPECT_TRUE(it != beyond); #if (__cplusplus > 201402L) EXPECT_DEATH([[maybe_unused]] auto _ = *beyond, expected); #else EXPECT_DEATH(auto _ = *beyond, expected); #endif EXPECT_TRUE(beyond - first == 4); EXPECT_TRUE(first - first == 0); EXPECT_TRUE(beyond - beyond == 0); ++it; EXPECT_TRUE(it - s.rbegin() == 1); EXPECT_TRUE(*it == 3); *it = 22; EXPECT_TRUE(*it == 22); EXPECT_TRUE(beyond - it == 3); it = first; EXPECT_TRUE(it == first); while (it != s.rend()) { *it = 5; ++it; } EXPECT_TRUE(it == beyond); EXPECT_TRUE(it - beyond == 0); for (const auto& n : s) { EXPECT_TRUE(n == 5); } } } template static constexpr bool AsWritableBytesCompilesFor = false; template static constexpr bool AsWritableBytesCompilesFor()))>> = true; TEST(span_test, as_bytes) { int a[] = {1, 2, 3, 4}; static_assert(AsWritableBytesCompilesFor>, "AsWriteableBytesCompilesFor>"); // you should not be able to get writeable bytes for const objects static_assert(!AsWritableBytesCompilesFor>, "!AsWriteableBytesCompilesFor>"); { const span s = a; EXPECT_TRUE(s.size() == 4); const span bs = as_bytes(s); EXPECT_TRUE(static_cast(bs.data()) == static_cast(s.data())); EXPECT_TRUE(bs.size() == s.size_bytes()); } { span s; const auto bs = as_bytes(s); EXPECT_TRUE(bs.size() == s.size()); EXPECT_TRUE(bs.size() == 0); EXPECT_TRUE(bs.size_bytes() == 0); EXPECT_TRUE(static_cast(bs.data()) == static_cast(s.data())); EXPECT_TRUE(bs.data() == nullptr); } { span s = a; const auto bs = as_bytes(s); EXPECT_TRUE(static_cast(bs.data()) == static_cast(s.data())); EXPECT_TRUE(bs.size() == s.size_bytes()); } } TEST(span_test, as_writable_bytes) { int a[] = {1, 2, 3, 4}; { span s; const auto bs = as_writable_bytes(s); EXPECT_TRUE(bs.size() == s.size()); EXPECT_TRUE(bs.size() == 0); EXPECT_TRUE(bs.size_bytes() == 0); EXPECT_TRUE(static_cast(bs.data()) == static_cast(s.data())); EXPECT_TRUE(bs.data() == nullptr); } { span s = a; const auto bs = as_writable_bytes(s); EXPECT_TRUE(static_cast(bs.data()) == static_cast(s.data())); EXPECT_TRUE(bs.size() == s.size_bytes()); } } TEST(span_test, fixed_size_conversions) { const auto terminateHandler = std::set_terminate([] { std::cerr << "Expected Death. fixed_size_conversions"; std::abort(); }); const auto expected = GetExpectedDeathString(terminateHandler); int arr[] = {1, 2, 3, 4}; // converting to an span from an equal size array is ok span s4 = arr; EXPECT_TRUE(s4.size() == 4); // converting to dynamic_range is always ok { span s = s4; EXPECT_TRUE(s.size() == s4.size()); static_cast(s); } // initialization or assignment to static span that REDUCES size is NOT ok static_assert(!ConversionCompilesFor, int[4]>, "!ConversionCompilesFor, int[4]>"); static_assert(!ConversionCompilesFor, span>, "!ConversionCompilesFor, span>"); // even when done dynamically static_assert(!ConversionCompilesFor, span>, "!ConversionCompilesFor, span>"); // but doing so explicitly is ok // you can convert statically { const span s2{&arr[0], 2}; static_cast(s2); } { const span s1 = s4.first<1>(); static_cast(s1); } // this is not a legal operation in std::span, so we are no longer supporting it // conversion from span to span via call to `first` // then convert from span to span // The dynamic to fixed extents are not supported in the standard // to make this work, span would need to be span. static_assert(!ConversionCompilesFor, span>, "!ConversionCompilesFor, span>"); // initialization or assignment to static span that requires size INCREASE is not ok. int arr2[2] = {1, 2}; static_assert(!ConversionCompilesFor, int[2]>, "!ConversionCompilesFor, int[2]>"); static_assert(!ConversionCompilesFor, int[2]>, "!ConversionCompilesFor, int[2]>"); static_assert(!ConversionCompilesFor, span>, "!ConversionCompilesFor, span>"); { auto f = [&]() { const span _s4{arr2, 2}; static_cast(_s4); }; EXPECT_DEATH(f(), expected); } // This no longer compiles. There is no suitable conversion from dynamic span to a fixed size // span. // this should fail - we are trying to assign a small dynamic span to a fixed_size larger one static_assert(!ConversionCompilesFor, span>, "!ConversionCompilesFor, span>"); } TEST(span_test, interop_with_std_regex) { char lat[] = {'1', '2', '3', '4', '5', '6', 'E', 'F', 'G'}; span s = lat; const auto f_it = s.begin() + 7; std::match_results::iterator> match; std::regex_match(s.begin(), s.end(), match, std::regex(".*")); EXPECT_TRUE(match.ready()); EXPECT_FALSE(match.empty()); EXPECT_TRUE(match[0].matched); EXPECT_TRUE(match[0].first == s.begin()); EXPECT_TRUE(match[0].second == s.end()); std::regex_search(s.begin(), s.end(), match, std::regex("F")); EXPECT_TRUE(match.ready()); EXPECT_FALSE(match.empty()); EXPECT_TRUE(match[0].matched); EXPECT_TRUE(match[0].first == f_it); EXPECT_TRUE(match[0].second == (f_it + 1)); } TEST(span_test, default_constructible) { EXPECT_TRUE((std::is_default_constructible>::value)); EXPECT_TRUE((std::is_default_constructible>::value)); EXPECT_FALSE((std::is_default_constructible>::value)); } TEST(span_test, std_container_ctad) { #if (defined(__cpp_deduction_guides) && (__cpp_deduction_guides >= 201611L)) // this test is just to verify that these compile { std::vector v{1, 2, 3, 4}; gsl::span sp{v}; static_assert(std::is_same>::value); } { std::string str{"foo"}; gsl::span sp{str}; static_assert(std::is_same>::value); } #ifdef HAS_STRING_VIEW { std::string_view sv{"foo"}; gsl::span sp{sv}; static_assert(std::is_same>::value); } #endif #endif } TEST(span_test, front_back) { int arr[5] = {1, 2, 3, 4, 5}; span s{arr}; EXPECT_TRUE(s.front() == 1); EXPECT_TRUE(s.back() == 5); const auto terminateHandler = std::set_terminate([] { std::cerr << "Expected Death. front_back"; std::abort(); }); const auto expected = GetExpectedDeathString(terminateHandler); span s2; EXPECT_DEATH(s2.front(), expected); EXPECT_DEATH(s2.back(), expected); } #if defined(FORCE_STD_SPAN_TESTS) || defined(__cpp_lib_span) && __cpp_lib_span >= 202002L TEST(span_test, std_span) { // make sure std::span can be constructed from gsl::span int arr[5] = {1, 2, 3, 4, 5}; gsl::span gsl_span{arr}; #if defined(__cpp_lib_ranges) || (defined(_MSVC_STL_VERSION) && defined(__cpp_lib_concepts)) EXPECT_TRUE(std::to_address(gsl_span.begin()) == gsl_span.data()); EXPECT_TRUE(std::to_address(gsl_span.end()) == gsl_span.data() + gsl_span.size()); #endif // __cpp_lib_ranges std::span std_span = gsl_span; EXPECT_TRUE(std_span.data() == gsl_span.data()); EXPECT_TRUE(std_span.size() == gsl_span.size()); } #endif // defined(FORCE_STD_SPAN_TESTS) || defined(__cpp_lib_span) && __cpp_lib_span >= 202002L #if defined(__cpp_lib_span) && defined(__cpp_lib_ranges) // This test covers the changes in PR #1100 TEST(span_test, msvc_compile_error_PR1100) { int arr[]{1, 7, 2, 9}; gsl::span sp{arr, std::size(arr)}; std::ranges::sort(sp); for (const auto& e : sp) { (void) e; } } #endif // defined(__cpp_lib_span) && defined(__cpp_lib_ranges) TEST(span_test, empty_span) { span s{}; EXPECT_TRUE(s.empty()); EXPECT_TRUE(s.size() == 0); EXPECT_TRUE(s.data() == nullptr); span cs{}; EXPECT_TRUE(cs.empty()); EXPECT_TRUE(cs.size() == 0); EXPECT_TRUE(cs.data() == nullptr); } TEST(span_test, conversions) { int arr[5] = {1, 2, 3, 4, 5}; #if defined(__cpp_deduction_guides) && (__cpp_deduction_guides >= 201611L) span s = arr; span cs = s; #else span s = arr; span cs = s; #endif EXPECT_TRUE(cs.size() == s.size()); EXPECT_TRUE(cs.data() == s.data()); span fs = s; EXPECT_TRUE(fs.size() == s.size()); EXPECT_TRUE(fs.data() == s.data()); span cfs = s; EXPECT_TRUE(cfs.size() == s.size()); EXPECT_TRUE(cfs.data() == s.data()); } TEST(span_test, comparison_operators) { int arr1[3] = {1, 2, 3}; int arr2[3] = {1, 2, 3}; int arr3[3] = {4, 5, 6}; span s1 = arr1; span s2 = arr2; span s3 = arr3; EXPECT_TRUE(s1 == s2); EXPECT_FALSE(s1 != s2); EXPECT_FALSE(s1 == s3); EXPECT_TRUE(s1 != s3); EXPECT_TRUE(s1 < s3); EXPECT_FALSE(s3 < s1); EXPECT_TRUE(s1 <= s2); EXPECT_TRUE(s1 <= s3); EXPECT_FALSE(s3 <= s1); EXPECT_TRUE(s3 > s1); EXPECT_FALSE(s1 > s3); EXPECT_TRUE(s3 >= s1); EXPECT_TRUE(s1 >= s2); EXPECT_FALSE(s1 >= s3); } // ...existing code... #if defined(__cpp_lib_span) && __cpp_lib_span >= 202002L #include // for std::span TEST(span_test, compare_empty_span) { gsl::span gsl_s{}; std::span std_s{}; EXPECT_TRUE(gsl_s.empty()); EXPECT_TRUE(std_s.empty()); EXPECT_EQ(gsl_s.size(), std_s.size()); EXPECT_EQ(gsl_s.data(), std_s.data()); } TEST(span_test, compare_subspan) { int arr[5] = {1, 2, 3, 4, 5}; gsl::span gsl_s = arr; std::span std_s = arr; auto gsl_sub1 = gsl_s.subspan(1); auto std_sub1 = std_s.subspan(1); EXPECT_EQ(gsl_sub1.size(), std_sub1.size()); EXPECT_EQ(gsl_sub1.data(), std_sub1.data()); auto gsl_sub2 = gsl_s.subspan(1, 2); auto std_sub2 = std_s.subspan(1, 2); EXPECT_EQ(gsl_sub2.size(), std_sub2.size()); EXPECT_EQ(gsl_sub2.data(), std_sub2.data()); } TEST(span_test, compare_conversions) { int arr[5] = {1, 2, 3, 4, 5}; gsl::span gsl_s = arr; std::span std_s = arr; gsl::span gsl_cs = gsl_s; std::span std_cs = std_s; EXPECT_EQ(gsl_cs.size(), std_cs.size()); EXPECT_EQ(gsl_cs.data(), std_cs.data()); gsl::span gsl_fs = gsl_s; std::span std_fs = std_s; EXPECT_EQ(gsl_fs.size(), std_fs.size()); EXPECT_EQ(gsl_fs.data(), std_fs.data()); gsl::span gsl_cfs = gsl_s; std::span std_cfs = std_s; EXPECT_EQ(gsl_cfs.size(), std_cfs.size()); EXPECT_EQ(gsl_cfs.data(), std_cfs.data()); } TEST(span_test, deduction_guides) { int arr[5] = {1, 2, 3, 4, 5}; std::array std_arr = {1, 2, 3, 4, 5}; std::vector vec = {1, 2, 3, 4, 5}; // Test deduction guides for gsl::span gsl::span gsl_s1 = arr; gsl::span gsl_s2 = std_arr; gsl::span gsl_s3 = vec; // Test deduction guides for std::span (for sanity checks) std::span std_s1 = arr; std::span std_s2 = std_arr; std::span std_s3 = vec; // Compare sizes EXPECT_EQ(gsl_s1.size(), std_s1.size()); EXPECT_EQ(gsl_s2.size(), std_s2.size()); EXPECT_EQ(gsl_s3.size(), std_s3.size()); // Compare data pointers EXPECT_EQ(gsl_s1.data(), std_s1.data()); EXPECT_EQ(gsl_s2.data(), std_s2.data()); EXPECT_EQ(gsl_s3.data(), std_s3.data()); } #endif // defined(__cpp_lib_span) && __cpp_lib_span >= 202002L GSL-4.2.1/tests/strict_notnull_tests.cpp000066400000000000000000000315131511561312500203210ustar00rootroot00000000000000/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// #include // for not_null, operator<, operator<=, operator> #include #include // for declval #include "deathTestCommon.h" using namespace gsl; #if __cplusplus >= 201703l using std::void_t; #else // __cplusplus >= 201703l template using void_t = void; #endif // __cplusplus < 201703l // stand-in for a user-defined ref-counted class template struct RefCounted { RefCounted(T* p) : p_(p) {} operator T*() { return p_; } T* p_; }; namespace { // clang-format off GSL_SUPPRESS(f.4) // NO-FORMAT: attribute // clang-format on bool helper(not_null p) { return *p == 12; } // clang-format off GSL_SUPPRESS(f.4) // NO-FORMAT: attribute // clang-format on bool helper_const(not_null p) { return *p == 12; } // clang-format off GSL_SUPPRESS(f.4) // NO-FORMAT: attribute // clang-format on bool strict_helper(strict_not_null p) { return *p == 12; } // clang-format off GSL_SUPPRESS(f.4) // NO-FORMAT: attribute // clang-format on bool strict_helper_const(strict_not_null p) { return *p == 12; } int* return_pointer() { return nullptr; } } // namespace template static constexpr bool CtorCompilesFor_A = false; template static constexpr bool CtorCompilesFor_A{std::declval()})>> = true; template static constexpr bool CtorCompilesFor_B = false; template static constexpr bool CtorCompilesFor_B{N})>> = true; template static constexpr bool DefaultCtorCompilesFor = false; template static constexpr bool DefaultCtorCompilesFor{})>> = true; template static constexpr bool CtorCompilesFor_C = false; template static constexpr bool CtorCompilesFor_C< U, void_t{std::declval>()})>> = true; TEST(strict_notnull_tests, TestStrictNotNullConstructors) { { static_assert(CtorCompilesFor_A, "CtorCompilesFor_A"); static_assert(!CtorCompilesFor_A, "!CtorCompilesFor_A"); static_assert(!CtorCompilesFor_B, "!CtorCompilesFor_B"); static_assert(!DefaultCtorCompilesFor, "!DefaultCtorCompilesFor"); static_assert(!CtorCompilesFor_C, "CtorCompilesFor_C"); #ifdef CONFIRM_COMPILATION_ERRORS // Forbid non-nullptr assignable types strict_not_null> f(std::vector{1}); strict_not_null z(10); strict_not_null> y({1, 2}); #endif } const auto terminateHandler = std::set_terminate([] { std::cerr << "Expected Death. TestNotNullConstructors"; std::abort(); }); const auto expected = GetExpectedDeathString(terminateHandler); { // from shared pointer int i = 12; auto rp = RefCounted(&i); strict_not_null p(rp); EXPECT_TRUE(p.get() == &i); strict_not_null> x( std::make_shared(10)); // shared_ptr is nullptr assignable int* pi = nullptr; EXPECT_DEATH((strict_not_null(pi)), expected); } { // from unique pointer strict_not_null> x( std::make_unique(10)); // unique_ptr is nullptr assignable EXPECT_DEATH((strict_not_null>(std::unique_ptr{})), expected); } { // from pointer to local int t = 42; strict_not_null x{&t}; helper(&t); helper_const(&t); EXPECT_TRUE(*x == 42); } { // from raw pointer // from strict_not_null pointer int t = 42; int* p = &t; strict_not_null x{p}; helper(p); helper_const(p); helper(x); helper_const(x); EXPECT_TRUE(*x == 42); } { // from raw const pointer // from strict_not_null const pointer int t = 42; const int* cp = &t; strict_not_null x{cp}; helper_const(cp); helper_const(x); EXPECT_TRUE(*x == 42); } { // from strict_not_null const pointer, using auto int t = 42; const int* cp = &t; auto x = strict_not_null{cp}; EXPECT_TRUE(*x == 42); } { // from returned pointer EXPECT_DEATH(helper(return_pointer()), expected); EXPECT_DEATH(helper_const(return_pointer()), expected); } } template static constexpr bool StrictHelperCompilesFor = false; template static constexpr bool StrictHelperCompilesFor()))>> = true; template static constexpr bool StrictHelperConstCompilesFor = false; template static constexpr bool StrictHelperConstCompilesFor()))>> = true; template static constexpr bool HelperCompilesFor = false; template static constexpr bool HelperCompilesFor()))>> = true; TEST(strict_notnull_tests, TestStrictNotNull) { { // raw ptr <-> strict_not_null int x = 42; #ifdef CONFIRM_COMPILATION_ERRORS strict_not_null snn = &x; #endif static_assert(!StrictHelperCompilesFor, "!StrictHelperCompilesFor"); static_assert(!StrictHelperConstCompilesFor, "!StrictHelperCompilesFor"); const strict_not_null snn1{&x}; static_assert(StrictHelperCompilesFor>, "StrictHelperCompilesFor>"); helper(snn1); helper_const(snn1); EXPECT_TRUE(*snn1 == 42); } { // raw ptr <-> strict_not_null const int x = 42; #ifdef CONFIRM_COMPILATION_ERRORS strict_not_null snn = &x; #endif static_assert(!StrictHelperCompilesFor, "!StrictHelperFor"); static_assert(!StrictHelperConstCompilesFor, "!StrictHelperCompilesFor"); const strict_not_null snn1{&x}; static_assert(!HelperCompilesFor>, "!HelperCompilesFor>"); static_assert(StrictHelperConstCompilesFor>, "StrictHelperCompilesFor>"); helper_const(snn1); EXPECT_TRUE(*snn1 == 42); } { // strict_not_null -> strict_not_null int x = 42; strict_not_null snn1{&x}; const strict_not_null snn2{&x}; strict_helper(snn1); strict_helper_const(snn1); strict_helper_const(snn2); EXPECT_TRUE(snn1 == snn2); } { // strict_not_null -> strict_not_null const int x = 42; strict_not_null snn1{&x}; const strict_not_null snn2{&x}; static_assert(!StrictHelperCompilesFor>, "!StrictHelperCompilesFor>"); strict_helper_const(snn1); strict_helper_const(snn2); EXPECT_TRUE(snn1 == snn2); } { // strict_not_null -> not_null int x = 42; strict_not_null snn{&x}; const not_null nn1 = snn; const not_null nn2{snn}; helper(snn); helper_const(snn); EXPECT_TRUE(snn == nn1); EXPECT_TRUE(snn == nn2); } { // strict_not_null -> not_null const int x = 42; strict_not_null snn{&x}; const not_null nn1 = snn; const not_null nn2{snn}; static_assert(!HelperCompilesFor>, "!HelperCompilesFor>"); helper_const(snn); EXPECT_TRUE(snn == nn1); EXPECT_TRUE(snn == nn2); } { // not_null -> strict_not_null int x = 42; not_null nn{&x}; const strict_not_null snn1{nn}; const strict_not_null snn2{nn}; strict_helper(nn); strict_helper_const(nn); EXPECT_TRUE(snn1 == nn); EXPECT_TRUE(snn2 == nn); std::hash> hash_snn; std::hash> hash_nn; EXPECT_TRUE(hash_nn(snn1) == hash_nn(nn)); EXPECT_TRUE(hash_snn(snn1) == hash_nn(nn)); EXPECT_TRUE(hash_nn(snn1) == hash_nn(snn2)); EXPECT_TRUE(hash_snn(snn1) == hash_snn(nn)); } { // not_null -> strict_not_null const int x = 42; not_null nn{&x}; const strict_not_null snn1{nn}; const strict_not_null snn2{nn}; static_assert(!StrictHelperCompilesFor>, "!StrictHelperCompilesFor>"); strict_helper_const(nn); EXPECT_TRUE(snn1 == nn); EXPECT_TRUE(snn2 == nn); std::hash> hash_snn; std::hash> hash_nn; EXPECT_TRUE(hash_nn(snn1) == hash_nn(nn)); EXPECT_TRUE(hash_snn(snn1) == hash_nn(nn)); EXPECT_TRUE(hash_nn(snn1) == hash_nn(snn2)); EXPECT_TRUE(hash_snn(snn1) == hash_snn(nn)); } } TEST(pointers_test, member_types) { // make sure `element_type` is inherited from `gsl::not_null` static_assert(std::is_same::element_type, int*>::value, "check member type: element_type"); } #if defined(__cplusplus) && (__cplusplus >= 201703L) TEST(strict_notnull_tests, TestStrictNotNullConstructorTypeDeduction) { const auto terminateHandler = std::set_terminate([] { std::cerr << "Expected Death. TestStrictNotNullConstructorTypeDeduction"; std::abort(); }); const auto expected = GetExpectedDeathString(terminateHandler); { int i = 42; strict_not_null x{&i}; helper(strict_not_null{&i}); helper_const(strict_not_null{&i}); EXPECT_TRUE(*x == 42); } { const int i = 42; strict_not_null x{&i}; static_assert(!HelperCompilesFor>, "!HelperCompilesFor>"); helper_const(strict_not_null{&i}); EXPECT_TRUE(*x == 42); } { int i = 42; int* p = &i; strict_not_null x{p}; helper(strict_not_null{p}); helper_const(strict_not_null{p}); EXPECT_TRUE(*x == 42); } { const int i = 42; const int* p = &i; strict_not_null x{p}; static_assert(!HelperCompilesFor>, "!HelperCompilesFor>"); helper_const(strict_not_null{p}); EXPECT_TRUE(*x == 42); } { auto workaround_macro = []() { int* p1 = nullptr; const strict_not_null x{p1}; }; EXPECT_DEATH(workaround_macro(), expected); } { auto workaround_macro = []() { const int* p1 = nullptr; const strict_not_null x{p1}; }; EXPECT_DEATH(workaround_macro(), expected); } { int* p = nullptr; EXPECT_DEATH(helper(strict_not_null{p}), expected); EXPECT_DEATH(helper_const(strict_not_null{p}), expected); } #ifdef CONFIRM_COMPILATION_ERRORS { strict_not_null x{nullptr}; helper(strict_not_null{nullptr}); helper_const(strict_not_null{nullptr}); } #endif } #endif // #if defined(__cplusplus) && (__cplusplus >= 201703L) GSL-4.2.1/tests/utils_tests.cpp000066400000000000000000000101631511561312500163740ustar00rootroot00000000000000/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// #include #include // for move #include #include // for std::ptrdiff_t #include // for uint32_t, int32_t #include // for reference_wrapper, _Bind_helper<>::type #include // for narrow, narrowing_error #include // finally, narrow_cast #include // for numeric_limits #include // for is_same using namespace gsl; namespace { void f(int& i) { i += 1; } static int j = 0; void g() { j += 1; } } // namespace TEST(utils_tests, sanity_check_for_gsl_index_typedef) { static_assert(std::is_same::value, "gsl::index represents wrong arithmetic type"); } TEST(utils_tests, finally_lambda) { int i = 0; { auto _ = finally([&]() { f(i); }); EXPECT_TRUE(i == 0); } EXPECT_TRUE(i == 1); } TEST(utils_tests, finally_lambda_move) { int i = 0; { auto _1 = finally([&]() { f(i); }); { auto _2 = std::move(_1); EXPECT_TRUE(i == 0); } EXPECT_TRUE(i == 1); { auto _2 = std::move(_1); EXPECT_TRUE(i == 1); } EXPECT_TRUE(i == 1); } EXPECT_TRUE(i == 1); } TEST(utils_tests, finally_const_lvalue_lambda) { int i = 0; { const auto const_lvalue_lambda = [&]() { f(i); }; auto _ = finally(const_lvalue_lambda); EXPECT_TRUE(i == 0); } EXPECT_TRUE(i == 1); } TEST(utils_tests, finally_mutable_lvalue_lambda) { int i = 0; { auto mutable_lvalue_lambda = [&]() { f(i); }; auto _ = finally(mutable_lvalue_lambda); EXPECT_TRUE(i == 0); } EXPECT_TRUE(i == 1); } TEST(utils_tests, finally_function_with_bind) { int i = 0; { auto _ = finally([&i] { return f(i); }); EXPECT_TRUE(i == 0); } EXPECT_TRUE(i == 1); } TEST(utils_tests, finally_function_ptr) { j = 0; { auto _ = finally(&g); EXPECT_TRUE(j == 0); } EXPECT_TRUE(j == 1); } TEST(utils_tests, finally_function) { j = 0; { auto _ = finally(g); EXPECT_TRUE(j == 0); } EXPECT_TRUE(j == 1); } TEST(utils_tests, narrow_cast) { int n = 120; char c = narrow_cast(n); EXPECT_TRUE(c == 120); n = 300; unsigned char uc = narrow_cast(n); EXPECT_TRUE(uc == 44); } #ifndef GSL_KERNEL_MODE TEST(utils_tests, narrow) { int n = 120; const char c = narrow(n); EXPECT_TRUE(c == 120); n = 300; EXPECT_THROW(narrow(n), narrowing_error); const auto int32_max = std::numeric_limits::max(); const auto int32_min = std::numeric_limits::min(); EXPECT_TRUE(narrow(int32_t(0)) == 0); EXPECT_TRUE(narrow(int32_t(1)) == 1); EXPECT_TRUE(narrow(int32_max) == static_cast(int32_max)); EXPECT_THROW(narrow(int32_t(-1)), narrowing_error); EXPECT_THROW(narrow(int32_min), narrowing_error); n = -42; EXPECT_THROW(narrow(n), narrowing_error); EXPECT_TRUE( narrow>(std::complex(4, 2)) == std::complex(4, 2)); EXPECT_THROW(narrow>(std::complex(4.2)), narrowing_error); EXPECT_TRUE(narrow(float(1)) == 1); } #endif // GSL_KERNEL_MODE