Compare commits

..

515 Commits

Author SHA1 Message Date
Carson Radtke 0da5eff392 docs: fix false statements in gsl::dyn_array docs
https://github.com/microsoft/GSL/pull/1228 was merged with a handful of
unresolved comments. This PR resolves those comments.
2026-07-13 14:56:33 -06:00
Carson Radtke a75212b9f3 feat: implementation of gsl::dyn_array (#1228)
* feat: implementation of gsl::dyn_array

Implement gsl::dyn_array<T, Allocator> as specified by the
CppCoreGuidlines here:
https://github.com/isocpp/CppCoreGuidelines/blob/master/docs/dyn_array.md

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
2026-07-13 14:53:09 -06:00
Werner Henze b2f6bec48e clang-format improvements (#1251)
* clang-format improvements

- Add a clang-format linter check to the PR pipeline
- Apply clang-format to files where the linter initially failed
- Remove `CommentPragmas` from `.clang-format`
- Remove all `// clang-format off` and `// NO-FORMAT` as they are not needed
- Remove a commented out `GSL_SUPPRESS`

* clang-format 20

* pipeline fail

* Update .github/workflows/clang-format.yml

Co-authored-by: Carson Radtke <nosrac925@gmail.com>

* output used clang-format version

* installed version is 18 which replaces "GSL_SUPPRESS(bounds.1)" with "GSL_SUPPRESS(bounds .1)"

* only include/gsl, not include

to prevent formatting of include/CMakeLists.txt

* apply clang-format[-20]

In a VS2026 developer command prompt I ran `clang-format -i include\gsl\* --assume-filename x.cpp`. This was necessary because VS GUI does not format files without an extension :(. Please note that `--assume-filename` is necessary here, otherwise the files will not be formatted. Surprisingly the behaviour for the formatter differs from the behaviour of `lang-format(-20) --dry-run --Werror include/gsl/*` where clang-format recognizes that the files is C++.

* change "#if 0" back to original version with comments only

* formatting scripts for windows and linux

for linux with linter (shfmt and shellcheck)

* add WhitespaceSensitiveMacros: [GSL_SUPPRESS]

* provide path for clang-format (Windows)

Currently not clear to me:
On my personal computer at home, when I start "Developer Command Prompt for VS18", I can run `clang-format` without providing the path.
On my managed (domain) company computer, when I start "Developer Command Prompt for VS18", I can NOT run `clang-format` without providing the path. I need to call `"%VCINSTALLDIR%Tools\Llvm\bin\clang-format"`.
I have no idea what the difference is. At least the version `"%VCINSTALLDIR%Tools\Llvm\bin\clang-format"` works on both computers, so I add the path.

---------

Co-authored-by: Werner Henze <w.henze@avm.de>
Co-authored-by: Carson Radtke <nosrac925@gmail.com>
Co-authored-by: Werner Henze <werner.henze+gitcommits@posteo.de>
2026-06-05 06:45:10 -06:00
Werner Henze f3c5967126 remove space in GSL_SUPPRESS (#1248)
As VS2026 wants a string literal in `[[gsl::suppress(...)]]` it is a difference, if you `GSL_SUPPRESS(a.1)` without space or `GSL_SUPPRESS(a .1)` with space. The version with the space does not work, so this commit removes the spaces.

Co-authored-by: Werner Henze <werner.henze+gitcommits@posteo.de>
2026-05-27 12:04:16 -06:00
maflcko 4524208d32 ci: Bump actions/setup-java@v5 (#1249)
Co-authored-by: MarcoFalke <*~=`'#}+{/-|&$^_@721217.xyz>
2026-05-27 11:15:45 -06:00
Werner Henze 66ca39d9c8 narrow_cast instead of static_cast (#1250)
This removes the "warning C26472: Don't use a static_cast for arithmetic conversions. Use brace initialization, gsl::narrow_cast or gsl::narrow (type.1)." issued by VS2026.

Co-authored-by: Werner Henze <w.henze@avm.de>
2026-05-27 11:15:07 -06:00
maflcko 0249144ad1 ci: Use microsoft/setup-msbuild@v3 (#1240)
Co-authored-by: MarcoFalke <*~=`'#}+{/-|&$^_@721217.xyz>
2026-03-24 11:59:58 -06:00
maflcko 688ffcde90 ci: Bump to actions/checkout@v6 (#1237)
Co-authored-by: MarcoFalke <*~=`'#}+{/-|&$^_@721217.xyz>
2026-03-23 12:23:07 -06:00
maflcko fcf3fe37c6 gsl::not_null: C.89: Make a hash noexcept (#1236)
Without this change, the guideline
https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#c89-make-a-hash-noexcept
would be violated.

The test fails before the changes here:

```
tests/pointers_tests.cpp:102:23: error: static assertion failed due to requirement 'noexcept(std::hash<gsl::not_null<std::shared_ptr<int>>>{}(std::declval()))': gsl::not_null hash operator must be noexcept
  102 |         static_assert(noexcept(std::hash<Key>{}(std::declval<Key>())),
      |                       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
tests/pointers_tests.cpp:108:23: error: static assertion failed due to requirement 'noexcept(std::hash<gsl::strict_not_null<std::shared_ptr<int>>>{}(std::declval()))': gsl::strict_not_null hash operator must be noexcept
  108 |         static_assert(noexcept(std::hash<Key>{}(std::declval<Key>())),
      |                       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Co-authored-by: MarcoFalke <*~=`'#}+{/-|&$^_@721217.xyz>
2026-03-23 12:18:30 -06:00
maflcko 9f9f65c7e2 Mark gsl::not_null swap noexcept (#1235)
Co-authored-by: MarcoFalke <*~=`'#}+{/-|&$^_@721217.xyz>
2026-03-23 12:16:36 -06:00
maflcko 5ca9c77666 doc: Fix to use lower-case anchors in links to C++ Core Guidelines (#1234)
Co-authored-by: MarcoFalke <*~=`'#}+{/-|&$^_@721217.xyz>
2026-03-20 07:38:12 -06:00
maflcko bf9d5e1aef doc: Update URL in pointers to F.16 C++ Core Guidelines (#1232)
The anchor ID in the target is now lower-case.
2026-03-18 10:14:34 -06:00
Carson Radtke 756c91ab89 infra: individual test executables (#1212)
* infra: individual test executables

We used have tests contained in a single executable. This was fine for
testing, but it would be more convient to separate tests into indivudal
modules so targeted changes could have targeted tests.

This change associates each test file with its own executable. We now
have 14 tests for GSL each of which testing a different component.

* revert -Wno-reserved-identifier

* Update tests/span_tests.cpp

thanks copilot

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* be sure to include build type in ctest command

* [VS] make sure we are building the correct configuration

* restore tests/span_tests.cpp

* fix build break after merge conflicts

* fix build break after merge conflicts #2

* another try at fixing a build break

* fix silly typo. build break pt 4

* Use file globbing for test sources instead of manual list (#1227)

* Initial plan

* Use file globbing for test sources instead of manual list

Replace the manually maintained list of test sources with file(GLOB) to
automatically discover all .cpp files in the tests directory, excluding
no_exception_ensure_tests.cpp which needs special compilation flags.

This approach:
- Automatically picks up new test files without CMake updates
- Still correctly excludes no_exception_ensure_tests.cpp
- Maintains the same test build configuration
- Works with both C++14 and C++20

Co-authored-by: carsonRadtke <10507970+carsonRadtke@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: carsonRadtke <10507970+carsonRadtke@users.noreply.github.com>

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com>
2025-12-05 13:24:15 -07:00
Copilot 1883887359 Fix std::hash compilation error for gsl::not_null<std::shared_ptr<T>> (#1210)
* Initial plan for issue

* Fix hash compilation issue for gsl::not_null with shared_ptr

Co-authored-by: carsonRadtke <10507970+carsonRadtke@users.noreply.github.com>

* Add comment explaining safe usage of typename T::element_type in not_null_hash

Co-authored-by: carsonRadtke <10507970+carsonRadtke@users.noreply.github.com>

* Initial plan for issue

* Remove upgrade_checklist.md file as requested

Co-authored-by: carsonRadtke <10507970+carsonRadtke@users.noreply.github.com>

* restore docs/upgrade_checklist.md

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: carsonRadtke <10507970+carsonRadtke@users.noreply.github.com>
Co-authored-by: Carson Radtke <carsonradtke@microsoft.com>
2025-12-05 10:00:06 -07:00
Carson Radtke c31617f56a use cmake presets instead of cmake settings (#1219)
* use cmake presets instead of cmake settings

This change uses a cmake presets file in an effort allow for agentic AI
to better switch between project settings. It replaces the old
CMakeSettings.json for the more flexible CMakePresets.json.

* Update GitHub Actions workflows to use CMake presets (#1223)

* Initial plan

* Update GitHub Actions to use CMake presets for compilers workflow

Co-authored-by: carsonRadtke <10507970+carsonRadtke@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: carsonRadtke <10507970+carsonRadtke@users.noreply.github.com>

* remove unused cmake options

* address PR feedback from copilot

* fix build break

---------

Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com>
2025-12-05 09:59:18 -07:00
Werner Henze 4fb59125d1 Revert unintended change to GSL_SUPPRESS (#1226)
PR #1213 changed this line. According to https://github.com/microsoft/GSL/pull/1213/files#r2586073058 the change was unintended. This PR reverts the change to the previous implementation.

Co-authored-by: Werner Henze <w.henze@avm.de>
2025-12-04 12:44:26 -07:00
Carson Radtke 543d0dd3fe export proper syntax for GSL_SUPPRESS for new VS (#1213)
A new Visual Studio version will soon be available that deprecates the
old syntax for gsl::suppress. Customers will now get a C4875 diagnostic
on suppressions that look like `gsl::suppress(x)` urging them to use
`gsl::suppress("x")` instead.

This change updates the `GSL_SUPPRESS` macro to preprocess
GSL_SUPPRESS(x) to gsl::suppress("x") on clang and new versions of MSVC.
2025-10-02 08:47:16 -06:00
Carson Radtke 494e6e988c fix: all pipeline failures (#1221)
* fix: update conditional static assertion
There is a static assertion that spuriously fails on MSVC that was
version checked. Unfortunately it fires every time there is a new
compiler update, so for now we will remove the version check and add it
back once the compiler bug is fixed.

* fix: ios pipeline failure

Looks like somewhere along the line, the iOS simulator changed the range
of support iOS versions. This changes bumps the version from 9 to 12.0.

Also noticed that the GSL OSX bundle version was quite out of date. I
bumped this from 3.1.0 to 4.2.0 and created an upgrade checklist file in
docs/ so we don't forget these types of tasks in the future.

* bump xcode version from 15.4 to 16.4

* fix compiler warning when building gtest for ios

* allow for missing include dirs on command line

* replace windows-2019 with windows-2025

* update visual studio versions after runner bump

* PR feedback: make sure markdown links are syntactically correct
2025-09-30 15:10:46 -06:00
Copilot 7e0943d20d Add constexpr to not_null comparison operators (#1208)
* Initial plan for issue

* Add test and plan to make not_null comparison functions constexpr

Co-authored-by: carsonRadtke <10507970+carsonRadtke@users.noreply.github.com>

* Add constexpr to not_null comparison operators

Co-authored-by: carsonRadtke <10507970+carsonRadtke@users.noreply.github.com>

* Fix copyright year in constexpr_notnull_tests.cpp

Co-authored-by: carsonRadtke <10507970+carsonRadtke@users.noreply.github.com>

* Fix constexpr tests for better compiler compatibility

Co-authored-by: carsonRadtke <10507970+carsonRadtke@users.noreply.github.com>

* Remove build artifacts and update .gitignore

Co-authored-by: carsonRadtke <10507970+carsonRadtke@users.noreply.github.com>

* Fix constexpr tests to be compatible with more compilers

Co-authored-by: carsonRadtke <10507970+carsonRadtke@users.noreply.github.com>

* copilot: Provide more project context for the Copilot coding agent (#1207)

* copilot: create .github/copilot-instructions.md

This file provides additional context and instructions to GitHub
Copilot so it can better understand the codebase and coding conventions.

More can be found about this file at the following links:
 - [Best practices for using Copilot to work on tasks](https://docs.github.com/en/enterprise-cloud@latest/copilot/using-github-copilot/using-copilot-coding-agent-to-work-on-tasks/best-practices-for-using-copilot-to-work-on-taskshttps://docs.github.com/en/enterprise-cloud@latest/copilot/using-github-copilot/using-copilot-coding-agent-to-work-on-tasks/best-practices-for-using-copilot-to-work-on-tasks)
 - [Adding repository custom instructions for GitHub Copilot](https://docs.github.com/en/enterprise-cloud@latest/copilot/customizing-copilot/adding-repository-custom-instructions-for-github-copilot?tool=webuihttps://docs.github.com/en/enterprise-cloud@latest/copilot/customizing-copilot/adding-repository-custom-instructions-for-github-copilot)

* copilot: add copilot-setup-steps.yml

This new workflow is done when copilot loads into an environment and
enables copilot to be sure it has the proper dependencies before working
on changes. Also included in the change are explicit instructions on
what to do before reporting back "done".

* Initial plan for issue

* Rebase onto main and verify changes meet project guidelines

Co-authored-by: carsonRadtke <10507970+carsonRadtke@users.noreply.github.com>

* Update .gitignore to exclude build-cxx* directories

Co-authored-by: carsonRadtke <10507970+carsonRadtke@users.noreply.github.com>

* Fix newline at end of constexpr_notnull_tests.cpp and update .gitignore

Co-authored-by: carsonRadtke <10507970+carsonRadtke@users.noreply.github.com>

* Remove C++14 feature check that is redundant since C++14 is the minimum supported standard

Co-authored-by: carsonRadtke <10507970+carsonRadtke@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: carsonRadtke <10507970+carsonRadtke@users.noreply.github.com>
Co-authored-by: Carson Radtke <carsonradtke@microsoft.com>
2025-05-22 11:52:47 -06:00
Copilot 2d343b0440 Document differences between hardened std::span and gsl::span (#1206)
* Initial plan for issue

* Document differences between hardened std::span and gsl::span

Co-authored-by: carsonRadtke <10507970+carsonRadtke@users.noreply.github.com>

* Simplify documentation for span differences

Co-authored-by: carsonRadtke <10507970+carsonRadtke@users.noreply.github.com>

* Enhance span documentation with comparison table and links

Co-authored-by: carsonRadtke <10507970+carsonRadtke@users.noreply.github.com>

* Fix library hardening documentation links

Co-authored-by: carsonRadtke <10507970+carsonRadtke@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: carsonRadtke <10507970+carsonRadtke@users.noreply.github.com>
2025-05-22 11:34:22 -06:00
Carson Radtke c21970972b copilot: Provide more project context for the Copilot coding agent (#1207)
* copilot: create .github/copilot-instructions.md

This file provides additional context and instructions to GitHub
Copilot so it can better understand the codebase and coding conventions.

More can be found about this file at the following links:
 - [Best practices for using Copilot to work on tasks](https://docs.github.com/en/enterprise-cloud@latest/copilot/using-github-copilot/using-copilot-coding-agent-to-work-on-tasks/best-practices-for-using-copilot-to-work-on-taskshttps://docs.github.com/en/enterprise-cloud@latest/copilot/using-github-copilot/using-copilot-coding-agent-to-work-on-tasks/best-practices-for-using-copilot-to-work-on-tasks)
 - [Adding repository custom instructions for GitHub Copilot](https://docs.github.com/en/enterprise-cloud@latest/copilot/customizing-copilot/adding-repository-custom-instructions-for-github-copilot?tool=webuihttps://docs.github.com/en/enterprise-cloud@latest/copilot/customizing-copilot/adding-repository-custom-instructions-for-github-copilot)

* copilot: add copilot-setup-steps.yml

This new workflow is done when copilot loads into an environment and
enables copilot to be sure it has the proper dependencies before working
on changes. Also included in the change are explicit instructions on
what to do before reporting back "done".
2025-05-22 10:32:01 -06:00
ozaktash 466e4ebaa5 Update return by value threshold in gsl::not_null (#1205)
- Allow returning by value for types that are not greater than two pointers in size
2025-05-12 11:02:03 -06:00
Werner Henze 3325bbd33d Fix version info (#1202)
Just tagging as 4.2.0 is not enough, the version number must be incremented for cmake and in the readme. Compare https://github.com/microsoft/GSL/pull/1163.

Co-authored-by: Werner Henze <w.henze@avm.de>
2025-03-27 11:00:24 -05:00
Werner Henze 2828399820 replace BYTE_TYPE with a solution based on namespaces (#1201)
- A macro with the very generic name `BYTE_TYPE` is likely to collide with existing code, so get rid of the macro.
- The new solution is to provide a non-deprecated `byte` in the namespace `gsl::impl`.
  - Users of GSL should use `gsl::byte`, which is still deprecated when mapped to a `std::std::byte`.
  - GSL types and functions need to use `gsl::impl::byte` so they do not trigger the deprecation warning.
- The `gsl::impl::byte` return type in an exported function is not nice, it might mislead users to use that type in their own declarations. But the `BYTE_TYPE` solution is not better in this respect.

Co-authored-by: Werner Henze <w.henze@avm.de>
2025-02-28 08:53:25 -06:00
Werner Henze c5fbb81ad4 documentation (#1200)
- reintroduce documentation internal links
- remove `gsl::` prefix in table so it is the same as in the other tables
- fix documentation for span::element_type

Co-authored-by: Werner Henze <w.henze@avm.de>
2025-02-28 08:49:53 -06:00
Carson Radtke 7fabaa499d deprecate features adopted into C++ (#1198)
* deprecated features adopted into C++

1) Mark the following GSL features as deprecated:
 - gsl::unique_ptr (always)
 - gsl::shared_ptr (always)
 - gsl::byte (since c++17)
 - gsl::joining_thread (never implemented)
2) Refactor existing deprecations to use the new GSL_DEPRECATED(msg) macro.
3) Create a section in the README for deprecated features in the
   standard.

* do not deprecate gsl::to_integer because we never claim to implement it.

* do not use gsl::byte if it is deprecated
2025-02-14 11:24:51 -06:00
Carson Radtke 4742bc192a use relative path in # include (#1194)
Reverts commit that changes #include "assert" -> #include "gsl/assert".
This change is necessary in order to comply with CppCoreGuideline's
SF.12. Now we do #include "./assert".
2025-02-12 09:16:45 -06:00
Carson Radtke ec729d63a7 introduce gsl::not_null<T>::element_type (#1196)
* introduce gsl::not_null<T>::element_type

* use std::is_same instead of is_same_v

* fix: cannot put a non-pointer in a gsl::not_null
2025-02-12 09:16:05 -06:00
Carson Radtke 7f4fc9388b Add more gsl::span tests [copilot] (#1189)
* Add more gsl::span tests [copilot]

This PR adds comprehensive unit tests for `gsl::span` to ensure its correctness and consistency. The following tests have been added:

1. **Empty Span Tests**:
   - Tests to verify the behavior of an empty `gsl::span` and `gsl::span<const int>`.

2. **Conversion Tests**:
   - Tests to check the conversion between different types of `gsl::span`.

3. **Comparison Operator Tests**:
   - Tests to verify the comparison operators for `gsl::span`.

4. **Deduction Guide Tests**:
   - Tests to compare the behavior of `gsl::span` and `std::span` deduction guides for various types of arrays and containers.

These tests help ensure that `gsl::span` behaves correctly in various scenarios and is consistent with `std::span`.

This PR was created with the help of GitHub Copilot.

**Changes**:
- Added tests for empty span.
- Added tests for conversions.
- Added tests for comparison operators.
- Added tests for deduction guides.

**Testing**:
- All new tests have been added to the existing test suite.
- Run the test suite using `ctest` to ensure all tests pass.This PR adds comprehensive unit tests for `gsl::span` to ensure its correctness and consistency. The following tests have been added:

1. **Empty Span Tests**:
   - Tests to verify the behavior of an empty `gsl::span` and `gsl::span<const int>`.

2. **Conversion Tests**:
   - Tests to check the conversion between different types of `gsl::span`.

3. **Comparison Operator Tests**:
   - Tests to verify the comparison operators for `gsl::span`.

4. **Deduction Guide Tests**:
   - Tests to compare the behavior of `gsl::span` and `std::span` deduction guides for various types of arrays and containers.

These tests help ensure that `gsl::span` behaves correctly in various scenarios and is consistent with `std::span`.

This PR was created with the help of GitHub Copilot.

**Changes**:
- Added tests for empty span.
- Added tests for conversions.
- Added tests for comparison operators.
- Added tests for deduction guides.

**Testing**:
- All new tests have been added to the existing test suite.
- Run the test suite using `ctest` to ensure all tests pass.

* fix tests for pre-C++17
2025-02-12 09:15:43 -06:00
Tiago 355982daf6 Delete gsl/string_span (#1185)
This has been deprecated for 2+ years.
2025-01-07 08:58:59 -06:00
Werner Henze 50aaf2efbb remove documentation for deprecated make_span overloads (#1183)
Co-authored-by: Werner Henze <werner.henze+gitcommits@posteo.de>
2025-01-07 08:50:49 -06:00
Tiago 7b6b8013b1 Add "gsl" to #includes (#1184)
Office is seeing build breaks due to `#include "span"` including
C++20 span instead of gsl/span. Most likely we want all headers
includes qualified with "gsl/" to avoid similar issues.
2025-01-07 08:42:38 -06:00
Werner Henze 1cdb8d295e More checks for non-compilable code, plus fix for span (#1180) 2025-01-04 11:50:31 -06:00
Carson Radtke c832885f15 React to ubuntu-latest changing to 24.04 (#1181)
* React to ubuntu-latest changing to 24.04
Reacting to https://github.com/actions/runner-images/issues/10636
* update clang to 16,17,18
* update gcc to 12,13,14
2025-01-03 10:23:50 -06:00
Werner Henze 16a60199df strict_not_null for unique_ptr (#1179)
- `strict_not_null<std::unique_ptr<int>>{ std::make_unique<int>()}` failed to compile
  - `strict_not_null` ctor needs to move the passed `unique_ptr`, not copy
  - Copied `not_null` `TestNotNullConstructors` for `strict_not_null`
- The `noexcept` specifiers on the `strict_not_null` and `not_null` constructors were out of sync.
- Added unit test for `not_null<unique_ptr<T>>` and for `strict_not_null<unique_ptr<T>>`
- Added unit test for `gsl::swap` for two `strict_not_null`
- Added unit test for `gsl::swap` for `not_null` and `strict_not_null`

Co-authored-by: Werner Henze <w.henze@avm.de>
2024-12-26 11:00:36 -06:00
Werner Henze fcd55ee924 Better use of std::enable_if (#1177)
* this commits adds tests that should fail, but don't

* Better use of std::enable_if

Replace the occurances of `class = std::enable_if_t<Cond>` and `typename = std::enable_if_t<Cond>` that have been identified in the previous commit with `std::enable_if_t<Cond, bool> = true`.

This commit is inspired by #1174, which changed one occurance in the owner header. This commit is aimed to fix all remaining occurances.

* fix failing checks

- core.cxx_gsl aktualisiert auf [](https://gitlab.avm.de/fos/repos/core.cxx_gsl/-/commit/)
- plc.access_lib aktualisiert auf [](https://gitlab.avm.de/fos/repos/plc.access_lib/-/commit/)
- plc.common aktualisiert auf [](https://gitlab.avm.de/fos/repos/plc.common/-/commit/)
- plc.daemon aktualisiert auf [](https://gitlab.avm.de/fos/repos/plc.daemon/-/commit/)
-

Test Plan:
-

---------

Co-authored-by: Werner Henze <werner.henze+gitcommits@posteo.de>
Co-authored-by: Werner Henze <w.henze@avm.de>
2024-12-23 10:40:22 -06:00
Werner Henze b8ac820fe1 Force unit tests for byte to use GSL implementation (#1176)
When setting `GSL_USE_STD_BYTE` to zero, then the unit test does not compile because `byte` is ambiguous (could be `std::byte` or `gsl::byte`). So `gsl::` prefix is needed for `byte`.
It looks like the unit tests never ran on a platform where `gsl::byte` is not based on `std::byte`.
It does not make much sense to test `std::byte` for compliance, so make the unit tests based on the GSL implementation of `gsl::byte` (`#define GSL_USE_STD_BYTE 0`).

Co-authored-by: Werner Henze <werner.henze+gitcommits@posteo.de>
2024-12-18 10:16:36 -06:00
Carson Radtke 272463043e introduce gsl::swap for swapping gsl::not_null (#1160)
fixes: https://github.com/microsoft/GSL/issues/1129

* create gsl::swap<T>(T&, T&) which wraps std::swap
* specialize gsl::swap<T>(gsl::not_null<T>&, gsl::not_null<T>&)
* add tests
2024-12-13 15:16:53 -06:00
Carson Radtke 8a0e3d8a9b fix: direct-init const ref instead of list-init (#1175)
fixes: https://github.com/microsoft/GSL/issues/1162

gcc has a bug that generates a call to the copy constructor when list
initializing a const reference. This PR offers a workaround which is to
direct initialize the value.

see: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=117900
2024-12-13 10:22:16 -06:00
Alberto La Rocca aed09c41b6 Fix SFINAE on gsl::owner. (#1174)
`std::enable_if_t` must not be used as a default template argument, otherwise the instantiator will be able to override it freely with something that doesn't fail substitution. Instead, `std::enable_if_t` itself must be the type of the template argument.

More information in the examples here: https://en.cppreference.com/w/cpp/types/enable_if
2024-12-13 09:56:28 -06:00
Carson Radtke 4b190d2e2a Create issue templates (#1173) 2024-12-02 14:34:38 -06:00
Carson Radtke ddae9d72b6 fix stale badge links in README (#1170)
* update pipeline badge links
* add link to compilers pipeline
* add badge to vcpkg version
2024-11-25 13:06:02 -06:00
Carson Radtke 74d2bb79d4 fix various pipeline failures (#1172)
* fix failing pipeline tests
* upgrade to googletest v1.14.0 so it works with newer cmake versions
* fix android pipeline to permit new cmake versions (short-term fix)
2024-11-25 12:58:45 -06:00
Carson Radtke f8ec309118 improve performance of span_iterator w/ clang (#1166)
* improve performance of span_iterator w/ clang

Issue: #1165

Before this PR, the range-for loop was ~3300x slower. After this PR, it
is ~1.005x slower

The clang optimizer is very good at optimizing `current != end`, so
we changed to this idiom. This moves the Expects assertion into the
constructor instead of on the hot-path which is called whenever either
operator++ or operator* is called.

Note: The codegen for the assertion is still a missed optimization,
but less worrisome as it only happens once per iterator.

Note: benchmarks on M1 Macbook Pro w/ Apple Clang 16.0.0
2024-11-12 15:41:21 -06:00
Carson Radtke 87f9d76886 GSL v4.1.0 (#1163)
Fixes: #1161

Update version strings in README and CMakeLists.txt.
2024-10-21 10:19:37 -05:00
Heiko Kröger 82ba6c77ce Added the IWYU pragma export (#1154)
* Added the IWYU pragma export

clang-tidy has added the check misc-include-cleaner with version 17. This check respects the IWYU pragmas.
2024-10-15 17:26:45 -05:00
mq白 32511b8de4 Delete the useless 'noexcept(false)' (#1152) 2024-10-14 15:30:40 -05:00
Konstantin Akimov 84b2ca1352 Remove unused headers from gsl/pointers (#1153)
* Remove unused headers from gsl/pointers

forward is already declared in utility, no need to include algorithm which is relativaly heavy
hash is already declared in memory, no need to bring brand-new header system_error for hash only

* Fix: add missing header <functional> to gsl/pointers due to using less/greater
2024-10-14 15:15:46 -05:00
Carson Radtke ce2a959e02 [ci]: add testing pipelines to github actions (#1159)
move pipeline testing from AzDO to GitHub Actions.

* update clang versions to 13-15
* update gcc versions to 10-12
* update xcode versions to 14.3.1 and 15.4
* test against C++23 (where supported)
2024-10-14 15:05:13 -05:00
Brian Kroth 11fe02d1ac Add a MS GSL disambiguation note (#1156) 2024-10-14 09:43:43 -05:00
Werner Henze 3275f9ccb9 Fix gcc build problem (#1149)
Closes issue #1148 by fixing problems introduced in PR #1140.

Co-authored-by: Werner Henze <w.henze@avm.de>
2024-10-11 19:46:21 -05:00
Carson Radtke b206bd163b [ci]: fix android job (#1158)
Job has been failing for months and is preventing other PRs from getting
merged. This PR fixes the pipeline - it changed the following:
 - runs on macos-latest-large (which is a non-arm image)
 - starts the emulator under java8 (see
   https://learn.microsoft.com/en-us/java/openjdk/transition-from-java-8-to-java-11)
 - runs emulator with -no-audio

The above were requirements to get the pipeline running. Other changes
include the following:
 - The job will auto-cancel when a newer commit is pushed to the
 PR.
 - The 'Wait for emulator ready' step now has a 2 minute timeout. This
   is necessary because we get no indication on whether or not the
   command that started the emulator suceeded. I believe there is room
   for improvement here, but it is outside the scope of the PR.
2024-10-11 16:05:20 -07:00
Werner Henze b39e7e4b09 Add documentation for to_integer(byte) (#1144)
Co-authored-by: Werner Henze <w.henze@avm.de>
2024-02-26 13:23:45 -08:00
Stephan T. Lavavej 2e0d1ba48c Test only __cpp_lib_byte, drop _HAS_STD_BYTE. (#1145) 2024-02-26 13:22:20 -08:00
d-winsor 1b4d42ca2e Fix initialization in test (#1140)
* Suppress unsafe-buffer-usage
2024-02-26 13:17:12 -08:00
Bruce Mitchener caae4dd0f8 Fix some typos. (#1146) 2024-02-21 15:06:29 -08:00
Bruce Mitchener f1a494cfd2 ci: Update to actions/checkout@v4. (#1142)
This fixes annotations on task runs like the following:

    The following actions uses node12 which is deprecated and will be forced
    to run on node16: actions/checkout@v2. For more info:
    https://github.blog/changelog/2023-06-13-github-actions-all-actions-will-run-on-node16-instead-of-node12-by-default/
2024-01-17 15:25:32 -08:00
Bruce Mitchener 77b2f4f3b8 Fix some typos. (#1143) 2024-01-17 15:25:07 -08:00
Nicholas Guriev e64c97fc2c Mark not_null constructors as noexcept when underlying type can be moved with no exception (#1135)
This enables possible optimisations for trivial types. This also avoids a bug
in std::variant::emplace from GNU's libstdc++.

https://gcc.gnu.org/bugzilla/show_bug.cgi?id=106547
2023-10-18 15:15:26 -07:00
Edward Chen 52212c2d76 Update Clang GSL_SUPPRESS to stringize parameter instead of using fixed string literal. (#1133)
Fix #1130.
2023-09-11 10:52:30 -07:00
Dmitry Kobets 2940006b5c Suppress some noisy / buggy warnings (#1136)
Two warnings were being emitted in the MSVC+LLVM tests. 

The warning `-Wunsafe-buffer-usage` is initially introduced in some capacity here https://reviews.llvm.org/D137346 pointing to documentation at https://discourse.llvm.org/t/rfc-c-buffer-hardening/65734. The warning is a stylistic checker whose goal is to "emit a warning every time an unsafe operation is performed on a raw pointer". This type of programming model is not useful for library implementations of types such as `span`, where direct manipulation of raw pointers is inevitable, so disable the warning altogether.

There is also a false-positive warning https://github.com/llvm/llvm-project/issues/65689 that I've disabled inline.
2023-09-11 10:06:40 -07:00
Werner Henze 9695da9b38 fix and optimize documentation (#1131)
- Add anchor for `finally` in `headers.md` so that the link in `README.md` can work
- In `README.md` add code formatting for the character types of the `zstring` and `string_span` types
- In `README.md` change code formatting to links for GSL types
- Vertical alignment
2023-09-05 16:08:36 -07:00
Dmitry Kobets 4300304ef2 Remove unused macros (#1128)
This macro is a relic of the old implementation of GSL's header. It is unused and can be removed.
2023-07-26 15:07:28 -07:00
Werner Henze b34f7350fe get back gcc 8.4 compatibility (#1127)
Before my PR #1122 `gsl/pointers` was gcc 8.4 compatible. Now it is not. This commit makes it compatible with gcc 8.4 again.
2023-07-06 12:51:48 -07:00
Werner Henze 167c77d28e add missing include (#1126)
The header file uses `std::declval`, so it needs to `#include <utility>`.
2023-07-03 17:20:50 -07:00
Werner Henze 87e21400dc remove gcc noexcept warning (#1122)
Without this change a `gsl::not_null<class_type>` triggers these `noexcept` warnings:
```
.../gsl/include/gsl/pointers:162:50: warning: noexcept-expression evaluates to ‘false’ because of a call to ‘constexpr gsl::details::value_or_reference_return_t<T> gsl::not_null<T>::get() const [with T = class_type*; gsl::details::value_or_reference_return_t<T> = class_type* const]’ [-Wnoexcept]
  162 |                 const not_null<U>& rhs) noexcept(noexcept(lhs.get() == rhs.get()))
      |                                                  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.../gsl/include/gsl/pointers:119:55: note: but ‘constexpr gsl::details::value_or_reference_return_t<T> gsl::not_null<T>::get() const [with T = class_type*; gsl::details::value_or_reference_return_t<T> = class_type* const]’ does not throw; perhaps it should be declared ‘noexcept’
  119 |     constexpr details::value_or_reference_return_t<T> get() const
      |                                                       ^~~
```

Co-authored-by: Werner Henze <w.henze@avm.de>
2023-06-28 15:17:12 -07:00
Dmitry Kobets 3549e31ba4 Deprecate <gsl/string_span> and replace with <gsl/zstring> (#1125)
With `string_span` having been deprecated (https://github.com/microsoft/GSL/pull/931, https://github.com/microsoft/GSL/pull/945) and removed (https://github.com/microsoft/GSL/pull/1074), the header `<gsl/string_span>` now only contains the definitions for the `zstring` family. Update the name accordingly from `<gsl/string_span>` to `<gsl/zstring>`. The old header is now deprecated and should no longer be used and will be removed in some future release.
2023-06-28 10:48:23 -07:00
Dmitry Kobets 65a5995035 Remove deprecated headers (#1124)
Headers that were previously prefixed with `gsl_` were renamed to drop the `gsl_` prefix in https://github.com/microsoft/GSL/pull/946, and the original version deprecated.
The deprecation happened a long time ago, so it is now time to remove these headers entirely.
2023-06-28 10:48:04 -07:00
Dmitry Kobets 303d964a24 Deprecate the Ptr make_span overloads (#1113)
These overloads don't seem to be in a usable state, and their original purpose is no longer clear. Deprecate them.
Resolves #1092
2023-05-22 10:48:41 -07:00
jpr42 afaaa71bce Install GSL.natvis (#1112)
Turns out supporting GSL.natvis perfectly is quite difficult.

There is no universal way to consume .natvis files that would satisfy everyone.

I thought the solution was to use the /NATVIS linker option. But it turns out that actually embeds information into the PDB. So I'm not sure how to properly support the Ninja generator...

That's not even accounting for the fact target_link_options doesn't play nicely with /NATVIS

When you just add the file via target_sources the visual studio solution will just pick it up and recognize it without adding it to the PDB file. Which won't affect the binary and is what most devs want.

This all comes down to the fact that /NATVIS files have native integration with visual studio that makes it difficult to use with non-visual studio solutions. /NATVIS almost works but embeds itself into the PDB which not everyone wants, and not everyone generates PDBs either.

Docs for natvis files and /NATVIS
- https://learn.microsoft.com/en-us/visualstudio/debugger/create-custom-views-of-native-objects?view=vs-2022
- https://learn.microsoft.com/en-us/cpp/build/reference/natvis-add-natvis-to-pdb?view=msvc-170

So my current solution is to just simplify the existing CMake code, and install the natvis so the user can decide.

closes #1084
2023-05-10 17:02:44 -07:00
Dmitry Kobets 4b5b5a1ed5 Disable std::hash<gsl::not_null<T>> if std::hash<T> is not enabled. (#1109)
Resolves #914
2023-05-10 11:25:04 -07:00
Dmitry Kobets 5dc7fae119 Use the implementation-defined strict total order for pointer comparisons with not_null (#1106)
Using `<`,`<=`,`>`,`>=` to compare unrelated pointers gives an unspecified result according to the standard.
This PR replaces the usage of these operators in `gsl::not_null` with the STL counterparts, which would leverage any implementation-defined strict total ordering for pointers.

Resolves #880
2023-05-09 09:06:53 -07:00
Dmitry Kobets 9face82309 Remove unnecessary check from size_bytes() (#1105)
`size_bytes()` returns the span's size in bytes. 
Assuming the span was constructed with an accurate size parameter, the check `size() < dynamic_extent / sizeof(element_type)` isn't required, since `size_t(-1)` (which is `dynamic_extent`) represents the size of the address space, so the number of bytes will never exceed it and in practice won't even come close.
Otherwise, it is not actually feasible to detect cases when the size parameter does not correspond to the dimensions of the underlying data pointer. In these cases, the relationship `size() < dynamic_extent / sizeof(element_type)` is simply one of many ways in which the `size()` could be incorrect, and serves no necessary purpose.

Resolves #1012
2023-05-09 09:05:26 -07:00
Dmitry Kobets 1d036585cc Add testcase for #1100 (#1101) 2023-03-30 11:10:15 -07:00
Werner Henze 43d60c5e38 Suppress warning C26481 (#1099)
Suppress "warning C26481: Don't use pointer arithmetic. Use span instead (bounds.1)." in the code that impements `span`.
2023-03-14 16:57:46 -07:00
Stephan T. Lavavej 50d6eef541 Add span_iterator::_Prevent_inheriting_unwrap. (#1100) 2023-03-14 13:50:34 -07:00
dmitrykobets-msft b080081c9c Add missing link to documentation 2023-02-27 15:49:09 -08:00
Werner Henze 9f85e4e088 minor docs improvements (#1097)
- Capitalize inital letter (make both tables consistent)
- Add links to docs/headers.md
- Latest cmake requirement is 3.14
- Mark text as code
2023-02-23 11:10:19 -08:00
dmitrykobets-msft 78eb6ca145 Document span_ext (#1098)
`<gsl/span>` is intended to mirror `<span>` in the STL. `<span_ext>` provides convenience features that aren't part of `<span>`.
Address #1095
2023-02-23 10:22:02 -08:00
Werner Henze 7f7108a076 Better links to CoreGuidelines (#1094)
The `#i13-do-not-pass-an-array-as-a-single-pointer` anchor seems to be auto generated based on the title of the section. The `#Ri-array` anchor is explicitely written in the source, so this should be a better link.
2023-02-21 17:11:30 -08:00
Werner Henze 7a297d4283 Extend docs and tests for span ctor (#1096) 2023-02-21 15:46:40 -08:00
Werner Henze 9851b94d7e add some span test for constructor from other span (#1093)
More combinations with dynamic_extent or fixed extent for higher coverage.
2023-02-17 13:05:40 -08:00
Werner Henze 743939744c Documentation (#1086)
Add documentation for #1071.
2023-02-17 10:38:34 -08:00
Werner Henze 3ba80d5dd4 simplify to_byte (#1090)
- to_byte_impl is not necessary, the same can be achieved with shorter code
- add test code for things that should not compile
2023-02-14 14:10:56 -08:00
Werner Henze 49c88f27bd add not_null and strict_not_null tests for const (#1085) 2023-02-06 13:16:06 -08:00
jpr42 f7da2e41f0 Raise CMake min to 3.14 (#1083)
- Explicitly test package manager support with CMake 3.14 and Ninja
- Remove gsl_install.cmake
- Simplify installation code
2023-02-06 11:16:37 -08:00
dmitrykobets-msft cbf5e664fc Fix max macro collision (#1081)
PR https://github.com/microsoft/GSL/pull/1076 introduced a usage of `numeric_limits::max()` function, which seems to have [issues interacting with some Windows headers](https://github.com/skypjack/entt/wiki/Frequently-Asked-Questions#warning-c4003-the-min-the-max-and-the-macro). This PR implements [a simple fix](https://stackoverflow.com/questions/1394132/macro-and-member-function-conflict), which is to wrap the invocations in parentheses. This offloads the fix from the users of the library.
2023-01-19 13:17:39 -08:00
Werner Henze a381a3759f 1075 Wrong Expects in gsl::at? (#1076)
https://github.com/microsoft/GSL/issues/1075
- Add `static_assert` because we only support C style array `at` for up to half of the address space.
- Add `std::` before `size_t`.
- tests:
  - Add `#include <exception>`
  - Implement `span_tests` `interop_with_gsl_at` like `at_tests` `std_span`
2023-01-18 13:33:20 -08:00
Gabriel Gerlero 0822838a7c Add Linguist language override for include files (#1079)
Add a `linguist-language` Git attribute that matches the files at `include/gsl` and sets their language to C++. Without this override, these files are not detected as C++ code by [GitHub's Linguist](https://github.com/github/linguist) (likely due to lacking any file extensions).

This will cause GitHub.com to count these files correctly as C++ code and do syntax highlighting when browsing the repo.

**Linguist breakdown results**

Before:

<details>


```
$ docker run --rm -v $(pwd):$(pwd) -w $(pwd) -t linguist github-linguist --breakdown
91.57%  152148     C++
8.43%   14011      CMake

CMake:
CMakeLists.txt
cmake/gsl_functions.cmake
cmake/gsl_install.cmake
include/CMakeLists.txt
tests/CMakeLists.txt

C++:
tests/algorithm_tests.cpp
tests/assertion_tests.cpp
tests/at_tests.cpp
tests/byte_tests.cpp
tests/deathTestCommon.h
tests/no_exception_ensure_tests.cpp
tests/notnull_tests.cpp
tests/owner_tests.cpp
tests/span_compatibility_tests.cpp
tests/span_ext_tests.cpp
tests/span_tests.cpp
tests/strict_notnull_tests.cpp
tests/utils_tests.cpp
```

</details>

After:

<details>

```
$ docker run --rm -v $(pwd):$(pwd) -w $(pwd) -t linguist github-linguist --breakdown
94.16%  225699     C++
5.84%   14011      CMake

CMake:
CMakeLists.txt
cmake/gsl_functions.cmake
cmake/gsl_install.cmake
include/CMakeLists.txt
tests/CMakeLists.txt

C++:
include/gsl/algorithm
include/gsl/assert
include/gsl/byte
include/gsl/gsl
include/gsl/gsl_algorithm
include/gsl/gsl_assert
include/gsl/gsl_byte
include/gsl/gsl_narrow
include/gsl/gsl_util
include/gsl/narrow
include/gsl/pointers
include/gsl/span
include/gsl/span_ext
include/gsl/string_span
include/gsl/util
tests/algorithm_tests.cpp
tests/assertion_tests.cpp
tests/at_tests.cpp
tests/byte_tests.cpp
tests/deathTestCommon.h
tests/no_exception_ensure_tests.cpp
tests/notnull_tests.cpp
tests/owner_tests.cpp
tests/span_compatibility_tests.cpp
tests/span_ext_tests.cpp
tests/span_tests.cpp
tests/strict_notnull_tests.cpp
tests/utils_tests.cpp
```
</details>
2023-01-06 08:11:06 -08:00
Werner Henze f94c1f6f2b use code spans in README.md (#1078) 2022-12-29 10:23:30 -08:00
Werner Henze ac26d7bc71 cleanup natvis (#1077)
- `fail_fast`,`basic_string_span` and `basic_zstring_span` are not declared in the headers any more.
- Name the exporting header file for all types in `GSL.natvis`.
2022-12-29 10:21:11 -08:00
Werner Henze c016bdc77f remove all deprecated string_span stuff (#1074)
This solves issue #1070 and removes the class `string_span`. The only content remaining in the header file `gsl/string_span` is the `*zstring` types.
This also removes the `string_span_tests.cpp` unit tests as these were only for the deprecated `string_span` class.

Co-authored-by: Werner Henze <werner.henze+gitcommits@posteo.de>
2022-12-27 07:22:26 -08:00
dmitrykobets-msft 46c72713f2 Document potentially confusing behavior in gsl::narrow (#1073)
NaN != Nan, so the comparisons used in gsl::narrow will always throw when attempting to cast a NaN value. This may be surprising, so document it.
2022-12-24 11:49:26 -08:00
dmitrykobets-msft 6c6111acb7 Remove null check inside not_null::get (#1067)
Guidelines issue 2006 removes the null check inside not_null::get, since the contained pointer is already guaranteed to be not-null upon construction.

Resolves #1051
2022-12-14 18:16:52 -08:00
dmitrykobets-msft f3620bb009 Suppress false postive warning (#1068)
The Clang compiler for MSVC in Visual Studio 2022 17.4.33122.133 used by the test runner has a bug which raises -Wdeprecated "out-of-line definition of constexpr static data member is redundant in C++17 and is deprecated" in gsl/span, when compiling with C++14. Temporarily suppress this warning for MSVC Clang with C++14.
2022-12-14 15:39:34 -08:00
Changming Sun 517ed29228 Fix GSL_SUPPRESS definition when nvcc is in-use (#1064) 2022-11-07 14:00:32 -08:00
jpr42 d69e578519 clang-tidy: performance-noexcept-move-constructor (#1063)
I ran GSL through clang-tidy with the performance-* checks

https://releases.llvm.org/15.0.0/tools/clang/tools/extra/docs/clang-tidy/checks/performance/noexcept-move-constructor.html
2022-11-01 10:07:47 -07:00
jpr42 9c4212aca4 Raise CMake min to 3.8 (#1061)
This avoids propagating -std=c++14 as a compile option

Currently if you use less than CMake 3.8 and you install the project
`-std=c++14` gets added to the INTERFACE_COMPILE_OPTIONS. This forces
users to use C++ 14 or remove the property from the imported target.

The solution is to raise the minimum and use `cxx_std_14`
2022-10-29 12:31:23 -07:00
Eli Boyarski 1e0d0446dd README.md: fixed a typo (#1062) 2022-10-24 13:34:44 -07:00
jpr42 c52bad36aa CMake cleanup (#1060)
- Move all install logic inside gsl_install.cmake
  - This makes reading the logic easier, and avoids the enable language
    issue with `GNUInstallDirs` by having it included after the project
    call
- Have all functions inside gsl_functions.cmake
- Use CMake idiom PROJECT_IS_TOP_LEVEL
- Update README.md
2022-10-18 11:05:09 -07:00
dmitrykobets-msft 991fa6682e Prevent inefficient copying when using not_null::get (#1059)
Closes issue #550, which highlighted overhead in not_null::get for larger types such as shared_ptr. Every call to get would return a copy of the contained value.
This PR implements Herb's suggestion for changing the return type of not_null::get. The not_null's value will now only be copied if it is "trivially copyable"; otherwise, it will be returned by const reference.
Note: this change also forces the returned copy to be const.
2022-10-11 16:49:16 -07:00
Herb Sutter 7d49d4b45d Clean up final_act and finally, closes #846 (#977)
Somewhere along the way, GSL's implementation of final_act and finally seems to have become way overthought. This PR is to re-simplify these facilities back to what C++ Core Guidelines C.30 said which is simple and clear and works. It just copies the invocable thing, and doesn't bother trying to optimize the copy. This should be fine, because we're typically passing something that's cheap to copy, often a stateless lambda.

The problem in #846 appears to be because finally looks like was originally written as a const&/&& overload (its state at the time that issue was opened)... to eliminate a copy when you invoke it with a temporary. If so, then the && was probably never intended to be a forwarder, but an rvalue reference that tripped over the horrid C++ syntax collision where a && parameter magically instead means a forwarding reference because the type happens to be a template parameter type here. So I suspect the original author was just trying to write an rvalue overload, and the forwarder that's there now was never intended at all.
2022-10-10 16:09:21 -07:00
Rose 849f7ceaf7 Fix Clang-tidy 15 warnings (#1058)
These warnings were found by running clang-tidy 15.
2022-10-06 09:44:39 -07:00
dmitrykobets-msft 1683d87a3f Fix NDK version in Android CI (#1054)
This PR future-proofs the fix made in #1053, which is now outdated due to further updates to the NDK version in the Azure VMs used as part of the CI.
2022-09-27 17:04:21 -07:00
Werner Henze 10df83d292 solve span compile problem with gcc 5.5.0 (#1052)
GCC 4.8.0 - 7.0 has a bug (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=56480) involving specialization in a namespace enclosing the specialized template. This PR fixes an appearance of this bug in the span header.
2022-08-18 12:28:11 -07:00
dmitrykobets-msft 2e94541fcf Use updated NDK version in android test suite (#1053)
https://github.com/actions/runner-images/issues/5930 recently updated the NDK version, resulting in test breakages. Update the version.
2022-08-17 12:40:45 -07:00
dmitrykobets-msft 330583f478 Resolve MSVC warning C5260 (#1049)
* Test solution

* Mark dynamic_extent as inline, compiler-version-permitting
2022-07-18 17:42:21 -07:00
microsoft-github-policy-service[bot] d9fc52e20e Microsoft mandatory file (#1047)
Co-authored-by: microsoft-github-policy-service[bot] <77245923+microsoft-github-policy-service[bot]@users.noreply.github.com>
2022-05-23 15:27:04 -07:00
dmitrykobets-msft da01eb28db Remove useless runtime checks in span implementation (#1029)
Both checks for Expects(ExtentType::size() != dynamic_extent); in storage_type are always useless. storage_type<ExtentType> is only ever created with ExtentType == extent_type<Extent>, where Extent has type std::size_t and is the extent of the span.

Looking at extent_type<std::size_t Ext>::size():

- if Ext != dynamic_extent, then size() always returns Ext, and therefore size() != dynamic_extent
- if Ext == dynamic_extent, then size() returns extent_type<dynamic_extent>::size_. size_ can only be set via one of two constructors:
  - constexpr explicit extent_type(size_type size), which already does the check in question
  - constexpr explicit extent_type(extent_type<Other> ext) : size_(ext.size()), which simply relies on the other extent's size() method
So there is no way for ExtentType::size() == dynamic_extent.
2022-04-28 14:58:25 -07:00
dmitrykobets-msft d8c493c89f Suppress es.46 warning in implementation of gsl::narrow (#1046)
As per the CoreGuidelines, gsl::narrow is defined in terms of static_cast.
Suppress es.46, which suggests converting the static_cast into gsl::narrow
2022-04-28 09:49:38 -07:00
dmitrykobets-msft 7fefaaf2c8 Fix reason for including assert inside gsl/narrow (#1045) 2022-04-28 09:49:10 -07:00
Juan Carlos Arevalo Baeza f21f29d210 gsl/narrow should include <exception> (#1044)
This file uses std::exception, so it should include the appropriate header.

Normally it gets the STL's <exception> header included via the gsl/assert file, but this is skipped with _HAS_EXCEPTIONS=0. I understand _HAS_EXCEPTIONS is undocumented and unsupported, but regardless, the appropriate header should be included here.

Alternatively, gsl/narrow should be modified to support _HAS_EXCEPTIONS=0, like gsl/assert was. But I'm not proposing that change. <exception> does define std::exception even with _HAS_EXCEPTIONS=0.
2022-04-26 14:41:10 -07:00
dmitrykobets-msft 2bfd495080 Suppress -Wfloat-equal warning in implementation of gsl::narrow (#1043)
In the implementation of gsl::narrow, there is a comparison `static_cast<U>(t) != u` which may be comparing two floats.
The comparison here is done purposefully to categorize ill effects of narrowing conversion, since the values being compared *should* be the same when compared with `operator==`. 
Note, using #pragma GCC will suppress this warning for both GCC and Clang.
2022-04-14 11:08:28 -07:00
dmitrykobets-msft 383723676c Make gsl::span's iterators use the contiguous_iterator concept (#1035)
Resolves #1016

Co-authored-by: Casey Carter <Casey@Carter.net>
2022-03-22 13:20:54 -07:00
dmitrykobets-msft f22f524aa2 Suppress reserved identifier warning (#1041)
The following reserved identifiers are being used specifically to target certain MSVC constructs, so suppress the warning in VS 2022 (LLVM) "... is reserved because it starts with '_' followed by a capital letter":
- _Unchecked_type
- _Verify_range
- _Verify_offset
- _Unwrapped
- _Unwrap_when_unverified
- _Seek_to
- _Unchecked_begin
- _Unchecked_end
2022-03-22 12:24:23 -07:00
Werner Henze 4377f6e603 quoted form of #include when GSL includes GSL files (#1030)
[SF.12: Prefer the quoted form of #include for files relative to the including file and the angle bracket form everywhere else](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rs-incform)

Additionally changed #include order in `span` so that all `span_ext` is in the GSL include block and not in the STL include block.

Fixes issues #1025.

Co-authored-by: Werner Henze <w.henze@avm.de>
2022-01-31 13:06:42 -08:00
Vitaly Zaitsev a353456718 Fixed wrong version number in exported CMake configs. (#1027) 2022-01-28 15:22:59 -08:00
dmitrykobets-msft 99a29ce797 Document safe usage of undefined behavior in gsl::narrow (#1024) 2022-01-26 16:44:07 -08:00
dmitrykobets-msft ebf0498363 Update compiler support (#1021)
Bump clang and Xcode supported versions and add support for VS with LLVM
2022-01-06 10:17:21 -08:00
dmitrykobets-msft c412deb31e Update compiler support (#1019) 2021-12-10 11:17:47 -08:00
dmitrykobets-msft bcf008ae55 Fix/implement C++2020 compilation, tests, and CI (#1017)
* Fix C++20 bugs and tests
* Rework CI for C++2020 tests
* Update readme compiler versions
2021-12-09 14:54:06 -08:00
dmitrykobets-msft e0880931ae Fix googletest build failure with gcc 11.1+ (#1015) 2021-11-17 12:24:40 -08:00
Jordan Maples c31a9ad5e8 Delete .travis.yml (#995) 2021-10-26 16:52:07 -07:00
Werner Henze da80ce15d8 make zstring family don't require empty angle brackets any more (#998)
Co-authored-by: Werner Henze <werner.henze+gitcommits@posteo.de>
2021-10-26 16:50:58 -07:00
Jean-Michaël Celerier f09b24970d Fix gsl/util for c++20 compilers without <span> (#993)
For instance, clang 10 sets __cplusplus >= 202002L yet does not have span, which causes build errors:

https://gcc.godbolt.org/z/Yq345zGea
2021-09-15 15:12:11 -07:00
Johel Ernesto Guerrero Peña 8a4b9ed0bf feat: narrow for non totally ordered types (#986) 2021-06-23 15:28:45 -07:00
Jordan Maples [MSFT] b26f6d5ec7 gsl::at behavior change regarding gsl::span (#985)
* move span specialization of 'at' to <gsl/span> and update the parameter to be taken by reference

* undid previous changes and acted upon decisions made in maintainer sync. Fixed tests failing in /kernel mode

* ran clang-format on the include folder

* ran clang-format on the test folder

Co-authored-by: Jordan Maples <jordan.maples@microsoft.com>
2021-05-20 18:18:08 -07:00
Tushar Maheshwari c1cbb41b42 Fix iPhone simulator CI (#981)
* Run iOS simulator CI

* Fix link errors

- scope function linkage using anonymous namespace

* Update noexcept test for consistency
2021-05-13 10:52:09 -07:00
beinhaerter ef0ffefe52 is_comparable_to_nullptr for better static_assert (#975)
* is_comparable_to_nullptr for better static_assert

Trying `gsl::not_null<char> p2{ 0 };` on VS2019 the current implementation would trigger

>error C2446 : '!=' : no conversion from 'nullptr' to 'int'
>message: A native nullptr can only be converted to bool or , using reinterpret_cast, to an integral type
>message: see reference to class template instantiation 'gsl::not_null<char>' being compiled
>error C2955 : 'std::is_convertible' : use of class template requires template argument list
>message: see declaration of 'std::is_convertible'
>error C2039 : 'value' : is not a member of 'std::is_convertible<_From,_To>'
>error C2065 : 'value' : undeclared identifier


The new implementation gives much shorter and clearer message and does exactly as the `static_assert` intends to do:

> error C2338: T cannot be compared to nullptr.
> message : see reference to class template instantiation 'gsl::not_null<char *>' being compiled

* Update include/gsl/pointers

Co-authored-by: Casey Carter <cartec69@gmail.com>

Co-authored-by: Werner Henze <w.henze@avm.de>
Co-authored-by: Casey Carter <cartec69@gmail.com>
2021-02-24 14:39:13 -08:00
Jordan Maples [MSFT] 176c92e802 Branch rename cleanup (#976)
* Update pipeline build tag

The build status was still looking for a "master" branch, updated it to point to "main"

* Update ios.yml

* Update android.yml

* Update azure-pipelines.yml

* Update CONTRIBUTING.md
2021-02-24 11:16:21 -08:00
jpr89 84aeb59f26 Fixing cmake developer warning (#972)
Here is the warning currently being produced:

CMake Warning (dev) at C:/Program Files/CMake/share/cmake-3.19/Modules/GNUInstallDirs.cmake:223 (message):
  Unable to determine default CMAKE_INSTALL_LIBDIR directory because no
  target architecture is known.  Please enable at least one language before
  including GNUInstallDirs.
Call Stack (most recent call first):
  cmake/guidelineSupportLibrary.cmake:20 (include)
  CMakeLists.txt:4 (include)
This warning is for project developers.  Use -Wno-dev to suppress it.

I noted how I fixed the error. This is caused by GNUInstallDirs automatically executing code just by including it.

I also added -Werror=dev to the CI to ensure this never happens again.

Co-authored-by: Juan Ramos <juanr0911@gmail.com>
2021-01-19 13:41:25 -08:00
Nicholas Guriev d9fa328f89 Improve build script for standalone tests (#963)
* Require Git for build tests only if installed GTest is not found

Cloning via Git is not the only path to obtain Google Test framework. In Linux,
using a system package manager is the preferred way, and gtest can be installed
through APK, APT, DNF, pacman, or many other. Now we make Git mandatory after
checking GTest existence.

See also: https://github.com/microsoft/GSL/pull/961#discussion_r548959056

* Support standalone tests

The patch makes possible to run auto-tests against globally installed GSL,
ignoring local headers. To do this, run CMake in the tests/ folder.

    cmake -B build -S tests -DGSL_CXX_STANDARD=14

This feature should not break existing build recipes.

Co-authored-by: Nicholas Guriev <nicholas@guriev.su>
2021-01-08 10:55:59 -08:00
hdf89shfdfs d0052f6320 Minor cmake nitpicks (#969)
It's much nicer and less error prone to just use add_subdirectory to establish the include directory.

Hide the GNUInstallDirs module by placing it in the helper module. The intent being that the main CMakeLists.txt should have a little code as possible. So that readers can quickly understand the project.

Use include_guard() when available in cmake 3.10+

Co-authored-by: Juan Ramos <juanr0911@gmail.com>
2021-01-08 09:56:04 -08:00
hdf89shfdfs 3b3478eaf8 Update README.md (#970)
Mention the new FetchContent functionality cmake offers. And provide a usable example.

Co-authored-by: Juan Ramos <juanr0911@gmail.com>
2021-01-07 14:02:47 -08:00
Jordan Maples [MSFT] e427b02c89 Reintroduce CMake changes that were reverted in #966 (#967)
* [cmake] Adding options for INSTALL and TEST (#964)

* [cmake] Adding GSL_INSTALL option

Not all consumers of GSL automatically want to have this install logic.

It's good practice to gate install logic behind an option.
For an example look at magic_enum:
https://github.com/Neargye/magic_enum/blob/master/CMakeLists.txt

If the client wants to install GSL they still can. But they should ask
for it by overriding GSL_INSTALL.

* Update cmake/guidelineSupportLibrary.cmake

added nl@eof

* Update CMakeLists.txt

* Update CMakeLists.txt

Co-authored-by: Juan Ramos <juanr0911@gmail.com>
Co-authored-by: Jordan Maples [MSFT] <49793787+JordanMaples@users.noreply.github.com>

* missing config line restored by moving GNUInstallDirs back to main file

Co-authored-by: hdf89shfdfs <31327577+hdf89shfdfs@users.noreply.github.com>
Co-authored-by: Juan Ramos <juanr0911@gmail.com>
2021-01-05 11:55:13 -08:00
Jordan Maples [MSFT] 25bb4bd948 Revert "[cmake] Adding options for INSTALL and TEST (#964)" (#966)
This reverts commit eca0eca6f1.
2021-01-04 14:17:03 -08:00
Jordan Maples [MSFT] 1c509ad8e1 update gtest (#965) 2021-01-04 11:31:01 -08:00
hdf89shfdfs eca0eca6f1 [cmake] Adding options for INSTALL and TEST (#964)
* [cmake] Adding GSL_INSTALL option

Not all consumers of GSL automatically want to have this install logic.

It's good practice to gate install logic behind an option.
For an example look at magic_enum:
https://github.com/Neargye/magic_enum/blob/master/CMakeLists.txt

If the client wants to install GSL they still can. But they should ask
for it by overriding GSL_INSTALL.

* Update cmake/guidelineSupportLibrary.cmake

added nl@eof

* Update CMakeLists.txt

* Update CMakeLists.txt

Co-authored-by: Juan Ramos <juanr0911@gmail.com>
Co-authored-by: Jordan Maples [MSFT] <49793787+JordanMaples@users.noreply.github.com>
2021-01-04 10:42:33 -08:00
Jordan Maples [MSFT] a47352cb2a Delete appveyor.yml 2020-12-18 13:03:34 -08:00
hdf89shfdfs d15cb5fdbe Minor cmake changes (#961)
Abstract adding natvis file.

Move call to find_package(Git) as well as making it required/quiet.
2020-12-15 10:06:46 -08:00
Jordan Maples [MSFT] a6cef6bc6c remove multi_span (#958) 2020-12-09 15:18:07 -08:00
hdf89shfdfs ec6cd75d57 Remove unneccesssary compile definitions (#957) 2020-12-02 14:12:38 -08:00
Jordan Maples [MSFT] 0140ab1d73 Change build status badges (#955)
Using Azure Pipelines badge instead of the Travis-ci and Appveyor badges.
2020-11-23 16:11:40 -08:00
hdf89shfdfs 475b785d2c Use CMAKE_CXX_STANDARD when available (#953)
* Use CMAKE_CXX_STANDARD when available

If the use has provided the variable CMAKE_CXX_STANDARD use that instead of providing a default cache variable.

* Typo
2020-11-16 14:05:33 -08:00
Jordan Maples [MSFT] 959ce58bbc Update gsl (#954) 2020-11-16 09:31:12 -08:00
Jordan Maples [MSFT] 804a14fe8b Update README.md
update the supported matrix
2020-11-11 13:52:11 -08:00
beinhaerter 00d4a5aab6 suppress bounds.1 (#950)
Suppress "warning C26481: Don't use pointer arithmetic. Use span instead (bounds.1)."

Co-authored-by: Werner Henze <werner.henze+gitcommits@posteo.de>
2020-11-11 13:47:58 -08:00
Jordan Maples [MSFT] 9150ce9a95 Adding std::hash<not_null<T>> tests to notnull_tests.cpp (#947)
* added std::hash<not_null> tests

* nl
2020-11-03 16:56:09 -08:00
Jordan Maples [MSFT] a150aaa4ed renaming main logic files. Added warning message of the removal and include passthrough. Renamed includes in the source files. Ran Clang-Format (#946)
Header rename
2020-10-29 17:38:48 -07:00
Jordan Maples [MSFT] e8978c01ab Remove deprecation of basic_zstring et al (#945)
* Azure pipeline (#8)

* azure-pipeline test

* nl @ eof

* trimming the pipeline and adding debug steps

* removing redundant lines

* change ctest to script cmd and remove debug

* removed bad char

* added dir change for ctest

* explicit output file and cmake standard

* test cat

* more ctest tests

* injecting failure in test for validation

* another test

* removing bad test

* massive matrix

* added parallel

* commenting everything but xcode out for testing purposes

* uncomment the other tests

* testing some variables

* rename

* changed macos versions

* adding one more layer of templates

* fixing jobs.yml

* idk what i'm doing

* slight modifications

* maybe some spaces will help

* removing 'variables.'

* another test

* adding back pr w/ autocancel

* adding failing test to validate error = failing task

* remove failing test

* trigger master

* nl in steps.yml

* removing deprecation of basic_zstring and derived types. only *string_span should have been deprecated
2020-10-29 11:34:05 -07:00
Jordan Maples [MSFT] 2c3ab0211c Fix C26481 warning in span array ctor (#944)
* Azure pipeline (#8)

* azure-pipeline test

* nl @ eof

* trimming the pipeline and adding debug steps

* removing redundant lines

* change ctest to script cmd and remove debug

* removed bad char

* added dir change for ctest

* explicit output file and cmake standard

* test cat

* more ctest tests

* injecting failure in test for validation

* another test

* removing bad test

* massive matrix

* added parallel

* commenting everything but xcode out for testing purposes

* uncomment the other tests

* testing some variables

* rename

* changed macos versions

* adding one more layer of templates

* fixing jobs.yml

* idk what i'm doing

* slight modifications

* maybe some spaces will help

* removing 'variables.'

* another test

* adding back pr w/ autocancel

* adding failing test to validate error = failing task

* remove failing test

* trigger master

* nl in steps.yml

* remove forced decay of array reference to pointer in span array ctor
2020-10-29 10:54:37 -07:00
Jordan Maples [MSFT] 179fba51f5 Azure pipeline (#8) (#943) 2020-10-28 16:35:49 -07:00
Jordan Maples [MSFT] d74ae54b60 Update README.md
Closes #911
2020-10-28 15:47:06 -07:00
bowie7070 b6c57e2403 Include gsl_narrow from gsl and fix comment. (#939)
narrow() is now in gsl_narrow rather than gsl_util. Include gsl_narrow when exceptions are enabled. Ensures that #include <gsl/gsl> includes entire library as advertised in the documentation.

Co-authored-by: Bowie Owens <bowie.owens@csiro.au>
2020-10-28 15:38:32 -07:00
mtnpke 736b62a838 Allow usage on platforms not providing iostreams (#935)
Closes #933.
2020-10-28 15:37:02 -07:00
Jordan Maples [MSFT] 6f4529395c Merge pull request #941 from JordanMaples/cmake_update
added GSL_ prefix to VS_ADD_NATIVE_VISUALIZERS
2020-10-26 10:12:40 -07:00
Jordan Maples [MSFT] 9fa2c5d5b9 Merge pull request #942 from tjs137/patch-1
use `narrow_cast`
2020-10-26 10:06:20 -07:00
tjs137 8009a703c2 use narrow_cast 2020-10-24 19:44:06 -04:00
Jordan Maples cfb4db0c1e added GSL_ prefix to VS_ADD_NATIVE_VISUALIZERS 2020-10-22 15:40:27 -07:00
Jordan Maples [MSFT] 6432f920ea Merge pull request #937 from beinhaerter/cast_warning
eliminate warning, use narrow_cast instead of static_cast
2020-10-20 10:55:05 -07:00
beinhaerter 2af9b11fe9 Update include/gsl/span
Co-authored-by: Jordan Maples [MSFT] <49793787+JordanMaples@users.noreply.github.com>
2020-10-20 00:44:11 +02:00
beinhaerter dc6fdff4c0 Update include/gsl/span
Co-authored-by: Jordan Maples [MSFT] <49793787+JordanMaples@users.noreply.github.com>
2020-10-20 00:44:02 +02:00
Werner Henze 2ccf36b4b9 eliminate warning, use narrow_cast instead of static_cast 2020-10-14 15:04:50 +02:00
Jordan Maples [MSFT] bd23bdc0ad Merge pull request #931 from JordanMaples/deprecate-string_span
Deprecate string_span
2020-10-02 12:36:09 -07:00
Jordan Maples 1665f07cf6 updating readme to reflect the deprecation of string_span 2020-10-01 14:38:41 -07:00
Jordan Maples 3f68a0034a fixed botched formatting 2020-10-01 14:16:01 -07:00
Jordan Maples 7721de88f3 ran clang-format over string_span 2020-10-01 14:08:01 -07:00
Jordan Maples a64c489c78 added deprecation message 2020-10-01 14:04:04 -07:00
Jordan Maples 5e773556fe initial deprecation of all types in string_span 2020-09-30 16:39:33 -07:00
Jordan Maples [MSFT] 5de956aaf0 Merge pull request #929 from JordanMaples/yml_experiment
split GitHub action into multiple files.
2020-09-23 14:23:52 -07:00
Jordan Maples [MSFT] bd803cc7cf Merge pull request #928 from JordanMaples/narrowing_error-add-what
add what to narrowing_error
2020-09-14 16:51:38 -07:00
Jordan Maples e7e3bf4f5f add what to narrowing_error 2020-09-14 15:50:46 -07:00
Jordan Maples [MSFT] 21b69e5cce Updating span section of Supported Features table.
Added a link to the span section to point to the "gsl::span and std::span" page in the wiki.
2020-08-28 10:53:19 -07:00
Jordan Maples [MSFT] d58e50c6f4 Merge pull request #922 from JordanMaples/constexpr-string_span
constexpr string_span
2020-08-27 14:29:30 -07:00
Jordan Maples 5fb0c8611e constexpr string_span stuff 2020-08-27 13:21:35 -07:00
Jordan Maples [MSFT] 6c518638ac Merge pull request #921 from JordanMaples/not_null-changes
not_null improvements
2020-08-26 17:48:26 -07:00
Jordan Maples 4a4bb3c13a adding changes suggested by Jonathan Wakely 2020-08-26 16:51:58 -07:00
Jordan Maples [MSFT] b6451c5db0 Merge pull request #920 from macjohnny/patch-1
fix typo in readme
2020-08-24 09:27:02 -07:00
Esteban Gehring 81957f6f91 fix typo in readme 2020-08-24 15:17:30 +02:00
Jordan Maples [MSFT] 6aa755e9ce Merge pull request #913 from jwakely/notnull_hash
Pass correct value to std::hash
2020-08-20 15:32:22 -07:00
Jordan Maples [MSFT] e426750695 Merge pull request #720 from menuet/fix-finally
Fix finally when passing a non const lvalue invokable thing
2020-08-17 09:10:50 -07:00
Pascal Menuet c25a7544b8 Fix finally with mutable lvalue invokable 2020-08-14 16:24:10 +02:00
Jordan Maples [MSFT] 06c46195ee Merge pull request #910 from JordanMaples/exception_fix_new_file
exception free - Version 2
2020-08-13 16:35:04 -07:00
Jordan Maples [MSFT] 83ce710d6c Merge pull request #807 from kuzkry/implemented_features
Add a table of features
2020-08-13 09:34:31 -07:00
Jordan Maples [MSFT] ec471abe44 Merge pull request #912 from jwakely/patch-1
Fix comment typos
2020-08-13 09:30:31 -07:00
Jordan Maples dad3d80c25 Update README.md
Rearranged and updated the table.
Added a second table of concepts that exist in the Microsoft GSL that do not exist in the C++ Core Guidelines
2020-08-13 15:35:46 +02:00
Krystian Kuzniarek a9ffcf7f65 add a table of features 2020-08-13 15:35:45 +02:00
Jonathan Wakely e09326eefd Pass correct value to std::hash 2020-08-13 12:59:01 +01:00
Jonathan Wakely d09f1544fd Fix comment typos 2020-08-13 10:46:39 +01:00
Jordan Maples 74968d3ef8 Merge branch 'master' into exception_fix_new_file 2020-08-12 17:14:13 -07:00
Jordan Maples [MSFT] 0c80f51f7c Merge pull request #908 from JordanMaples/fix_nodiscard_in_finally_macro
Finally [[nodiscard]] - Version 2
2020-08-12 15:49:55 -07:00
Jordan Maples [MSFT] ef714fa49e Merge pull request #676 from ericLemanissier/patch-3
fix requirement on not_null template
2020-08-12 15:28:25 -07:00
Jordan Maples [MSFT] 9355982fc5 Merge pull request #868 from mymedia2/master
Search for GoogleTest via pkg-config first
2020-08-12 15:08:54 -07:00
Jordan Maples 4da6a264c4 forgot newline at eof. 2020-08-12 13:22:33 -07:00
Jordan Maples 2469db7a5a add copyright header 2020-08-12 13:14:53 -07:00
Jordan Maples afe824490e change macro test to use __cplusplus instead of __has_cpp_attribute 2020-08-12 12:13:19 -07:00
Jordan Maples 72ddfb7a40 created new file for gsl_narrow, might want to rename if we go this approach to have all exception prone logic to live here 2020-08-11 17:11:14 -07:00
Jordan Maples bf0697be71 update readme to have the correct asset badges. This will render correctly when it's merged into the main repo 2020-08-11 16:46:41 -07:00
Jordan Maples 97cb97c685 readme update for the updated badges 2020-08-11 16:30:48 -07:00
Jordan Maples 13f57a1e70 update ci names 2020-08-11 16:28:37 -07:00
Jordan Maples c482c82d3a experimenting with splitting the yml files into their own runs 2020-08-11 16:08:16 -07:00
Jordan Maples 01eaf5bef1 macro version 2020-08-10 16:45:47 -07:00
Jordan Maples [MSFT] 63379b7935 Merge pull request #850 from beinhaerter/zstring_ctor
zstring_span: fix for Expects, simplify functions
2020-08-06 10:28:02 -07:00
Werner Henze 2231d733c6 zstring_span: fix for Expects, simplify functions
- `s[s.size() - 1]` is wrong for empty `s`, so `Expects(s.size() > 0)`
- no hard coded `'\0'`but `value_type{}`
- hard code `empty()` to return `false`
- simplify `as_string_span`: can never be `empty`
- clarify comment on `ensure_z`
2020-08-06 11:25:29 +02:00
Jordan Maples [MSFT] f8d9f2e2e3 Merge pull request #906 from TManhente/intel_suppress_fix
Fix  GSL_SUPPRESS definition on Intel C++ Compiler
2020-08-05 15:35:26 -07:00
Jordan Maples [MSFT] 552eedb390 Merge pull request #881 from robert-andrzejuk/patch-1
Refactor `narrow`.
2020-08-05 15:16:25 -07:00
Thiago M. de C. Marques ca3bf7710f Fix GSL_SUPPRESS definition on Intel C++ Compiler
Intel C++ Compiler defines the `_MSC_VER` macro, but it doesn't support `[[gsl::*]]` attributes.
2020-08-05 18:30:24 -03:00
Jordan Maples [MSFT] 559f8cfaae Merge pull request #899 from JordanMaples/dev/jomaples/cleanup_namespaces
cleanup gsl namespace qualification for dynamic_extent.
2020-07-15 14:56:54 -07:00
Jordan Maples [MSFT] f79ed1bb5c Merge pull request #876 from beinhaerter/make_notnull_noexcept
noexcept for make_(strict_)not_null and not_null comparisons
2020-07-15 14:36:17 -07:00
Jordan Maples [MSFT] bf6e103dfd Merge pull request #898 from JordanMaples/dev/jomaples/remove_pragma_push_pop
Remove msvc < 1910 checks.
2020-07-15 14:00:29 -07:00
Jordan Maples 4c66cea06c remove gsl namespace qualification within the gsl namespace 2020-07-15 13:11:57 -07:00
Jordan Maples 478d876951 remove pragma pop for constexpr macro 2020-07-15 11:43:29 -07:00
Jordan Maples 853b061141 remove msvc < 1910 checks as those versions are no longer supported. 2020-07-15 11:38:41 -07:00
Jordan Maples [MSFT] 301030310e Merge pull request #897 from microsoft/JordanMaples-patch-1
Update README.md
2020-07-07 10:58:04 -07:00
Jordan Maples [MSFT] be3bc0e754 Update README.md
Removed the line saying that specific workarounds exist for MSVC 2015 as they were removed in #886 when support for MSVC 2015 was dropped.
2020-07-06 08:22:35 -07:00
Jordan Maples [MSFT] 98002ab601 Merge pull request #893 from xvitaly/fix-noarch
Added ARCH_INDEPENDENT parameter to write_basic_package_version_file()
2020-06-10 11:09:31 -07:00
Vitaly Zaitsev cfe9baf02e Added ARCH_INDEPENDENT parameter to write_basic_package_version_file().
Signed-off-by: Vitaly Zaitsev <vitaly@easycoding.org>
2020-06-07 16:02:27 +02:00
Jordan Maples [MSFT] 0f6dbc9e29 Merge pull request #892 from JordanMaples/dev/jomaples/gsl3.1.0
Update project version to GSL 3.1.0
2020-06-04 10:10:04 -07:00
Jordan Maples 78744ed530 update cmake project version to reflect upcoming GSL 3.1.0 release 2020-06-03 16:52:20 -07:00
Jordan Maples [MSFT] 794d7bb69b Merge pull request #891 from JordanMaples/dev/jomaples/missing_span_ctad
Adding missing span deduction guides
2020-05-29 16:47:08 -07:00
Jordan Maples 72803a7ecb adding template type to the vector to suppress clang-10 warning that vector may not intend for type deduction. 2020-05-29 15:45:25 -07:00
Jordan Maples 4d2090ebc4 fixed typo 2020-05-29 10:54:13 -07:00
Jordan Maples c4a2ce6cc8 wrapping string_view checks in deduction guide checks to prevent 'macro unused' errors 2020-05-29 10:53:30 -07:00
Jordan Maples [MSFT] 9720cc552a Merge pull request #6 from CaseyCarter/deduction_guides
Add string_view test case and modify deduction guides
2020-05-29 10:16:06 -07:00
Casey Carter c143a07f61 Add string_view test case and modify deduction guides 2020-05-28 18:00:40 -07:00
Jordan Maples 6c405a1b7f adding a test to verify that the additional ctad works 2020-05-28 17:18:08 -07:00
Jordan Maples 689abc2982 adding container ctad 2020-05-28 14:04:31 -07:00
Jordan Maples [MSFT] 0dbdf322fa Merge pull request #886 from JordanMaples/dev/jomaples/build_matrix
compiler support revision
2020-05-26 15:14:08 -07:00
Jordan Maples [MSFT] 283e31478f Merge pull request #857 from pps83/master-natvis
Fix debugger visualizer for Ext=gsl::dynamic_extent
2020-05-21 11:32:45 -07:00
Jordan Maples [MSFT] 8cd19412b4 Merge pull request #887 from JordanMaples/dev/jomaples/p1976r2
gsl::span P1976R2 implemenation
2020-05-21 10:07:37 -07:00
Jordan Maples 25e7af9c7d fixing clang build break 2020-05-20 17:52:03 -07:00
Jordan Maples 7e4ed8da98 addressing Stephan's comments 2020-05-20 16:50:50 -07:00
Jordan Maples 34750814fb updating table with compiler versions that are in the test matrix 2020-05-20 16:24:05 -07:00
Jordan Maples 313a1121bf fix spacing 2020-05-20 15:46:20 -07:00
Jordan Maples 1e44481646 Finished integrating CaseyCarter's changes into span 2020-05-20 13:37:42 -07:00
Jordan Maples ed3fea6d93 implementing some of Casey's recommendations 2020-05-20 13:11:37 -07:00
Jordan Maples 31604f44f6 string_span_tests CLRF -> LF 2020-05-20 12:32:25 -07:00
Jordan Maples d3468230b1 renaming extent to prevent shadowing of static member 2020-05-20 12:29:56 -07:00
Jordan Maples 552cd20472 addressing most of Casey's comments 2020-05-20 10:59:57 -07:00
Jordan Maples 2085c7acde initial impl of P1976R2 2020-05-19 16:27:46 -07:00
Jordan Maples 33544a706e revised the readme 2020-05-13 17:05:45 -07:00
Jordan Maples f0160fcb1b removing breaking test code. removing compiler versions n-2 and beyond from travis script. Updating XCode 11.3 to 11.4 2020-05-13 14:49:17 -07:00
Jordan Maples [MSFT] 2a483c1728 Update span 2020-05-13 11:13:14 -07:00
Jordan Maples 031231466d pushing bad code that only reveals itself in gcc < 6 to test the allow_failures logic in travis 2020-05-13 11:04:11 -07:00
Jordan Maples a6d382109e missed a GSL_CONSTEXPR_NARROW for removal 2020-05-12 16:43:23 -07:00
Jordan Maples 09caa20d99 changing matrices and removing msc < 1910 work arounds 2020-05-12 16:21:55 -07:00
Jordan Maples [MSFT] 0843ea444f Merge pull request #884 from dipidoo/master
reflects verification of iOS and Android support
2020-05-08 09:57:45 -07:00
Bas Hendri 1e4e23738c updates README.md with iOS & Android support 2020-05-07 15:44:56 -07:00
Jordan Maples [MSFT] 839de21707 Merge pull request #879 from leha-bot/cmake/add-version-to-cmake-project
CMakeLists: add VERSION to project() and package
2020-05-06 16:57:50 -07:00
Bas Hendri 91858ca3f3 forces GTEST_HAS_DEATH_TEST 2020-05-04 13:31:08 -07:00
Bas Hendri 0ab350f5de enables iOS and Android testing 2020-05-04 13:26:50 -07:00
Robert Andrzejuk 84847041ee In narrow refactor !is_same_signedness to is_different_signedness 2020-04-29 20:39:44 +02:00
Robert Andrzejuk 1e5f44d3ea Refactor narrow - simplify & move is_same_signedness into function, remove uneeded detail namespace. Merge 2 if's with a ||. 2020-04-29 20:11:44 +02:00
leha-bot de053645bb CMakeLists: Drop ARCH_INDEPENDENT as it does not supported via old CMake 2020-04-28 13:07:41 +03:00
Werner Henze 29297e7dac noexcept for make_(strict_)not_null and not_null comparisons 2020-04-27 14:42:56 +02:00
Alex 879335cebf CMakeLists: add VERSION to project() and package
So the library consumers via find_package(Microsoft.GSL 3.0.2) could determine the actual library version.
2020-04-26 18:09:49 +03:00
Jordan Maples [MSFT] 1999b48a51 Merge pull request #870 from beinhaerter/suppress_span_warning
suppress code analysis warning
2020-04-23 10:13:33 -07:00
Jordan Maples [MSFT] 3da256d03b Merge pull request #874 from JordanMaples/dev/jomaples/multi_span-cleanup
Minor changes to multi_span
2020-04-23 10:13:04 -07:00
Jordan Maples [MSFT] 601b55ea61 Merge pull request #873 from londey/narrow-throw
Changed implementation of gsl::narrow to throw gsl::narrowing_error
2020-04-22 22:57:14 -07:00
Nicholas Londey 3a5b83db35 Removed unused contant from test 2020-04-23 12:30:44 +10:00
Nicholas Londey 94d6a35726 Fixed narrow unit test EXPECT_THROW 2020-04-23 12:23:36 +10:00
Nicholas Londey 14acdcd7a8 Removed unused #include 2020-04-23 12:22:30 +10:00
Nicholas Londey 4eb554d7c2 Removed no_exception_throw_tests.cpp
as per review feedback
2020-04-23 11:58:00 +10:00
Jordan Maples [MSFT] 70e1317ab6 Update include/gsl/gsl 2020-04-22 15:27:00 -07:00
Nicholas Londey 61534ca3ad Changed implementation of gsl::narrow to throw gsl::narrowing_error
Implementation now behaves as described in the C++ Core Guidlines
2020-04-22 10:09:13 +10:00
Jordan Maples afa2f3fd9a fully qualify ptrdiff_t in multi_span and remove it from gsl\gsl 2020-04-21 16:14:58 -07:00
Werner Henze fb1243d735 suppress code analysis warning
- suppress " warning C26481: Don't use pointer arithmetic. Use span instead (bounds.1)."
- Please note that the suppression in `end()` does not work with MSVC 16.5.4.
2020-04-19 16:41:12 +02:00
Nicholas Guriev f5cf01083b Search for GoogleTest via pkg-config first 2020-04-18 13:30:17 +03:00
Jordan Maples [MSFT] 9f6a9a5807 Merge pull request #867 from xvitaly/fix-cmake-install
Fixed installation on GNU/Linux distributions
2020-04-17 10:18:37 -07:00
Vitaly Zaitsev aeb65efada Fixed installation on GNU/Linux distributions.
Signed-off-by: Vitaly Zaitsev <vitaly@easycoding.org>
2020-04-17 11:47:23 +02:00
Jordan Maples [MSFT] b43855631a Merge pull request #861 from JordanMaples/dev/jomaples/lwg3320
implement LWG3320
2020-04-15 10:00:55 -07:00
Jordan Maples 9cb376c050 adding back free functions for [c|cr][begin|end] 2020-04-14 16:57:12 -07:00
Jordan Maples 7341c5d1b5 implement LWG3320 by deleting const_iterator and const_reverse_iterator 2020-04-14 13:51:49 -07:00
Jordan Maples [MSFT] 044849d6fa Merge pull request #823 from RedDwarf69/std_byte_fix
Add missing #include if built with GSL_USE_STD_BYTE=1
2020-04-13 11:33:56 -07:00
Jordan Maples [MSFT] 24dc828cbb Merge pull request #860 from karzhenkov/fix-googletest-link
Fix link to Google Test
2020-04-13 10:35:19 -07:00
Alexander Karzhenkov 8b8c25fa66 Fix link to Google Test 2020-04-13 18:19:51 +05:00
Jordan Maples [MSFT] f7aae78ff6 Merge pull request #854 from JordanMaples/dev/jomaples/LWG3255
Implement span std::array ctor changes from LWG3255
2020-04-09 23:42:04 -07:00
Jordan Maples efbce17ca4 testing one of CaseyCarter's comments 2020-04-09 17:33:33 -07:00
Jordan Maples ffbfcc0a9f apply clang-format to the span_compatibility_tests. 2020-04-09 16:15:08 -07:00
Jordan Maples 5ca02327c4 another test 2020-04-09 15:56:26 -07:00
Jordan Maples 8d907dadfb prevent comparison for apple clang versions older than 11 2020-04-09 14:35:44 -07:00
Jordan Maples b7d9d754ac another attempt at apple clang version filtering 2020-04-09 14:17:52 -07:00
Jordan Maples 809aee2315 testing different major/minor for Apple suppression 2020-04-09 11:51:59 -07:00
Jordan Maples 6ef56d73da fixed a couple typos 2020-04-09 10:35:44 -07:00
Jordan Maples 2f9d873043 added additional filtering to Apple clang versions 9.4 and 10.1 for the ArrayConvertibilityCheck 2020-04-09 10:34:58 -07:00
Jordan Maples f85166aa8b Merge branch 'master' into dev/jomaples/LWG3255 2020-04-09 09:53:45 -07:00
Jordan Maples [MSFT] b0b933b842 Merge pull request #858 from Farwaykorse/patch-1
Solve MSVC warning C4668: __GNUC__ & __clang__ not defined
2020-04-08 23:21:08 -07:00
Jordan Maples [MSFT] bc7ea7aac7 Merge pull request #859 from Farwaykorse/patch-2
Suppress GCC 8 "-Warray-bounds" warning
2020-04-08 23:20:44 -07:00
Farwaykorse 611674d60b GCC "-Warray-bounds" warning persists with release 8.4
modification of commit 5e21831494
2020-04-09 03:50:17 +02:00
Farwaykorse 6e2398b524 Solve MSVC warning C4668: __GNUC__ & __clang__ not defined as a preprocessor macro
MSVC compiler warning C4668:
` '__clang__' is not defined as a preprocessor macro, replacing with '0' for '#if/#elif'`
2020-04-09 03:15:57 +02:00
Jordan Maples ff45864dba Merge branch 'dev/jomaples/LWG3255' of https://github.com/JordanMaples/GSL into dev/jomaples/LWG3255 2020-04-08 14:48:05 -07:00
Jordan Maples 15dd17aa5b Merge branch 'master' into dev/jomaples/LWG3255 2020-04-08 14:47:08 -07:00
Jordan Maples [MSFT] c5dd0e6d40 Merge pull request #3 from JordanMaples/dev/jomaples/lwg3255
adding additional filtering
2020-04-08 14:43:15 -07:00
Jordan Maples 01d206f4d8 adding additional filtering 2020-04-08 14:38:01 -07:00
Pavel P 830b081de7 Fix debugger visualizer for Ext=gsl::dynamic_extent
VS 2019 doesn't seem to match -1 for size_t template parameter, as a result dynamic span/basic_string_span/basic_zstring_span show extent as `extent = 4294967295` (for 32-bit builds). This change updates details::extent_type to have static constexpr size_ parameter for non-dynamic span/basic_string_span/basic_zstring_span and simplifies/removes dynamic versions from GSL.natvis

fixes #856
2020-03-28 01:59:04 +06:00
Jordan Maples [MSFT] 226a854a97 Merge pull request #835 from Farwaykorse/TravisCI
Improve CI with TravisCI
2020-03-26 15:00:27 -07:00
Roelf-Jilling 5e21831494 Suppress test for GCC 8.3 triggering "-Warray-bounds" 2020-03-26 20:15:29 +01:00
Roelf-Jilling 04809f8559 TravisCI: moved "based on" comment to relevant legacy section 2020-03-26 17:16:32 +01:00
Roelf-Jilling 511faf07d4 TravisCI: remove deprecated key "sudo" and replace alias "matrix" for "jobs" 2020-03-26 17:04:01 +01:00
Roelf-Jilling 610c40333d TravisCI: add Clang-10 2020-03-26 16:29:27 +01:00
Roelf-Jilling 30c068781f Merge branch 'master' into TravisCI 2020-03-26 16:24:19 +01:00
Roelf-Jilling f4c2292f9d Update to use the latest CMake releases
3.17.0, 3.16.5 and 3.15.7
2020-03-26 16:12:07 +01:00
Jordan Maples [MSFT] 0357a02921 Apply suggestions from code review
Committing suggested change: XCode to Xcode

Co-Authored-By: Kevin Wojniak <kainjow@users.noreply.github.com>
2020-03-23 13:57:46 -07:00
Jordan Maples ddde9e153d update convertibility test 2020-03-19 14:08:04 -07:00
Jordan Maples 6eab19d3c1 moving decl so we dont get the stl_nullptr is not used warning 2020-03-17 15:13:26 -07:00
Jordan Maples f8bcb7d9eb applied clang-format 2020-03-17 15:04:58 -07:00
Jordan Maples 9b3ac8d681 discussed the issue with Casey Carter, the span ctor changes are accurate but the tests are not. The test require work that was done in C++17 regarding qualifier conversions to work correctly. Scoping tests for 17. 2020-03-17 15:02:00 -07:00
Jordan Maples 1dd1320c8b test commit to get extra eyes on the problem 2020-03-17 13:53:13 -07:00
Jordan Maples [MSFT] d90fefea6d Merge pull request #851 from JordanMaples/dev/jomaples/exception
prevent exception include when in no-exception mode.
2020-03-17 13:41:33 -07:00
Jordan Maples 06adf557e9 update kernel mode detection macro 2020-03-12 12:32:32 -07:00
Jordan Maples ce4d689f4f shuffle around code to bring includes to top. 2020-03-06 11:22:09 -08:00
Jordan Maples b30524088a added some comments and ran clang-format 2020-03-06 11:17:58 -08:00
Jordan Maples 769f01900d moving exception include 2020-03-03 17:04:46 -08:00
Jordan Maples [MSFT] 4b643918a1 Merge pull request #784 from hanst99/hunterization
Update "Make library importable by CMake using find_package"
2020-02-26 08:48:04 -08:00
Jordan Maples [MSFT] a3b86971d9 Merge pull request #847 from JordanMaples/dev/jomaples/split_span
Removing non-standard functionality from span header. Use span_ext for span comparisons and make_span functionality.
2020-02-25 16:59:54 -08:00
Jordan Maples [MSFT] 4a6a7a095d add back array header, will remove in separate pr 2020-02-25 14:09:29 -08:00
Jordan Maples [MSFT] d2fdeda06e Merge branch 'dev/jomaples/split_span' of https://github.com/jordanmaples/gsl into dev/jomaples/split_span 2020-02-25 13:53:00 -08:00
Jordan Maples [MSFT] fc54e0d89a just pulling in array header if we detect apple clang 2020-02-25 13:39:47 -08:00
Jordan Maples [MSFT] 5d54cada8e just pulling in array header if we detect apple clang 2020-02-24 15:49:30 -08:00
Jordan Maples [MSFT] 32e5fea6ac test 2020-02-24 14:47:45 -08:00
Jordan Maples [MSFT] 0f60c68ab9 disgusting test to get apple clang to work, dont look at it 2020-02-24 14:41:29 -08:00
Jordan Maples [MSFT] 60372b6468 apple-clang failed again, forcing class instead of struct 2020-02-24 13:43:42 -08:00
Jordan Maples [MSFT] 89271b89c1 fix apple clang forward declaration 2020-02-24 13:06:01 -08:00
Jordan Maples [MSFT] ac37004274 clang defines struct as array where msvc and g++ define it as class. 2020-02-24 11:45:33 -08:00
Jordan Maples [MSFT] 3144082909 forward declare span and remove header 2020-02-24 11:16:26 -08:00
Jordan Maples [MSFT] c853017be3 forgot nl @ eof in span_ext_tests.cpp 2020-02-19 14:44:22 -08:00
Jordan Maples [MSFT] 94f43d4adf splitting up span's standard and non-standard behavior 2020-02-19 14:28:12 -08:00
Jordan Maples [MSFT] 691a78c016 Merge pull request #844 from JordanMaples/dev/jomaples/unsigned
gsl::span: Migrate from signed to unsigned
2020-02-18 16:55:14 -08:00
Jordan Maples [MSFT] 46603698ec rewrite operators in iterator to take advantage of nrvo 2020-02-18 15:36:15 -08:00
Jordan Maples [MSFT] f4c608fd39 addressing comments 2020-02-18 14:09:11 -08:00
Jordan Maples [MSFT] 8ba6cb1074 Merge branch 'dev/jomaples/unsigned' of https://github.com/jordanmaples/gsl into dev/jomaples/unsigned 2020-02-18 10:13:14 -08:00
Jordan Maples [MSFT] 8d6ca323fa GTest latest is breaking, rolling back to 1.10 until further investigation 2020-02-18 10:13:03 -08:00
Jordan Maples [MSFT] 6b01a0488b Update span_compatibility_tests.cpp
some fixes.
2020-02-14 16:25:25 -08:00
jordan maples b6b1e9c3cf assert -> expect_true 2020-02-14 16:13:21 -08:00
Jordan Maples [MSFT] 67a7f7eaef errors in appveyor are indicating that AsWritableByesCompilersFor needs to be static. 2020-02-14 15:44:58 -08:00
Jordan Maples [MSFT] 41ae38f197 addressing a few more comments and adding gsl-std span compatibility tests 2020-02-14 15:24:46 -08:00
Jordan Maples [MSFT] 926aaeca56 reviewed the pr in its entirety and made some slight modifications. Removed all members and fields marked as deprecated. 2020-02-11 16:36:07 -08:00
Jordan Maples [MSFT] cce6ee563e address issue with v140 toolset 2020-02-10 17:09:58 -08:00
Jordan Maples [MSFT] dd78144c2e msvc and gcc work locally 2020-02-10 13:17:22 -08:00
Hannes Steffenhagen 849f14083a Add a note on CMake usage of exported target to the README 2020-02-08 13:11:11 +00:00
Hannes Steffenhagen 9c0c6b246c Add Microsoft.GSL::GSL alias for GSL
This ensures that dependents can be agnostic about
whether GSL was added via `add_subdirectory` or `find_package`
2020-02-08 12:58:25 +00:00
Hannes Steffenhagen 886fc95142 Remove PUBLIC_HEADER attribute from install command
Since we already explicitly install `include/gsl`, this
doesn’t do anything.
2020-02-08 12:55:19 +00:00
Hannes Steffenhagen ebe8844344 Make GSL includes based on CMAKE_INSTALL_INCLUDEDIR
This is to avoid inconsistencies with the `install`
command which specifies this as the destination for includes.
2020-02-08 12:53:40 +00:00
Jordan Maples [MSFT] d8fa68c4a5 address build failures 2020-02-07 14:40:09 -08:00
Jordan Maples [MSFT] b81d6e40e1 constexpr the make_subspan calls. 2020-02-07 14:15:44 -08:00
Jordan Maples [MSFT] 377b2db537 almost parity with std::span 2020-02-07 14:09:57 -08:00
Jordan Maples [MSFT] 202f332702 Merge pull request #845 from cbuchart/master
Fix incorrect package name for vcpkg
2020-02-07 10:41:33 -08:00
cbuchart 3f0d733466 Fix incorrect package name for vcpkg 2020-02-07 15:25:58 +01:00
Jordan Maples [MSFT] a49ff1b8df update span specialization of at, change some tests back to int i with narrowing for the comparisons. 2020-02-05 17:12:31 -08:00
Jordan Maples [MSFT] 3b9d15f49f reverting changes to gsl::index 2020-02-05 17:02:23 -08:00
Jordan Maples [MSFT] 45f016d96f add back capture variable for comparison in span_test 2020-02-05 14:41:41 -08:00
Jordan Maples [MSFT] ff5f7973a2 remove brackets around this deref for span_iterator operators 2020-02-05 14:36:34 -08:00
Jordan Maples [MSFT] 7fcc142ffc addressing travis errors 2020-02-05 14:32:08 -08:00
Jordan Maples [MSFT] 432be4852c captureing result of iterator comparisons to address -Wunused-comparison 2020-02-05 13:59:48 -08:00
Jordan Maples [MSFT] 5cf1610cfe prevent overflow in size_bytes. fix compilation issue for clang 3.6 and 3.7 2020-02-05 12:58:49 -08:00
Jordan Maples [MSFT] d7e1611137 gsl::index ptrdiff_t -> size_t. remove span::at span::operator(). 2020-02-04 16:53:43 -08:00
Jordan Maples [MSFT] 5a1e4f3953 update index_type to size_type, fix a couple Expects 2020-02-04 15:31:33 -08:00
Jordan Maples [MSFT] 61c6ef8d42 remove index_type from string_span, update comments 2020-02-04 13:30:03 -08:00
Jordan Maples [MSFT] db2134485a Merge branch 'dev/jomaples/unsigned' of https://github.com/jordanmaples/gsl into dev/jomaples/unsigned 2020-02-04 12:01:30 -08:00
Jordan Maples [MSFT] 0c6ce424ab refactoring index_type to size_type, changing expects 2020-02-04 12:01:27 -08:00
Jordan Maples [MSFT] e9fea77bcb Update include/gsl/span
Co-Authored-By: Casey Carter <cartec69@gmail.com>
2020-02-03 18:31:50 -08:00
Jordan Maples [MSFT] 4ec7058b56 Update include/gsl/span
Co-Authored-By: Casey Carter <cartec69@gmail.com>
2020-02-03 18:31:21 -08:00
Jordan Maples [MSFT] 49e7ed1ebf updating comparisons 2020-02-03 18:27:09 -08:00
Jordan Maples [MSFT] 592c28c6d1 fixing spaces in gsl_suppress 2020-02-03 18:18:14 -08:00
Jordan Maples [MSFT] 877816faa4 addressing feedback 2020-02-03 18:16:41 -08:00
Jordan Maples [MSFT] 2b7a8f1f2f Merge branch 'dev/jomaples/unsigned' of https://github.com/jordanmaples/gsl into dev/jomaples/unsigned 2020-02-03 18:14:52 -08:00
Jordan Maples [MSFT] e0dc8095b3 addressing feedback 2020-02-03 18:13:14 -08:00
Jordan Maples [MSFT] 81c2a1da15 addressing feedback 2020-02-03 18:12:57 -08:00
Jordan Maples [MSFT] 827fafd32c Update include/gsl/span
Co-Authored-By: Casey Carter <cartec69@gmail.com>
2020-02-03 18:12:32 -08:00
Jordan Maples [MSFT] 24646c6f7c Update include/gsl/span
Co-Authored-By: Casey Carter <cartec69@gmail.com>
2020-02-03 17:51:45 -08:00
Jordan Maples [MSFT] f4ee6ee73b Update include/gsl/span
Co-Authored-By: Casey Carter <cartec69@gmail.com>
2020-02-03 17:51:25 -08:00
Jordan Maples [MSFT] 1815791af8 Change iterator from Span* & ptrdiff_t to pointer, pointer, pointer 2020-02-03 16:26:36 -08:00
Jordan Maples [MSFT] d9d6ea8196 remove comparison to dynamic_extent 2020-02-03 13:53:38 -08:00
Jordan Maples [MSFT] 3e40b3fa4b Merge branch 'dev/jomaples/unsigned' of https://github.com/jordanmaples/gsl into dev/jomaples/unsigned 2020-02-03 13:52:11 -08:00
Jordan Maples [MSFT] d0fdbdbffa fixing suppress spacing 2020-02-03 13:52:00 -08:00
Jordan Maples [MSFT] a430823b43 Update include/gsl/string_span
Co-Authored-By: Casey Carter <cartec69@gmail.com>
2020-02-03 13:47:34 -08:00
Jordan Maples [MSFT] 9bb900e834 Update include/gsl/span
Co-Authored-By: Casey Carter <cartec69@gmail.com>
2020-02-03 13:46:18 -08:00
Jordan Maples [MSFT] 17e372c155 Update include/gsl/span
Co-Authored-By: Casey Carter <cartec69@gmail.com>
2020-02-03 13:45:56 -08:00
Jordan Maples [MSFT] 5b8cf5422b casting -1 for dynamic extent 2020-02-03 12:49:57 -08:00
Jordan Maples [MSFT] eabd9358f0 addressing some comments 2020-02-03 12:46:37 -08:00
Jordan Maples [MSFT] ad71477183 fix build breaks 2020-02-03 12:26:15 -08:00
Jordan Maples [MSFT] c31593dd0d updating from test loop from int to size_t 2020-02-03 11:01:24 -08:00
Jordan Maples [MSFT] 8579165d0a change span from signed to unsigned to align to std 2020-02-03 10:56:31 -08:00
Jordan Maples [MSFT] b4dd39615a Merge pull request #842 from JordanMaples/dev/jomaples/not_null
remove move constructor for not_null.
2020-01-30 19:51:35 -08:00
Jordan Maples [MSFT] 6b23937baf remove move constructor for not_null. 2020-01-30 17:00:13 -08:00
Jordan Maples [MSFT] 6e20bfbba2 Merge pull request #836 from Farwaykorse/suppressionToCMake
Compiler warning suppression for tests to CMake
2020-01-22 11:59:51 -08:00
Jordan Maples [MSFT] 57dd11b20f Merge pull request #840 from NancyLi1013/vcpkg-instructins
Add vcpkg installation instructions
2020-01-22 11:52:47 -08:00
NancyLi1013 c61b1503ad Add vcpkg installation instructions 2020-01-18 23:12:43 -08:00
Jordan Maples [MSFT] 7ba7f87475 Merge pull request #837 from Farwaykorse/fix/disable_exceptions
Restore disabling of exceptions for MSVC in "no exception tests"
2020-01-17 09:13:44 -08:00
Jordan Maples [MSFT] d976d41494 Merge pull request #838 from kunaltyagi/patch-1
Fix spelling error in docs
2020-01-17 09:13:09 -08:00
Kunal Tyagi 26a68c882b Correct spelling error in docs 2020-01-17 14:32:37 +09:00
Roelf-Jilling 95730a80c4 Restore disabling of exceptions for Microsoft STL in "no exception tests" 2020-01-16 19:31:31 +01:00
Roelf-Jilling 72312b6474 Revert "adding /EHsc for msvc cmake target gsl_test_config_noexcept"
This reverts commit 3539bd8008.
2020-01-16 19:29:36 +01:00
Roelf-Jilling adc5fb0d14 TravisCI: use more bash variable checks
To detect typos and logic errors.
2020-01-16 17:55:58 +01:00
Roelf-Jilling b29a18d3a8 TravisCI: use stages to end run when newest compilers fail
These tend to have the best error messages.
2020-01-16 17:55:58 +01:00
Roelf-Jilling 5082a21b04 TravisCI: keep googletest directories between CMake generator runs 2020-01-16 17:55:58 +01:00
Roelf-Jilling 8edc449efb CMake 3.2.3 or later to use AppleClang on OSX
GoogleTest uses CMake compile feature detection.
2020-01-16 17:55:58 +01:00
Roelf-Jilling 5caf336e02 TravisCI: validate CMake configuration with all supported releases 2020-01-16 17:55:58 +01:00
Roelf-Jilling ecff9e623c TravisCI: performance - use the default CMake version on CI images 2020-01-16 17:55:58 +01:00
Roelf-Jilling f828c55ec7 TravisCI: add Clang-8 and 9 2020-01-16 17:55:58 +01:00
Roelf-Jilling 586c4e52f8 TravisCI: add GCC-8 and 9 2020-01-16 17:55:58 +01:00
Roelf-Jilling e1a37d0430 Suppress -Wundefined-func-template for C++17 Clang v5.0.x and AppleClang 9.1
Warning appears on v5.0.2 from apt.llvm.org and Ubuntu provided v5.0.1
2020-01-16 17:55:58 +01:00
Roelf-Jilling f0061bfa2a TravisCI: default to Ubuntu Bionic and use Xenial where needed 2020-01-16 17:55:58 +01:00
Roelf-Jilling 8655dc1583 TravisCI: Xcode 9.0 earliest with C++17 support 2020-01-16 17:55:56 +01:00
Roelf-Jilling d768179ff6 TravisCI: add XCode v9.4, 10.1, 10.3 and 11.3 2020-01-16 17:54:59 +01:00
Roelf-Jilling 81f56796a1 MSVC and CoreChecker warning suppression for tests to CMake
Suppress CppCoreCheck warnings on GTest macros.
Suppress CppCoreCheck advice to use the GSL
2020-01-16 11:49:15 +01:00
Roelf-Jilling 4cbd894812 Enable more warnings in GCC 2020-01-16 11:49:15 +01:00
Roelf-Jilling d08ff53e61 Use [[maybe_unused]] with C++17 2020-01-16 11:49:15 +01:00
Roelf-Jilling 186f5d21c1 Move compiler warning suppression for tests from cpp files to CMake 2020-01-16 11:49:00 +01:00
Roelf-Jilling cdedae897c TravisCI: remove redundant setting of CXX variable 2020-01-15 21:06:14 +01:00
Jordan Maples [MSFT] 888b9b9723 Merge pull request #830 from JordanMaples/dev/jomaples/add_missing_span_functions
Add span::front and span::back. See #828.
2020-01-10 10:20:47 -08:00
Jordan Maples [MSFT] 395a5bf550 Merge branch 'master' into dev/jomaples/add_missing_span_functions 2020-01-10 10:20:37 -08:00
Jordan Maples [MSFT] 96b6964b30 Merge pull request #829 from JordanMaples/dev/jomaples/deprecate_span_non_std_functions
Deprecate span::at & span::operator(). See #828.
2020-01-10 10:19:32 -08:00
Jordan Maples [MSFT] a1e6fcbc46 Merge branch 'master' into dev/jomaples/deprecate_span_non_std_functions 2020-01-09 16:39:24 -08:00
Jordan Maples [MSFT] 2d878b94ee Merge branch 'master' into dev/jomaples/add_missing_span_functions 2020-01-09 16:37:12 -08:00
Jordan Maples [MSFT] b076205338 Merge branch 'dev/jomaples/deprecate_span_non_std_functions' of https://github.com/JordanMaples/GSL into dev/jomaples/deprecate_span_non_std_functions 2020-01-09 14:40:08 -08:00
Jordan Maples [MSFT] 75936c3109 missed from the merge 2020-01-09 12:56:00 -08:00
Jordan Maples [MSFT] cfd82aef4e deprecating span::at and span::operator() 2020-01-09 12:51:28 -08:00
Jordan Maples [MSFT] 3c0b38b777 Merge pull request #833 from JordanMaples/dev/jomaples/noexceptspan
Update noexcept in span and span_iterator
2020-01-09 12:45:17 -08:00
Jordan Maples [MSFT] 2bc6a7cb12 Merge pull request #825 from omartijn/free_standing_begin_end_ssize
Implement free-standing (c|r|cr)(begin|end) and ssize functions
2020-01-09 12:32:31 -08:00
Jordan Maples [MSFT] c7f9b3301a noexcepting new functions 2020-01-09 12:13:12 -08:00
Jordan Maples [MSFT] 6eccc81c5f Merge branch 'dev/jomaples/add_missing_span_functions' of https://github.com/JordanMaples/GSL into dev/jomaples/add_missing_span_functions 2020-01-09 12:09:24 -08:00
Jordan Maples [MSFT] 4b823b1651 adding front and back 2020-01-09 12:03:27 -08:00
Jordan Maples [MSFT] 3bf4106a44 noexcept all of the span iterator stuff 2020-01-08 12:34:11 -08:00
Martijn Otto fa8a8117a0 Add tests for free-standing iterator and size functions 2020-01-08 21:02:02 +01:00
Martijn Otto b186b6cc68 Implement free-standing (c|r|cr)(begin|end) and ssize functions 2020-01-08 21:01:52 +01:00
Jordan Maples [MSFT] b33bd4aebe updating all span functions to be noexcept 2020-01-08 11:51:15 -08:00
Jordan Maples [MSFT] 0fefba89da Merge pull request #832 from JordanMaples/dev/jomaples/buildfix
fix appveyor build issues.
2020-01-08 11:47:22 -08:00
Jordan Maples [MSFT] f04907c2f6 added suppression for missing destructor override 2020-01-08 10:13:00 -08:00
Jordan Maples [MSFT] 7786da91c9 Merge pull request #831 from JordanMaples/dev/jomaples/gtest
Migrate from Catch to GoogleTest & always terminate on contract violation
2020-01-07 15:41:25 -08:00
Jordan Maples [MSFT] 40bc3c3f00 testing something 2019-12-20 13:32:14 -08:00
Jordan Maples [MSFT] 8577033f13 addressing comments 2019-12-19 14:05:02 -08:00
Jordan Maples [MSFT] 3539bd8008 adding /EHsc for msvc cmake target gsl_test_config_noexcept 2019-12-13 13:56:42 -08:00
Jordan Maples [MSFT] 17ad4495fb deprecate gsl::details::throw_exception. remove unused header in gsl_assert. gsl_util to use terminate instead of throw_exception 2019-12-13 13:40:25 -08:00
Jordan Maples [MSFT] 6c5c708877 change from string to char* 2019-12-12 16:48:59 -08:00
Jordan Maples [MSFT] 0931262acf appveyor failed to start, sending dummy commit 2019-12-12 14:39:12 -08:00
Jordan Maples [MSFT] 5099e8fa3e removed string_view for string in tests 2019-12-12 11:15:41 -08:00
Jordan Maples [MSFT] 4f6f05d463 changing text in notices & readme. adding terminate handler for tests 2019-12-12 10:55:26 -08:00
Jordan Maples [MSFT] ec05ecd6b1 dummy commit to trigger appveyor 2019-12-10 11:58:42 -08:00
Jordan Maples [MSFT] 0784866608 added back death test, fixed VS2019 test failures 2019-12-09 16:08:27 -08:00
Jordan Maples 9a88262544 fixing suppression of gtest warnings for gcc 2019-12-06 16:03:47 -08:00
Jordan Maples [MSFT] b39a9732f8 attempting to fix the gtest print issues in vs17 2019-12-04 13:46:50 -08:00
Jordan Maples [MSFT] 87eaa45445 suppressing -Wundef in clang (GTest emitted) 2019-12-04 12:48:13 -08:00
Jordan Maples [MSFT] 43aca2646b ignore warnings from gtest 2019-12-04 12:30:58 -08:00
Jordan Maples [MSFT] 603b4671c1 removing unused function 2019-12-03 15:24:52 -08:00
Jordan Maples [MSFT] 2b10729386 gtest migration 2019-12-03 14:32:25 -08:00
Jordan Maples [MSFT] 7004ef506c adding front and back 2019-11-19 16:03:55 -08:00
Jordan Maples [MSFT] 5e0d76a1a7 deprecating span::at and span::operator() 2019-11-19 14:31:21 -08:00
Jordan Maples [MSFT] 7e99e76c97 Merge pull request #826 from JordanMaples/dev/jomaples/ctad_fix_v2
fix ctad warning in llvm
2019-11-18 13:02:53 -08:00
Jordan Maples [MSFT] 263440f2a1 changing white-space in comment to get tests to rerun 2019-11-18 11:39:36 -08:00
Jordan Maples [MSFT] a7759e6d3f lower __cpp_deduction_guide version number from 201907 to 201611 2019-11-18 10:14:05 -08:00
Jordan Maples [MSFT] 128b4356ac changing check from __cplusplus 201703L to __cpp_deduction_guides 201907L 2019-11-15 16:29:41 -08:00
Jordan Maples [MSFT] 8e481ebe19 adding deduction guide for strict_not_null 2019-11-15 14:41:38 -08:00
Jordan Maples [MSFT] 4610f26b33 forgot comment 2019-11-15 12:43:33 -08:00
Jordan Maples [MSFT] d0e5daf441 fix ctad warning in llvm 2019-11-15 12:11:44 -08:00
Cristian Morales Vega b213c89700 Add missing #include if built with GSL_USE_STD_BYTE=1
cstddef was being included to detect whether GSL_USE_STD_BYTE should be
set to 0 or 1. But if the user provided GSL_USE_STD_BYTE no detection is
required and the header was never included.
2019-11-08 16:37:23 +00:00
Jordan Maples [MSFT] 9939d5889b Merge pull request #822 from JordanMaples/dev/jomaples/lib-byte-check
gsl_byte to inspect __cpp_lib_byte
2019-10-25 11:42:01 -07:00
Jordan Maples 22cba52114 update comments 2019-10-25 10:12:41 -07:00
Jordan Maples 97dc8f83fc adding check to __cpp_lib_byte, which was added to the defn for 15.8 2019-10-24 17:07:42 -07:00
Jordan Maples [MSFT] 71ec9f84d8 Merge pull request #2 from microsoft/master
updating personal branch.
2019-10-23 11:50:25 -07:00
Jordan Maples [MSFT] 3d56ba9e7f Merge pull request #813 from JordanMaples/dev/jomaples/deprecate_multispan
Deprecate multi_span, strided_span, etc
2019-10-09 15:11:59 -07:00
Jordan Maples [MSFT] cf9cc34da8 Merge pull request #815 from matt77hias/patch-1
Added std::exchange (C++14) to make the intent more explicit
2019-10-09 15:05:26 -07:00
Matthias Moulin 0a78d8ea3c Added std::exchange (C++14) to make the intent more explicit 2019-10-07 21:49:50 +02:00
Jordan Maples [MSFT] 02d1051fdd Merge pull request #814 from sizmailov/fix_typos
Fix typos in gsl/pointers
2019-10-06 14:39:57 -07:00
Sergei Izmailov 275e0176c0 Fix typos in gsl/pointers 2019-10-06 19:20:15 +03:00
Jordan Maples 4b289d4cf0 lack of nl for bounds_test 2019-10-04 14:15:24 -07:00
Jordan Maples 6ff4a5287d accidentally commented out pragma 2019-10-04 14:13:54 -07:00
Jordan Maples 2b8f7aea32 adding clang/gcc suppression of the deprecation warnings. 2019-10-04 12:38:55 -07:00
Jordan Maples 7adf7eb6fe new messages 2019-10-03 17:52:49 -07:00
Jordan Maples 5e4463a7c1 removing function deprecation, adding additional class / struct deprecations 2019-10-03 15:47:25 -07:00
Jordan Maples [MSFT] 10ce5b634f Merge pull request #812 from JordanMaples/dev/jomaples/typo_fixes
Fixing typo "Guideline" as "Guidelines"
2019-10-03 09:37:41 -07:00
Jordan Maples eb995b3671 deprecating strided_span 2019-10-02 16:17:46 -07:00
Jordan Maples b630dfe36a Guideline -> Guidelines
fixing issue as reported in issue #746
2019-10-02 15:42:40 -07:00
Jordan Maples e026971c03 deprecation, removing cassert 2019-10-02 15:40:15 -07:00
Jordan Maples bbeb0bdc91 initial deprecation of multi_span and strided_span 2019-09-28 12:54:18 -07:00
Jordan Maples [MSFT] 23066c829f Update README.md 2019-09-04 15:10:14 -07:00
Jordan Maples [MSFT] a454d295ed Merge pull request #803 from B1Z0N/master
Fixed memory leaks and out of bound access
2019-09-04 14:04:47 -07:00
B1Z0N ba9af38494 Merge branch 'master' of https://github.com/B1Z0N/GSL 2019-09-01 00:38:10 +03:00
B1Z0N d5382a293b Fixed memory leaks 2019-09-01 00:36:13 +03:00
B1Z0N 787e7ef616 Thanks to @stayprivates fixed out of bounds access in "TestNotNullostream" 2019-09-01 00:35:04 +03:00
Jordan Maples [MSFT] 1046c9d247 Merge pull request #1 from microsoft/master
updating from root
2019-08-30 12:37:36 -07:00
Jordan Maples [MSFT] b576cc6ce3 Merge pull request #769 from jack17529/patch-1
Update usage of difference_type in span
2019-08-15 14:49:12 -07:00
Jordan Maples [MSFT] 2ce3177ebd Merge pull request #800 from eyalroz/master
Fixes #798 : Dropping inclusion of `gsl/pointers` in `string_span`
2019-08-15 14:42:07 -07:00
Johel Ernesto Guerrero Peña cee1929de7 Fix GNUC typo (#780)
Resolves #779
2019-08-14 12:56:53 -07:00
beinhaerter 1d48188de9 Fixed check if std::byte is available (#764)
The check for std::byte existance fails on gcc 8.2. According to https://en.cppreference.com/w/cpp/utility/feature_test it is necessary to `#include <cstddef>` before checking `__cpp_lib_byte`.
2019-08-14 12:40:35 -07:00
Eyal Rozenberg b05a4464b9 Fixes #798 : Dropped inclusion of gsl/pointers in string_span. 2019-08-05 13:16:42 +03:00
NN 1212beae77 Add Visual Studio 2019 image for tests (#787)
* Add Visual Studio 2019 image for tests

Refer to https://github.com/appveyor/ci/issues/2907
VS2019 is enabled per request.

* Use CMake 3.14

* Fix CMake output directory

* trigger build

* Trigger build
2019-06-12 21:27:49 -07:00
Ian Taylor 66809c6852 make TypeListIndexer constexpr (#733) 2019-06-06 14:16:08 -07:00
Hannes Steffenhagen 0551cad467 Merge branch 'master' into hunterization 2019-05-09 18:09:21 +01:00
Fei Sun b74b286d5e add value_type size_type for string_span (#727) 2019-04-11 10:40:02 -07:00
JACK_1729 2a1ef25406 Update span
About my Issue - https://github.com/Microsoft/GSL/issues/765
2019-02-20 20:25:50 +05:30
Anna Gringauze 7d78b743e4 added clang7.0 to Travis configuration and README (#763) 2019-01-16 19:58:38 -08:00
Anna Gringauze 6418b5f4de Clang cl (#762)
* Added c++17 test configurations for clang5.0 and clang6.0

* Fix #739 correct cppcorecheck warnings for clang-cl

* Add clang-cl  configurations

* Corrections Appveyor;
Temporarily disable msvc compilation for faster testing (#741)

* Add path to clang-cl.exe (#741)

* Escape backslash in path (#741)

* Update vcpkg (#741)

* Check vcpkg version; try without building vcpkg; use latest clang-cl from path (#741)

* Fix blocks in ps script (#741)

* Try accessing APPVEYOR_BUILD_FOLDER variable (#471)

* Update span size() bug confirmation test for GCC 6.5 (#741)

* MSVC flags to Clang-cl; disable c++98-compat and undefined macro warnings (#741)

* Suppress clang warning on tests (missing-prototypes) (#741)

* Fix clang warning -Wnewline-eof (#741)

* Fix clang warning -Wdouble-promotion (#741)

* Set linker explicitly

* Clean condition statement

* For Clang, fallback to the AppVeyor installed version of CMake

* Fix clang warning -Wmissing-variable-declarations

* Fallback to the MSVC linker until vcpkg has been updated

* Revert "Fallback to the MSVC linker until vcpkg has been updated"

This reverts commit 7263f3289e.

* Fix clang warning -Wunused-member-function

* Fix clang warning -Wmissing-noreturn

* Fix clang warning -Winvalid-noreturn on Windows

* Add macro block end comment on large #if blocks

* Workaround: fallback to mscv link.exe

* Workaround: get msvc paths into PowerShell through intermediate file

* Workaround: fix, remove "PATH=" from text

* Workaround: try with full-path; and return user PATH

* Workaround: fix, escape backslashes

* Revert all since "Workaround: fallback to mscv link.exe" did not work on AppVeyor

This reverts the commits:
bda3d6a428
97062933ac
0f4fb04bac
1b0c19afd1
a5739ea5f0

* Suppress output of git pull; remove vcpkg from cache

* Re-enable AppVeyor builds for all platforms

* Correct typo

Co-Authored-By: Farwaykorse <Farwaykorse@users.noreply.github.com>

* Add Clang-cl 7.0.0 to the supported platforms

* Revert "Fix clang warning -Wunused-member-function"

This reverts commit 6fe1a42035.

* Fix or locally suppress clang warning -Wunused-member-function

* format touched code and correct comment

* git pull --quiet

* fix logic error in workaround

* fix missing bracket

* Suppress output of mkdir

* Replace MSBuild with Ninja

* Suppress output of 7z

* Add architecture flags for Clang

* Drop workaround for lld-link

* 7-zip Overwrite and Alternative output suppression without suppressing errors

Replaces 3c1c0794dd

* AppVeyor setup and CMake before build

* reorder compiler configuration

* remove unnecessary

* remove -fno-strict-aliasing

* remove -Wsign-conversion, since before v4.0 part of -Wconversion

* -Wctor-dtor-privacy is GCC only

* remove -Woverloaded-virtual part of -Wmost, part of -Wall

* add -Wmissing-noreturn

* remove the pragmas for -Wunused-member-function

* Re-add MSBuild generator on AppVeyor

* Print CMake commands

* Add MSBuild toolset selection

* Separate Architecture setting

* clang-cl: add -Weverything

* clang-cl -Wno-c++98-compat

* clang-cl -Wno-c++98-compat-pedantic

* clang-cl -Wno-missing-prototypes

* clang-cl C++14 -Wno-unused-member-function

* clang-cl -Wundef __GNUC__

* clang++: add -Weverything

* clang++ -Wno-c++98-compat

* clang++ -Wno-c++98-compat-pedantic

* clang++ -Wno-missing-prototypes

* clang++ -Wno-weak-vtables

* clang++ C++14 -Wno-unused-member-function

* clang++ fix -Wundef _MSC_VER

* clang++ -Wno-padded

* clang++ solve -Wdeprecated

* Add AppleClang compiler target
Since CMake v3.0 use of Clang for both is deprecated

* clang++ v5.0 C++17 -Wno-undefined-func-template

* Add VS2015 + LLVM/clang-cl to AppVeyor

* Do not disable constexpr when compiling with clang-cl on Windows

* Clean-up clang-only warnings (now under -Weverything)

* Revert "Fix clang warning -Winvalid-noreturn on Windows"

This reverts commit 2238c4760e.

* Suppress -Winvalid-noreturn for the MS STL noexception workaround

* CMake: put preprocessor definition in target_compile_definitions

* Solve compiler warning C4668: __GNUC__ not defined
2019-01-15 10:27:34 -08:00
Johel Ernesto Guerrero Peña 6eeed739f1 Make narrow constexpr (#698) 2019-01-14 18:37:37 -08:00
Anna Gringauze 9ff6e19ea9 Dev/annagrin/remove explicit not null constructor (#743)
* Added c++17 test configurations for clang5.0 and clang6.0

* Removed explicit not_null constructor, sloppy_not_null, added strict_not_null

We added explicit not_null constructor in version 2.0.0.
It proved very difficult to switch to the new version for
large code bases that adopted previous versions of gsl,
due to not_null used extensively in the code. Still, using
explicit constructor is very benefitial for new code, since
it encorages better API design and make null checks intentional.

To resolve the issue, this change:
- removes explicit keyword from not_null constructor
- removes unneded sloppy_not_null type
- adds strict_not_null type to behave the same way as v2 not_null
- updates tests

* Removed explicit not_null constructor, sloppy_not_null, added strict_not_null

We added explicit not_null constructor in version 2.0.0.
It proved very difficult to switch to the new version for
large code bases that adopted previous versions of gsl,
due to not_null used extensively in the code. Still, using
explicit constructor is very benefitial for new code, since
it encorages better API design and make null checks intentional.

To resolve the issue, this change:
- removes explicit keyword from not_null constructor
- removes unneded sloppy_not_null type
- adds strict_not_null type to behave the same way as v2 not_null
- updates tests

* fixed build break for gcc7

* added more tests

* added more non-compiling tests

* Addressed PR comments and suppressed a code analysis warning

* Fixed test failure in not_null tests
2019-01-14 16:45:47 -08:00
Alex Green 7a7d025ffa Make CheckRange constexpr (#754) (#755) 2019-01-14 16:44:45 -08:00
k-brac be3c3c2731 Fixes CMAKE_VERSION check (#759)
* Fixes CMAKE_VERSION check

Fixes #758 by using the correct comparison operator for a version
See documentation at https://cmake.org/cmake/help/latest/command/if.html
Thanks to this change, gsl natvis is properly included in a visual studio solution

* cmake version check for cmake < 3.7
2019-01-14 16:43:17 -08:00
hannesweisbach 0f68d133fa Suppress Warnings in GSL Headers (#731)
Suppress warnings in GSL headers using the SYSTEM keyword for target_include_directories(). This enables developers to see warnings standalone builds but hides them from users in non-standalone builds.
2018-11-28 15:37:59 -08:00
beinhaerter 88aca1caf3 added noexcept to get rid off VC warning con.4 (#748) 2018-11-28 11:57:43 -08:00
Stefan Dinkelacker 2e4d0d7e22 Fix spelling of library name (#747) 2018-11-28 11:53:38 -08:00
kile0 5a7093f983 Use the c++17 constexpr if in CheckRange if possible (#753)
* change c++17 to use constexpr if in CheckRange

* remove unnecessary macro

* use the portable feature test macro rather than direct version check
2018-11-28 11:52:11 -08:00
Anna Gringauze b673375719 Dev/annagrin/fix span size test gcc (#750)
* Added c++17 test configurations for clang5.0 and clang6.0

* fixed test for broken span.size() in gcc6.5
2018-11-27 17:28:57 -08:00
Dave Hill c02ddae4bc Span can be constructed from empty std::array safely (#686)
* Span std::array c'tor uses arr.data() instead of &arr[0]
- Fixes runtime issues when constructing from an empty std::array

* Construct span with std::data if C++17 detected

* Specialize span c'tor for std::array of length 0, set storage to nullptr
2018-11-05 15:39:41 -08:00
Ian Taylor 2bf9f137a6 make BoundsRanges constexpr (#732)
* make BoundsRanges constexpr

* fix clang compilation error

* fix windows compilation
2018-11-05 15:26:27 -08:00
Stefan Reinhold 457fb25609 Merge branch 'hunterization' of github.com:ithron/GSL into hunterization 2018-09-07 17:27:54 +02:00
Stefan Reinhold 8428e083e4 Merge branch 'master' into hunterization 2018-09-07 17:27:31 +02:00
Stefan Reinhold 73022d1103 Merge branch 'master' into hunterization 2018-08-03 00:53:40 +02:00
Stefan Reinhold ffe8ffb452 Dummy commit to force CI re-run 2018-07-18 09:35:36 +02:00
Stefan Reinhold e3ffe1c5cb Fix naming of exported CMake configuration file 2018-07-17 17:56:11 +02:00
Stefan Reinhold e2b57d16f9 Export target GSL in namespace Microsoft.GSL
This is to avoid conflicts with GNU Scientific Library which also has an
exported target named GSL.
2018-07-17 17:43:54 +02:00
Stefan Reinhold 9e1645b990 Do not install .natvis files.
This fixes an issue where CMake complains about INTERFACE_SOURCES
containing a path which is prefixed in source directory on windows.
2018-07-17 13:07:27 +02:00
Stefan Reinhold 0a31a14d09 Fix INSTALL_INTERFACE for exported target
CMake war reporting: 'Target "GSL" INTERFACE_SOURCES property contains
path: "..." which is prefixed in the source directory'.
CMake was confused because the $<BUILD_INTERFACE: ...> had linebreaks
in it.
Putting everything in one line fixed the issue.
2018-07-17 11:56:38 +02:00
Stefan Reinhold 030454e3e9 Fix for Windows: CMake complains about INTERFACE_SOURCES directory 2018-07-17 11:09:58 +02:00
Stefan Reinhold d452c3b061 Make library importable by CMake using find_package 2018-07-17 10:23:44 +02:00
ericLemanissier 423841e965 fix requirement on not_null template
it should be comparable to nullptr, it does not have to be assignable
2018-05-03 08:08:41 +02:00
68 changed files with 8891 additions and 10135 deletions
+1 -1
View File
@@ -31,4 +31,4 @@ AlignConsecutiveAssignments: false
AlignTrailingComments: true
SpaceAfterCStyleCast: true
CommentPragmas: '^ NO-FORMAT:'
WhitespaceSensitiveMacros: [GSL_SUPPRESS]
+1
View File
@@ -0,0 +1 @@
include/gsl/* linguist-language=C++
+29
View File
@@ -0,0 +1,29 @@
---
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 <gsl>
// 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.
+84
View File
@@ -0,0 +1,84 @@
# GitHub Copilot Instructions for GSL (Guidelines Support Library)
## Project Overview
This repository contains the Guidelines Support Library (GSL), a Microsoft implementation of types and functions
suggested for use by the C++ Core Guidelines. It's a header-only C++ library with emphasis on safety,
correctness, and zero overhead.
## Coding Standards
### General
- Follow C++ Core Guidelines wherever possible
- Use meaningful type, function, and template parameter names
- Keep functions small and focused with clear preconditions/postconditions
- Include comments for complex code, but prefer self-documenting code
- Use the Expects() and Ensures() macros for contract verification
### Style Guidelines
- Use 4 spaces for indentation (not tabs)
- Maximum line length of 100 characters
- Follow GSL naming conventions (lowercase with underscores)
- Keep templates clean and readable with appropriate spacing
- Use C++14 features since this is the minimum standard supported
### Error Handling
- Use Expects() for preconditions and Ensures() for postconditions
- Design for fail-fast semantics (std::terminate) on contract violations
- Template constraints should use static_assert or SFINAE
- Don't throw exceptions from basic operations
### Testing
- Write thorough unit tests for every component using GTest
- Test for all edge cases and error conditions
- Ensure cross-platform compatibility in tests
- Maintain 100% code coverage for changed code
## Project-Specific Conventions
### Architecture
- All public types must be in the gsl namespace
- Design for zero overhead abstractions when possible
- Respect the distinction between Owners and Views
- Maintain backward compatibility with existing GSL code
### Version Control
- Link all PRs to related issues
- Use clear commit messages explaining what and why
- Follow the contribution guidelines documented in CONTRIBUTING.md
- PRs should include appropriate tests with 100% coverage for changed code
### Documentation
- Document all public APIs with clarity on preconditions and postconditions
- Keep header comments up-to-date
- Include examples for complex functionality in docs/headers.md
## Technology Stack
- C++14 (minimum) for core implementation
- CMake build system (3.14+)
- Google Test for unit testing
- Support for multiple compilers (MSVC, GCC, Clang)
## Security Considerations
- Bounds checking is a core principle - enforce it consistently
- Design for safety while minimizing overhead
- Ensure undefined behavior is explicitly detected where possible
## Performance Guidelines
- Optimize for both safety and performance
- Constexpr-enable functions wherever possible
- Avoid hidden allocations
- Use noexcept appropriately for move operations and other performance-critical functions
## Cross-Platform Support
- Code must work across:
- Windows (MSVC)
- Linux (GCC, Clang)
- macOS (AppleClang)
- Android and iOS where applicable
## Copilot Tasks
- You can find the CMake artifacts for C++20 in build-cxx20 and C++14 in build-cxx14.
- Before publishing a PR, verify the following:
- There are no compiler warnings or errors when building the test suite.
- The test suite passes on all supported platforms and compilers.
- The test suite passes for both C++14 and C++20.
+59
View File
@@ -0,0 +1,59 @@
name: 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@v6
- name: Create build directory
run: mkdir -p build
working-directory: .
- uses: actions/setup-java@v5
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 {} \\\;
+39
View File
@@ -0,0 +1,39 @@
name: Code Formatting
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
permissions:
contents: read
env:
CLANG_VERSION: "20"
jobs:
clang-format:
name: Run clang-format
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
# Install the exact clang-format binary
- name: Install clang-format
run: |
sudo apt install clang-format-${{ env.CLANG_VERSION }}
# Prints the version of clang-format being used
- name: Log clang-format version
run: clang-format-${{ env.CLANG_VERSION }} --version
# Runs clang-format over the repository codebase
- name: Check format
run: |
{
find include/gsl -type f
find tests -type f \( -name '*.cpp' -o -name '*.h' \)
} | xargs clang-format-${{ env.CLANG_VERSION }} --dry-run --Werror
+33
View File
@@ -0,0 +1,33 @@
name: Composite CMake
inputs:
cmake_preset:
required: true
type: string
extra_cmake_build_args:
required: false
type: string
default: ''
extra_cmake_configure_args:
required: false
type: string
default: ''
extra_ctest_args:
required: false
type: string
default: ''
runs:
using: composite
steps:
- name: Configure CMake
run: cmake --preset ${{ inputs.cmake_preset }} ${{ inputs.extra_cmake_configure_args }} -DCI_TESTING:BOOL=ON -DCMAKE_VERBOSE_MAKEFILE:BOOL=ON -Werror=dev
shell: ${{ env.RUNNER_OS == 'Windows' && 'pwsh' || 'bash' }}
- name: Build (with preset)
run: cmake --build --preset ${{ inputs.cmake_preset }} ${{ inputs.extra_cmake_build_args }}
shell: ${{ env.RUNNER_OS == 'Windows' && 'pwsh' || 'bash' }}
- name: Test (with preset)
run: ctest --preset ${{ inputs.cmake_preset }} ${{ inputs.extra_ctest_args }} --output-on-failure --no-compress-output
shell: ${{ env.RUNNER_OS == 'Windows' && 'pwsh' || 'bash' }}
+25
View File
@@ -0,0 +1,25 @@
name: 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@v6
- 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
+106
View File
@@ -0,0 +1,106 @@
name: 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@v6
- name: Run CMake (configure, build, test)
uses: ./.github/workflows/cmake
with:
cmake_preset: gcc-${{ matrix.cxx_version }}-${{ matrix.build_type == 'Debug' && 'debug' || 'release' }}
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@v6
- name: Run CMake (configure, build, test)
uses: ./.github/workflows/cmake
with:
cmake_preset: clang-${{ matrix.cxx_version }}-${{ matrix.build_type == 'Debug' && 'debug' || 'release' }}
xcode:
strategy:
matrix:
xcode_version: [ '16.4' ]
build_type: [ Debug, Release ]
cxx_version: [ 14, 17, 20, 23 ]
runs-on: macos-latest
steps:
- uses: actions/checkout@v6
- 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_preset: clang-${{ matrix.cxx_version }}-${{ matrix.build_type == 'Debug' && 'debug' || 'release' }}
extra_cmake_configure_args: '-DCMAKE_CXX_FLAGS="-isysroot \"$(xcode-select --print-path)/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk\""'
msvc:
strategy:
matrix:
image: [ windows-2022, windows-2025 ]
build_type: [ Debug, Release ]
toolset: [ 'msvc', 'ClangCL' ]
cxx_version: [ 14, 17, 20, 23 ]
include:
# Regular MSVC builds use Ninja (from preset)
- toolset: 'msvc'
generator_override: ''
# ClangCL builds require Visual Studio generator
- toolset: 'ClangCL'
generator_override: '-G "Visual Studio 17 2022" -T ClangCL'
runs-on: ${{ matrix.image }}
steps:
- uses: actions/checkout@v6
- uses: microsoft/setup-msbuild@v3
- uses: ilammy/msvc-dev-cmd@v1
- name: Run CMake (configure, build, test)
uses: ./.github/workflows/cmake
with:
cmake_preset: msvc-${{ matrix.cxx_version }}-${{ matrix.build_type == 'Debug' && 'debug' || 'release' }}
extra_cmake_configure_args: ${{ matrix.generator_override }}
extra_cmake_build_args: ${{ matrix.toolset == 'ClangCL' && format('--config {0}', matrix.build_type) || '' }}
extra_ctest_args: ${{ matrix.toolset == 'ClangCL' && format('-C {0}', matrix.build_type) || '' }}
+21
View File
@@ -0,0 +1,21 @@
name: "Copilot Setup Steps"
on: workflow_dispatch
jobs:
copilot-setup-steps:
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout code
uses: actions/checkout@v6
- name: Install Build Dependencies
run: sudo apt-get update && sudo apt-get install -y clang cmake make
- name: Configure CMake (C++14)
run: cmake --preset clang-14-debug
- name: Configure CMake (C++20)
run: cmake --preset clang-20-debug
+53
View File
@@ -0,0 +1,53 @@
name: 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@v6
- 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=12.0 \
-DCMAKE_TRY_COMPILE_TARGET_TYPE=STATIC_LIBRARY \
"-DMACOSX_BUNDLE_GUI_IDENTIFIER=GSL.\$(EXECUTABLE_NAME)" \
-DMACOSX_BUNDLE_BUNDLE_VERSION=4.2.0 \
-DMACOSX_BUNDLE_SHORT_VERSION_STRING=4.2.0 \
-DCMAKE_CXX_FLAGS="-Wno-missing-include-dirs" \
..
- 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
+32
View File
@@ -0,0 +1,32 @@
name: Shell script linter
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
permissions:
contents: read
jobs:
clang-format:
name: Run shfmt and shellcheck
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
# Install the needed binaries
- name: Install shfmt and shellcheck
run: |
sudo apt install shfmt shellcheck
- name: Check format
run: |
find scripts -type f -name '*.sh' -exec shfmt -l {} \;
- name: Run shellcheck
run: |
find scripts -type f -name '*.sh' -exec shellcheck {} \;
+1 -1
View File
@@ -1,5 +1,5 @@
CMakeFiles
build
build*/
tests/CMakeFiles
tests/Debug
*.opensdf
-273
View File
@@ -1,273 +0,0 @@
# Based on https://github.com/ldionne/hana/blob/master/.travis.yml
language: cpp
sudo: false
notifications:
email: false
# Use Linux unless specified otherwise
os: linux
dist: trusty
cache:
directories:
- ${TRAVIS_BUILD_DIR}/deps
matrix:
include:
##########################################################################
# Clang on OSX
# Travis seems to take longer to start OSX instances,
# so leave this first for the overall build to be faster
##########################################################################
# XCode 8.3
- env: COMPILER=clang++ BUILD_TYPE=Debug GSL_CXX_STANDARD=14
os: osx
osx_image: xcode8.3
compiler: clang
- env: COMPILER=clang++ BUILD_TYPE=Release GSL_CXX_STANDARD=14
os: osx
osx_image: xcode8.3
compiler: clang
# XCode 9.1
- env: COMPILER=clang++ BUILD_TYPE=Debug GSL_CXX_STANDARD=14
os: osx
osx_image: xcode9.1
compiler: clang
- env: COMPILER=clang++ BUILD_TYPE=Release GSL_CXX_STANDARD=14
os: osx
osx_image: xcode9.1
compiler: clang
##########################################################################
# Clang on Linux
##########################################################################
# Clang 3.6
- env: COMPILER=clang++-3.6 BUILD_TYPE=Debug GSL_CXX_STANDARD=14
addons: &clang36
apt:
packages:
- clang-3.6
- g++-5
sources:
- ubuntu-toolchain-r-test
- llvm-toolchain-precise-3.6
- env: COMPILER=clang++-3.6 BUILD_TYPE=Release GSL_CXX_STANDARD=14
addons: *clang36
# Clang 3.7
- env: COMPILER=clang++-3.7 BUILD_TYPE=Debug GSL_CXX_STANDARD=14
addons: &clang37
apt:
packages:
- clang-3.7
- g++-5
sources:
- ubuntu-toolchain-r-test
- llvm-toolchain-precise-3.7
- env: COMPILER=clang++-3.7 BUILD_TYPE=Release GSL_CXX_STANDARD=14
addons: *clang37
# Clang 3.8
- env: COMPILER=clang++-3.8 BUILD_TYPE=Debug GSL_CXX_STANDARD=14
addons: &clang38
apt:
packages:
- clang-3.8
- g++-5
sources:
- ubuntu-toolchain-r-test
- llvm-toolchain-precise-3.8
- env: COMPILER=clang++-3.8 BUILD_TYPE=Release GSL_CXX_STANDARD=14
addons: *clang38
# Clang 3.9
- env: COMPILER=clang++-3.9 BUILD_TYPE=Debug GSL_CXX_STANDARD=14
addons: &clang39
apt:
packages:
- clang-3.9
- g++-5
sources:
- ubuntu-toolchain-r-test
- llvm-toolchain-precise-3.9
- env: COMPILER=clang++-3.9 BUILD_TYPE=Release GSL_CXX_STANDARD=14
addons: *clang39
# Clang 4.0
- env: COMPILER=clang++-4.0 BUILD_TYPE=Debug GSL_CXX_STANDARD=14
addons: &clang40
apt:
packages:
- clang-4.0
- g++-5
sources:
- ubuntu-toolchain-r-test
- llvm-toolchain-trusty-4.0
- env: COMPILER=clang++-4.0 BUILD_TYPE=Release GSL_CXX_STANDARD=14
addons: *clang40
# Clang 5.0
- env: COMPILER=clang++-5.0 BUILD_TYPE=Debug GSL_CXX_STANDARD=14
addons: &clang50
apt:
packages:
- clang-5.0
- g++-7
sources:
- ubuntu-toolchain-r-test
- llvm-toolchain-trusty-5.0
- sourceline: 'deb http://apt.llvm.org/trusty/ llvm-toolchain-trusty-5.0 main'
key_url: 'https://apt.llvm.org/llvm-snapshot.gpg.key'
- env: COMPILER=clang++-5.0 BUILD_TYPE=Release GSL_CXX_STANDARD=14
addons: *clang50
- env: COMPILER=clang++-5.0 BUILD_TYPE=Debug GSL_CXX_STANDARD=17
addons: *clang50
- env: COMPILER=clang++-5.0 BUILD_TYPE=Release GSL_CXX_STANDARD=17
addons: *clang50
# Clang 6.0
- env: COMPILER=clang++-6.0 BUILD_TYPE=Debug GSL_CXX_STANDARD=14
addons: &clang60
apt:
packages:
- clang-6.0
- g++-7
sources:
- ubuntu-toolchain-r-test
- llvm-toolchain-trusty-6.0
- sourceline: 'deb http://apt.llvm.org/trusty/ llvm-toolchain-trusty-6.0 main'
key_url: 'https://apt.llvm.org/llvm-snapshot.gpg.key'
- env: COMPILER=clang++-6.0 BUILD_TYPE=Release GSL_CXX_STANDARD=14
addons: *clang60
# Clang 6.0 c++17
- env: COMPILER=clang++-6.0 BUILD_TYPE=Debug GSL_CXX_STANDARD=17
addons: *clang60
- env: COMPILER=clang++-6.0 BUILD_TYPE=Release GSL_CXX_STANDARD=17
addons: *clang60
##########################################################################
# GCC on Linux
##########################################################################
# GCC 5
- env: COMPILER=g++-5 BUILD_TYPE=Debug GSL_CXX_STANDARD=14
addons: &gcc5
apt:
packages: g++-5
sources:
- ubuntu-toolchain-r-test
- env: COMPILER=g++-5 BUILD_TYPE=Release GSL_CXX_STANDARD=14
addons: *gcc5
# GCC 6
- env: COMPILER=g++-6 BUILD_TYPE=Debug GSL_CXX_STANDARD=14
addons: &gcc6
apt:
packages: g++-6
sources:
- ubuntu-toolchain-r-test
- env: COMPILER=g++-6 BUILD_TYPE=Release GSL_CXX_STANDARD=14
addons: *gcc6
# GCC 7
- env: COMPILER=g++-7 BUILD_TYPE=Debug GSL_CXX_STANDARD=14
addons: &gcc7
apt:
packages: g++-7
sources:
- ubuntu-toolchain-r-test
- env: COMPILER=g++-7 BUILD_TYPE=Release GSL_CXX_STANDARD=14
addons: *gcc7
# GCC 7 c++17
- env: COMPILER=g++-7 BUILD_TYPE=Debug GSL_CXX_STANDARD=17
addons: *gcc7
- env: COMPILER=g++-7 BUILD_TYPE=Release GSL_CXX_STANDARD=17
addons: *gcc7
install:
# Set the ${CXX} variable properly
- export CXX=${COMPILER}
- ${CXX} --version
# Dependencies required by the CI are installed in ${TRAVIS_BUILD_DIR}/deps/
- DEPS_DIR="${TRAVIS_BUILD_DIR}/deps"
- mkdir -p "${DEPS_DIR}"
- cd "${DEPS_DIR}"
# Travis machines have 2 cores
- JOBS=2
############################################################################
# Install a recent CMake (unless already installed on OS X)
############################################################################
- CMAKE_VERSION=3.7.2
- |
if [[ "${TRAVIS_OS_NAME}" == "linux" ]]; then
CMAKE_URL="https://cmake.org/files/v${CMAKE_VERSION%.[0-9]}/cmake-${CMAKE_VERSION}-Linux-x86_64.tar.gz"
mkdir cmake && travis_retry wget --no-check-certificate -O - ${CMAKE_URL} | tar --strip-components=1 -xz -C cmake
export PATH=${DEPS_DIR}/cmake/bin:${PATH}
else
brew install cmake || brew upgrade cmake
fi
- cmake --version
############################################################################
# [linux]: Install the right version of libc++
############################################################################
- |
LLVM_INSTALL=${DEPS_DIR}/llvm/install
# if in linux and compiler clang and llvm not installed
if [[ "${TRAVIS_OS_NAME}" == "linux" && "${CXX%%+*}" == "clang" && -n "$(ls -A ${LLVM_INSTALL})" ]]; then
if [[ "${CXX}" == "clang++-3.6" ]]; then LLVM_VERSION="3.6.2";
elif [[ "${CXX}" == "clang++-3.7" ]]; then LLVM_VERSION="3.7.1";
elif [[ "${CXX}" == "clang++-3.8" ]]; then LLVM_VERSION="3.8.1";
elif [[ "${CXX}" == "clang++-3.9" ]]; then LLVM_VERSION="3.9.1";
fi
LLVM_URL="http://llvm.org/releases/${LLVM_VERSION}/llvm-${LLVM_VERSION}.src.tar.xz"
LIBCXX_URL="http://llvm.org/releases/${LLVM_VERSION}/libcxx-${LLVM_VERSION}.src.tar.xz"
LIBCXXABI_URL="http://llvm.org/releases/${LLVM_VERSION}/libcxxabi-${LLVM_VERSION}.src.tar.xz"
mkdir -p llvm llvm/build llvm/projects/libcxx llvm/projects/libcxxabi
travis_retry wget -O - ${LLVM_URL} | tar --strip-components=1 -xJ -C llvm
travis_retry wget -O - ${LIBCXX_URL} | tar --strip-components=1 -xJ -C llvm/projects/libcxx
travis_retry wget -O - ${LIBCXXABI_URL} | tar --strip-components=1 -xJ -C llvm/projects/libcxxabi
(cd llvm/build && cmake .. -DCMAKE_INSTALL_PREFIX=${LLVM_INSTALL})
(cd llvm/build/projects/libcxx && make install -j2)
(cd llvm/build/projects/libcxxabi && make install -j2)
export CXXFLAGS="-isystem ${LLVM_INSTALL}/include/c++/v1"
export LDFLAGS="-L ${LLVM_INSTALL}/lib -l c++ -l c++abi"
export LD_LIBRARY_PATH="${LD_LIBRARY_PATH}:${LLVM_INSTALL}/lib"
fi
before_script:
# have CMake to generate build files
- cd "${TRAVIS_BUILD_DIR}"
- mkdir build && cd build
- cmake .. -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DGSL_CXX_STANDARD=$GSL_CXX_STANDARD
script:
# build and run tests
- cmake --build . -- -j${JOBS}
- ctest --output-on-failure -j${JOBS}
+38 -74
View File
@@ -1,84 +1,48 @@
cmake_minimum_required(VERSION 3.1.3)
cmake_minimum_required(VERSION 3.14...3.16)
project(GSL CXX)
project(GSL VERSION 4.2.0 LANGUAGES CXX)
include(ExternalProject)
find_package(Git)
# creates a library GSL which is an interface (header files only)
add_library(GSL INTERFACE)
add_library(Microsoft.GSL::GSL ALIAS GSL)
# determine whether this is a standalone project or included by other projects
set(GSL_STANDALONE_PROJECT OFF)
if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)
set(GSL_STANDALONE_PROJECT ON)
endif ()
# 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)
set(GSL_CXX_STANDARD "14" CACHE STRING "Use c++ standard")
set(GSL_CXX_STD "cxx_std_${GSL_CXX_STANDARD}")
option(GSL_INSTALL "Generate and install GSL target" ${PROJECT_IS_TOP_LEVEL})
option(GSL_TEST "Build and perform GSL tests" ${PROJECT_IS_TOP_LEVEL})
if (MSVC)
set(GSL_CXX_STD_OPT "-std:c++${GSL_CXX_STANDARD}")
else()
set(GSL_CXX_STD_OPT "-std=c++${GSL_CXX_STANDARD}")
endif()
# The implementation generally assumes a platform that implements C++14 support
target_compile_features(GSL INTERFACE "cxx_std_14")
# when minimum version required is 3.8.0 remove if below
# both branches do exactly the same thing
if (CMAKE_VERSION VERSION_LESS 3.7.9)
include(CheckCXXCompilerFlag)
CHECK_CXX_COMPILER_FLAG("${GSL_CXX_STD_OPT}" COMPILER_SUPPORTS_CXX_STANDARD)
# Setup include directory
add_subdirectory(include)
if(COMPILER_SUPPORTS_CXX_STANDARD)
target_compile_options(GSL INTERFACE "${GSL_CXX_STD_OPT}")
else()
message(FATAL_ERROR "The compiler ${CMAKE_CXX_COMPILER} has no c++${GSL_CXX_STANDARD} support. Please use a different C++ compiler.")
endif()
else ()
target_compile_features(GSL INTERFACE "${GSL_CXX_STD}")
# on *nix systems force the use of -std=c++XX instead of -std=gnu++XX (default)
set(CMAKE_CXX_EXTENSIONS OFF)
endif()
target_sources(GSL INTERFACE $<BUILD_INTERFACE:${GSL_SOURCE_DIR}/GSL.natvis>)
# add definitions to the library and targets that consume it
target_compile_definitions(GSL INTERFACE
$<$<CXX_COMPILER_ID:MSVC>:
# remove unnecessary warnings about unchecked iterators
_SCL_SECURE_NO_WARNINGS
# remove deprecation warnings about std::uncaught_exception() (from catch)
_SILENCE_CXX17_UNCAUGHT_EXCEPTION_DEPRECATION_WARNING
>
)
# add include folders to the library and targets that consume it
target_include_directories(GSL INTERFACE
$<BUILD_INTERFACE:
${CMAKE_CURRENT_SOURCE_DIR}/include
>
)
if ((CMAKE_VERSION GREATER 3.7.9) OR (CMAKE_VERSION EQUAL 3.7.9))
if (MSVC_IDE)
option(VS_ADD_NATIVE_VISUALIZERS "Configure project to use Visual Studio native visualizers" TRUE)
else()
set(VS_ADD_NATIVE_VISUALIZERS FALSE CACHE INTERNAL "Native visualizers are Visual Studio extension" FORCE)
endif()
# add natvis file to the library so it will automatically be loaded into Visual Studio
if(VS_ADD_NATIVE_VISUALIZERS)
target_sources(GSL INTERFACE
${CMAKE_CURRENT_SOURCE_DIR}/GSL.natvis
)
endif()
endif()
install(
DIRECTORY include/gsl
DESTINATION include
)
option(GSL_TEST "Generate tests." ${GSL_STANDALONE_PROJECT})
if (GSL_TEST)
enable_testing()
add_subdirectory(tests)
endif ()
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()
+459
View File
@@ -0,0 +1,459 @@
{
"version": 3,
"configurePresets": [
{
"name": "base",
"hidden": true,
"binaryDir": "${sourceDir}/build/${presetName}",
"installDir": "${sourceDir}/install/${presetName}",
"generator": "Ninja",
"cacheVariables": {
"GSL_CXX_STANDARD": "14",
"GSL_TEST": "ON"
}
},
{
"name": "msvc-base",
"inherits": "base",
"hidden": true,
"condition": {
"type": "equals",
"lhs": "${hostSystemName}",
"rhs": "Windows"
},
"cacheVariables": {
"CMAKE_CXX_COMPILER": "cl"
}
},
{
"name": "gcc-base",
"inherits": "base",
"hidden": true,
"cacheVariables": {
"CMAKE_CXX_COMPILER": "g++",
"CMAKE_C_COMPILER": "gcc"
}
},
{
"name": "clang-base",
"inherits": "base",
"hidden": true,
"cacheVariables": {
"CMAKE_CXX_COMPILER": "clang++",
"CMAKE_C_COMPILER": "clang"
}
},
{
"name": "msvc-14-debug",
"displayName": "MSVC C++14 Debug",
"inherits": "msvc-base",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Debug",
"GSL_CXX_STANDARD": "14"
}
},
{
"name": "msvc-14-release",
"displayName": "MSVC C++14 Release",
"inherits": "msvc-base",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Release",
"GSL_CXX_STANDARD": "14"
}
},
{
"name": "msvc-17-debug",
"displayName": "MSVC C++17 Debug",
"inherits": "msvc-base",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Debug",
"GSL_CXX_STANDARD": "17"
}
},
{
"name": "msvc-17-release",
"displayName": "MSVC C++17 Release",
"inherits": "msvc-base",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Release",
"GSL_CXX_STANDARD": "17"
}
},
{
"name": "msvc-20-debug",
"displayName": "MSVC C++20 Debug",
"inherits": "msvc-base",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Debug",
"GSL_CXX_STANDARD": "20"
}
},
{
"name": "msvc-20-release",
"displayName": "MSVC C++20 Release",
"inherits": "msvc-base",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Release",
"GSL_CXX_STANDARD": "20"
}
},
{
"name": "msvc-23-debug",
"displayName": "MSVC C++23 Debug",
"inherits": "msvc-base",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Debug",
"GSL_CXX_STANDARD": "23"
}
},
{
"name": "msvc-23-release",
"displayName": "MSVC C++23 Release",
"inherits": "msvc-base",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Release",
"GSL_CXX_STANDARD": "23"
}
},
{
"name": "gcc-14-debug",
"displayName": "GCC C++14 Debug",
"inherits": "gcc-base",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Debug",
"GSL_CXX_STANDARD": "14"
}
},
{
"name": "gcc-14-release",
"displayName": "GCC C++14 Release",
"inherits": "gcc-base",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Release",
"GSL_CXX_STANDARD": "14"
}
},
{
"name": "gcc-17-debug",
"displayName": "GCC C++17 Debug",
"inherits": "gcc-base",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Debug",
"GSL_CXX_STANDARD": "17"
}
},
{
"name": "gcc-17-release",
"displayName": "GCC C++17 Release",
"inherits": "gcc-base",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Release",
"GSL_CXX_STANDARD": "17"
}
},
{
"name": "gcc-20-debug",
"displayName": "GCC C++20 Debug",
"inherits": "gcc-base",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Debug",
"GSL_CXX_STANDARD": "20"
}
},
{
"name": "gcc-20-release",
"displayName": "GCC C++20 Release",
"inherits": "gcc-base",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Release",
"GSL_CXX_STANDARD": "20"
}
},
{
"name": "gcc-23-debug",
"displayName": "GCC C++23 Debug",
"inherits": "gcc-base",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Debug",
"GSL_CXX_STANDARD": "23"
}
},
{
"name": "gcc-23-release",
"displayName": "GCC C++23 Release",
"inherits": "gcc-base",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Release",
"GSL_CXX_STANDARD": "23"
}
},
{
"name": "clang-14-debug",
"displayName": "Clang C++14 Debug",
"inherits": "clang-base",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Debug",
"GSL_CXX_STANDARD": "14"
}
},
{
"name": "clang-14-release",
"displayName": "Clang C++14 Release",
"inherits": "clang-base",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Release",
"GSL_CXX_STANDARD": "14"
}
},
{
"name": "clang-17-debug",
"displayName": "Clang C++17 Debug",
"inherits": "clang-base",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Debug",
"GSL_CXX_STANDARD": "17"
}
},
{
"name": "clang-17-release",
"displayName": "Clang C++17 Release",
"inherits": "clang-base",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Release",
"GSL_CXX_STANDARD": "17"
}
},
{
"name": "clang-20-debug",
"displayName": "Clang C++20 Debug",
"inherits": "clang-base",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Debug",
"GSL_CXX_STANDARD": "20"
}
},
{
"name": "clang-20-release",
"displayName": "Clang C++20 Release",
"inherits": "clang-base",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Release",
"GSL_CXX_STANDARD": "20"
}
},
{
"name": "clang-23-debug",
"displayName": "Clang C++23 Debug",
"inherits": "clang-base",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Debug",
"GSL_CXX_STANDARD": "23"
}
},
{
"name": "clang-23-release",
"displayName": "Clang C++23 Release",
"inherits": "clang-base",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Release",
"GSL_CXX_STANDARD": "23"
}
}
],
"buildPresets": [
{
"name": "msvc-14-debug",
"configurePreset": "msvc-14-debug"
},
{
"name": "msvc-14-release",
"configurePreset": "msvc-14-release"
},
{
"name": "msvc-17-debug",
"configurePreset": "msvc-17-debug"
},
{
"name": "msvc-17-release",
"configurePreset": "msvc-17-release"
},
{
"name": "msvc-20-debug",
"configurePreset": "msvc-20-debug"
},
{
"name": "msvc-20-release",
"configurePreset": "msvc-20-release"
},
{
"name": "msvc-23-debug",
"configurePreset": "msvc-23-debug"
},
{
"name": "msvc-23-release",
"configurePreset": "msvc-23-release"
},
{
"name": "gcc-14-debug",
"configurePreset": "gcc-14-debug"
},
{
"name": "gcc-14-release",
"configurePreset": "gcc-14-release"
},
{
"name": "gcc-17-debug",
"configurePreset": "gcc-17-debug"
},
{
"name": "gcc-17-release",
"configurePreset": "gcc-17-release"
},
{
"name": "gcc-20-debug",
"configurePreset": "gcc-20-debug"
},
{
"name": "gcc-20-release",
"configurePreset": "gcc-20-release"
},
{
"name": "gcc-23-debug",
"configurePreset": "gcc-23-debug"
},
{
"name": "gcc-23-release",
"configurePreset": "gcc-23-release"
},
{
"name": "clang-14-debug",
"configurePreset": "clang-14-debug"
},
{
"name": "clang-14-release",
"configurePreset": "clang-14-release"
},
{
"name": "clang-17-debug",
"configurePreset": "clang-17-debug"
},
{
"name": "clang-17-release",
"configurePreset": "clang-17-release"
},
{
"name": "clang-20-debug",
"configurePreset": "clang-20-debug"
},
{
"name": "clang-20-release",
"configurePreset": "clang-20-release"
},
{
"name": "clang-23-debug",
"configurePreset": "clang-23-debug"
},
{
"name": "clang-23-release",
"configurePreset": "clang-23-release"
}
],
"testPresets": [
{
"name": "msvc-14-debug",
"configurePreset": "msvc-14-debug"
},
{
"name": "msvc-14-release",
"configurePreset": "msvc-14-release"
},
{
"name": "msvc-17-debug",
"configurePreset": "msvc-17-debug"
},
{
"name": "msvc-17-release",
"configurePreset": "msvc-17-release"
},
{
"name": "msvc-20-debug",
"configurePreset": "msvc-20-debug"
},
{
"name": "msvc-20-release",
"configurePreset": "msvc-20-release"
},
{
"name": "msvc-23-debug",
"configurePreset": "msvc-23-debug"
},
{
"name": "msvc-23-release",
"configurePreset": "msvc-23-release"
},
{
"name": "gcc-14-debug",
"configurePreset": "gcc-14-debug"
},
{
"name": "gcc-14-release",
"configurePreset": "gcc-14-release"
},
{
"name": "gcc-17-debug",
"configurePreset": "gcc-17-debug"
},
{
"name": "gcc-17-release",
"configurePreset": "gcc-17-release"
},
{
"name": "gcc-20-debug",
"configurePreset": "gcc-20-debug"
},
{
"name": "gcc-20-release",
"configurePreset": "gcc-20-release"
},
{
"name": "gcc-23-debug",
"configurePreset": "gcc-23-debug"
},
{
"name": "gcc-23-release",
"configurePreset": "gcc-23-release"
},
{
"name": "clang-14-debug",
"configurePreset": "clang-14-debug"
},
{
"name": "clang-14-release",
"configurePreset": "clang-14-release"
},
{
"name": "clang-17-debug",
"configurePreset": "clang-17-debug"
},
{
"name": "clang-17-release",
"configurePreset": "clang-17-release"
},
{
"name": "clang-20-debug",
"configurePreset": "clang-20-debug"
},
{
"name": "clang-20-release",
"configurePreset": "clang-20-release"
},
{
"name": "clang-23-debug",
"configurePreset": "clang-23-debug"
},
{
"name": "clang-23-release",
"configurePreset": "clang-23-release"
}
]
}
-18
View File
@@ -1,18 +0,0 @@
{
"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"
}
]
}
+3 -3
View File
@@ -1,6 +1,6 @@
## Contributing to the Guideline Support Library
## Contributing to the Guidelines Support Library
The Guideline Support Library (GSL) contains functions and types that are suggested for use by the
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
@@ -17,7 +17,7 @@ Please submit a Contributor License Agreement (CLA) before submitting a pull req
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 **master** branch
* 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
+4 -70
View File
@@ -4,13 +4,7 @@
vim: syntax=xml
-->
<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010">
<!-- These types are from the gsl_assert header. -->
<Type Name="gsl::fail_fast">
<!-- na hides the address, otherwise it would appear as 0x.... "Message" -->
<DisplayString>{_Data._What,nasb}</DisplayString>
</Type>
<!-- These types are from the gsl_util header. -->
<!-- These types are from the util header. -->
<Type Name="gsl::final_action&lt;*&gt;">
<DisplayString>{{ invoke = {invoke_}, action = {f_} }}</DisplayString>
<Expand>
@@ -19,9 +13,8 @@
</Expand>
</Type>
<!-- These types are from the span header. -->
<!-- This is for dynamic_extent spans. -->
<Type Name="gsl::span&lt;*, -1&gt;">
<!-- These types are from the span header. -->
<Type Name="gsl::span&lt;*, *&gt;">
<DisplayString>{{ extent = {storage_.size_} }}</DisplayString>
<Expand>
<ArrayItems>
@@ -31,66 +24,7 @@
</Expand>
</Type>
<!-- This works for constexpr size spans. -->
<Type Name="gsl::span&lt;*, *&gt;">
<DisplayString>{{ extent = {extent} }}</DisplayString>
<Expand>
<ArrayItems>
<Size>extent</Size>
<ValuePointer>storage_.data_</ValuePointer>
</ArrayItems>
</Expand>
</Type>
<!-- This is for dynamic_extent string_spans. -->
<Type Name="gsl::basic_string_span&lt;*, -1&gt;">
<DisplayString>{span_.storage_.data_,[span_.storage_.size_]na}</DisplayString>
<Expand>
<Item Name="[size]">span_.storage_.size_</Item>
<ArrayItems>
<Size>span_.storage_.size_</Size>
<ValuePointer>span_.storage_.data_</ValuePointer>
</ArrayItems>
</Expand>
</Type>
<!-- This works for constexpr size string_spans. -->
<Type Name="gsl::basic_string_span&lt;*, *&gt;">
<DisplayString>{span_.storage_.data_,[span_.extent]na}</DisplayString>
<Expand>
<Item Name="[size]">span_.extent</Item>
<ArrayItems>
<Size>span_.extent</Size>
<ValuePointer>span_.storage_.data_</ValuePointer>
</ArrayItems>
</Expand>
</Type>
<!-- This is for dynamic_extent zstring_spans. -->
<Type Name="gsl::basic_zstring_span&lt;*, -1&gt;">
<DisplayString>{span_.storage_.data_,[span_.storage_.size_]na}</DisplayString>
<Expand>
<Item Name="[size]">span_.storage_.size_</Item>
<ArrayItems>
<Size>span_.storage_.size_</Size>
<ValuePointer>span_.storage_.data_</ValuePointer>
</ArrayItems>
</Expand>
</Type>
<!-- This works for constexpr size string_spans. -->
<Type Name="gsl::basic_zstring_span&lt;*, *&gt;">
<DisplayString>{span_.storage_.data_,[span_.extent]na}</DisplayString>
<Expand>
<Item Name="[size]">span_.extent</Item>
<ArrayItems>
<Size>span_.extent</Size>
<ValuePointer>span_.storage_.data_</ValuePointer>
</ArrayItems>
</Expand>
</Type>
<!-- These types are from the gsl header. -->
<!-- These types are from the pointers header. -->
<Type Name="gsl::not_null&lt;*&gt;">
<!-- We can always dereference this since it's an invariant. -->
<DisplayString>value = {*ptr_}</DisplayString>
+153 -27
View File
@@ -1,12 +1,12 @@
# GSL: Guideline Support Library [![Build Status](https://travis-ci.org/Microsoft/GSL.svg?branch=master)](https://travis-ci.org/Microsoft/GSL) [![Build status](https://ci.appveyor.com/api/projects/status/github/Microsoft/GSL?svg=true)](https://ci.appveyor.com/project/neilmacintosh/GSL)
# 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 Guideline Support Library (GSL) contains functions and types that are suggested for use by the
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 library includes types like `span<T>`, `string_span`, `owner<>` and others.
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. There are specific workarounds to support MSVC 2015.
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.
@@ -18,39 +18,112 @@ other platforms. Please see [CONTRIBUTING.md](./CONTRIBUTING.md) for more inform
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 [Catch](https://github.com/philsquared/catch) testing library. Please see the [ThirdPartyNotices.txt](./ThirdPartyNotices.txt) file for details regarding the licensing of Catch.
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) | &#x2611; | An alias for a raw pointer
[not_null](docs/headers.md#user-content-H-pointers-not_null) | &#x2611; | Restricts a pointer/smart pointer to hold non-null values
[span](docs/headers.md#user-content-H-span-span) | &#x2611; | A view over a contiguous sequence of memory. Based on the standardized version of `std::span`, however `gsl::span` enforces bounds checking.
span_p | &#x2610; | 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) | &#x2611; | A pointer to a C-string (zero-terminated array) with a templated char type
[zstring](docs/headers.md#user-content-H-zstring) | &#x2611; | An alias to `basic_zstring` with dynamic extent and a char type of `char`
[czstring](docs/headers.md#user-content-H-zstring) | &#x2611; | An alias to `basic_zstring` with dynamic extent and a char type of `const char`
[wzstring](docs/headers.md#user-content-H-zstring) | &#x2611; | An alias to `basic_zstring` with dynamic extent and a char type of `wchar_t`
[cwzstring](docs/headers.md#user-content-H-zstring) | &#x2611; | An alias to `basic_zstring` with dynamic extent and a char type of `const wchar_t`
[u16zstring](docs/headers.md#user-content-H-zstring) | &#x2611; | An alias to `basic_zstring` with dynamic extent and a char type of `char16_t`
[cu16zstring](docs/headers.md#user-content-H-zstring) | &#x2611; | An alias to `basic_zstring` with dynamic extent and a char type of `const char16_t`
[u32zstring](docs/headers.md#user-content-H-zstring) | &#x2611; | An alias to `basic_zstring` with dynamic extent and a char type of `char32_t`
[cu32zstring](docs/headers.md#user-content-H-zstring) | &#x2611; | An alias to `basic_zstring` with dynamic extent and a char type of `const char32_t`
[**2. Owners**][cg-owners] | |
stack_array | &#x2610; | A stack-allocated array
dyn_array | &#x2611; | A heap-allocated array
[**3. Assertions**][cg-assertions] | |
[Expects](docs/headers.md#user-content-H-assert-expects) | &#x2611; | A precondition assertion; on failure it terminates
[Ensures](docs/headers.md#user-content-H-assert-ensures) | &#x2611; | A postcondition assertion; on failure it terminates
[**4. Utilities**][cg-utilities] | |
move_owner | &#x2610; | A helper function that moves one `owner` to the other
[final_action](docs/headers.md#user-content-H-util-final_action) | &#x2611; | A RAII style class that invokes a functor on its destruction
[finally](docs/headers.md#user-content-H-util-finally) | &#x2611; | 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) | &#x2611; | A macro that takes an argument and turns it into `[[gsl::suppress(x)]]` or `[[gsl::suppress("x")]]` depending on the compiler.
[[implicit]] | &#x2610; | A "marker" to put on single-argument constructors to explicitly make them non-explicit
[index](docs/headers.md#user-content-H-util-index) | &#x2611; | 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) | &#x2611; | 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) | &#x2611; | A narrowing cast for values and a synonym for `static_cast`
[narrowing_error](docs/headers.md#user-content-H-narrow-narrowing_error) | &#x2611; | A custom exception type thrown by [narrow](docs/headers.md#user-content-H-narrow-narrow)
[**5. Concepts**][cg-concepts] | &#x2610; |
## 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) | &#x2611; | A stricter version of [not_null](docs/headers.md#user-content-H-pointers-not_null) with explicit constructors
multi_span | &#x2610; | Deprecated. Multi-dimensional span.
strided_span | &#x2610; | Deprecated. Support for this type has been discontinued.
basic_string_span | &#x2610; | Deprecated. Like `span` but for strings with a templated char type
string_span | &#x2610; | Deprecated. An alias to `basic_string_span` with a char type of `char`
cstring_span | &#x2610; | Deprecated. An alias to `basic_string_span` with a char type of `const char`
wstring_span | &#x2610; | Deprecated. An alias to `basic_string_span` with a char type of `wchar_t`
cwstring_span | &#x2610; | Deprecated. An alias to `basic_string_span` with a char type of `const wchar_t`
u16string_span | &#x2610; | Deprecated. An alias to `basic_string_span` with a char type of `char16_t`
cu16string_span | &#x2610; | Deprecated. An alias to `basic_string_span` with a char type of `const char16_t`
u32string_span | &#x2610; | Deprecated. An alias to `basic_string_span` with a char type of `char32_t`
cu32string_span | &#x2610; | 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 Platforms
The test suite that exercises GSL has been built and passes successfully on the following platforms:<sup>1)</sup>
## 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).)
* Windows using Visual Studio 2015
* Windows using Visual Studio 2017
* Windows using Clang/LLVM 3.6
* Windows using GCC 5.1
* Windows using Intel C++ Compiler 18.0
* GNU/Linux using Clang/LLVM 3.6
* GNU/Linux using GCC 5.1
* OS X Yosemite using Xcode with Apple Clang 7.0.0.7000072
* OS X Yosemite using GCC-5.2.0
* OS X Sierra 10.12.4 using Apple LLVM version 8.1.0 (Clang-802.0.42)
* OS X El Capitan (10.11) using Xcode with AppleClang 8.0.0.8000042
* OS X High Sierra 10.13.2 (17C88) using Apple LLVM version 9.0.0 (clang-900.0.39.2)
* FreeBSD 10.x with Clang/LLVM 3.6
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. Please submit an issue to let us know. Also please consider
contributing any changes that were necessary back to this project to benefit the wider community.
---
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!
<sup>1)</sup> For `gsl::byte` to work correctly with Clang and GCC you might have to use the ` -fno-strict-aliasing` compiler option.
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.1.3 or later to be installed and in your PATH.
* [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).
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
@@ -58,7 +131,7 @@ These steps assume the source code of this repository has been cloned into a dir
2. Configure CMake to use the compiler of your choice (you can see a list by running `cmake --help`).
cmake -G "Visual Studio 14 2015" c:\GSL
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).
@@ -70,6 +143,18 @@ These steps assume the source code of this repository has been cloned into a dir
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.
@@ -90,5 +175,46 @@ Include the library using:
#include <gsl/gsl>
## Usage in CMake
The library provides a Config file for CMake, once installed it can be found via `find_package`.
Which, when successful, will add library target called `Microsoft.GSL::GSL` which you can use via the usual
`target_link_libraries` mechanism.
```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.0"
GIT_SHALLOW ON
)
FetchContent_MakeAvailable(GSL)
target_link_libraries(foobar PRIVATE Microsoft.GSL::GSL)
```
## Debugging visualization support
For Visual Studio users, the file [GSL.natvis](./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 <https://aka.ms/gsl>.
+41
View File
@@ -0,0 +1,41 @@
<!-- BEGIN MICROSOFT SECURITY.MD V0.0.7 BLOCK -->
## 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).
<!-- END MICROSOFT SECURITY.MD BLOCK -->
+33 -31
View File
@@ -2,38 +2,40 @@
THIRD-PARTY SOFTWARE NOTICES AND INFORMATION
Do Not Translate or Localize
GSL: Guideline Support Library incorporates third party material from the projects listed below. The original copyright notice and the license under which Microsoft received such third party material are set forth below. Microsoft reserves all other rights not expressly granted, whether by implication, estoppel or otherwise.
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.
1. Catch (https://github.com/philsquared/Catch)
%% Catch NOTICES, INFORMATION, AND LICENSE BEGIN HERE
=========================================
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
=========================================
END OF Catch NOTICES, INFORMATION, AND LICENSE
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.
-------------------------------------------------------------------------------
-58
View File
@@ -1,58 +0,0 @@
shallow_clone: true
platform:
- x86
- x64
configuration:
- Debug
- Release
image:
- Visual Studio 2015
- Visual Studio 2017
environment:
matrix:
- GSL_CXX_STANDARD: 14
- GSL_CXX_STANDARD: 17
matrix:
exclude:
- image: Visual Studio 2015
GSL_CXX_STANDARD: 17
cache:
- C:\cmake-3.8.0-win32-x86
install:
- ps: |
if (![IO.File]::Exists("C:\cmake-3.8.0-win32-x86\bin\cmake.exe")) {
Start-FileDownload 'https://cmake.org/files/v3.8/cmake-3.8.0-win32-x86.zip'
7z x -y cmake-3.8.0-win32-x86.zip -oC:\
}
$env:PATH="C:\cmake-3.8.0-win32-x86\bin;$env:PATH"
before_build:
- ps: |
mkdir build
cd build
if ("$env:APPVEYOR_JOB_NAME" -match "Image: Visual Studio 2015") {
$env:generator="Visual Studio 14 2015"
} else {
$env:generator="Visual Studio 15 2017"
}
if ($env:PLATFORM -eq "x64") {
$env:generator="$env:generator Win64"
}
echo generator="$env:generator"
cmake .. -G "$env:generator" -DGSL_CXX_STANDARD="$env:GSL_CXX_STANDARD"
build_script:
- cmake --build . --config %CONFIGURATION% -- /m /v:minimal
test_script:
- ctest -j2
deploy: off
+1070
View File
File diff suppressed because it is too large Load Diff
+19
View File
@@ -0,0 +1,19 @@
> When bumping the version, you need to update the following files:
1. [ ] [CMakeLists.txt](../CMakeLists.txt) Bump `GSL_VERSION`
1. [ ] [README.md](../README.md) Bump `GIT_TAG`
1. [ ] [ios.yml](../.github/workflows/ios.yml) Bump `MACOSX_BUNDLE_BUNDLE_VERSION` and
`MACOSX_BUNDLE_SHORT_VERSION_STRING`
> After updating, you need to create a new GitHub release:
1. [ ] [Microsoft/GSL - Create Release](https://github.com/microsoft/GSL/releases/new)
Be sure to update the release notes accordingly and properly mention open-source
contributors.
> After a new release exists, update the `ms-gsl` vcpkg port:
1. [ ] [Microsoft/vcpkg - ms-gsl port](https://github.com/microsoft/vcpkg/tree/master/ports/ms-gsl)
Be sure to monitor the PR that updates the port for any feedback from vcpkg maintainers.
+13
View File
@@ -0,0 +1,13 @@
# 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 <gsl/gsl>
if(PROJECT_IS_TOP_LEVEL)
target_include_directories(GSL INTERFACE $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>)
else()
target_include_directories(GSL SYSTEM INTERFACE $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>)
endif()
@@ -17,8 +17,8 @@
#ifndef GSL_ALGORITHM_H
#define GSL_ALGORITHM_H
#include <gsl/gsl_assert> // for Expects
#include <gsl/span> // for dynamic_extent, span
#include "./assert" // for Expects
#include "./span" // for dynamic_extent, span
#include <algorithm> // for copy_n
#include <cstddef> // for ptrdiff_t
@@ -37,8 +37,8 @@ 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 <class SrcElementType, std::ptrdiff_t SrcExtent, class DestElementType,
std::ptrdiff_t DestExtent>
template <class SrcElementType, std::size_t SrcExtent, class DestElementType,
std::size_t DestExtent>
void copy(span<SrcElementType, SrcExtent> src, span<DestElementType, DestExtent> dest)
{
static_assert(std::is_assignable<decltype(*dest.data()), decltype(*src.data())>::value,
@@ -48,7 +48,7 @@ void copy(span<SrcElementType, SrcExtent> src, span<DestElementType, DestExtent>
"Source range is longer than target range");
Expects(dest.size() >= src.size());
GSL_SUPPRESS(stl.1) // NO-FORMAT: attribute
GSL_SUPPRESS(stl.1)
std::copy_n(src.data(), src.size(), dest.data());
}
+43 -78
View File
@@ -14,59 +14,57 @@
//
///////////////////////////////////////////////////////////////////////////////
#ifndef GSL_CONTRACTS_H
#define GSL_CONTRACTS_H
#include <exception>
#include <stdexcept> // for logic_error
//
// make suppress attributes parse for some compilers
// Hopefully temporary until suppresion standardization occurs
//
#if defined (_MSC_VER)
#define GSL_SUPPRESS(x) [[gsl::suppress(x)]]
#else
#if defined(__clang__)
#define GSL_SUPPRESS(x) [[gsl::suppress("x")]]
#else
#define GSL_SUPPRESS(x)
#endif // __clang__
#endif // _MSC_VER
#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(_HAS_EXCEPTIONS) && !_HAS_EXCEPTIONS
#if defined(_MSC_VER) && (defined(_KERNEL_MODE) || (defined(_HAS_EXCEPTIONS) && !_HAS_EXCEPTIONS))
#define GSL_KERNEL_MODE
#define GSL_MSVC_USE_STL_NOEXCEPTION_WORKAROUND
#include <intrin.h>
#define RANGE_CHECKS_FAILURE 0
#endif
#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 <exception>
#endif // defined(_MSC_VER) && (defined(_KERNEL_MODE) || (defined(_HAS_EXCEPTIONS) &&
// !_HAS_EXCEPTIONS))
//
// There are three configuration options for this GSL implementation's behavior
// when pre/post conditions on the GSL types are violated:
// make suppress attributes parse for some compilers
// Hopefully temporary until suppression standardization occurs
//
// 1. GSL_TERMINATE_ON_CONTRACT_VIOLATION: std::terminate will be called (default)
// 2. GSL_THROW_ON_CONTRACT_VIOLATION: a gsl::fail_fast exception will be thrown
// 3. GSL_UNENFORCED_ON_CONTRACT_VIOLATION: nothing happens
//
#if !(defined(GSL_THROW_ON_CONTRACT_VIOLATION) || defined(GSL_TERMINATE_ON_CONTRACT_VIOLATION) || \
defined(GSL_UNENFORCED_ON_CONTRACT_VIOLATION))
#define GSL_TERMINATE_ON_CONTRACT_VIOLATION
#endif
#define GSL_STRINGIFY_DETAIL(x) #x
#define GSL_STRINGIFY(x) GSL_STRINGIFY_DETAIL(x)
#if defined(__clang__)
#define GSL_SUPPRESS(x) [[gsl::suppress(#x)]]
#elif defined(_MSC_VER) && _MSC_VER >= 1950
// Visual Studio versions after 2022 (_MSC_VER > 1944) support the justification message.
#define GSL_SUPPRESS(x) [[gsl::suppress(#x)]]
#elif defined(_MSC_VER) && !defined(__INTEL_COMPILER) && !defined(__NVCC__)
#define GSL_SUPPRESS(x) [[gsl::suppress(x)]]
#else
#define GSL_SUPPRESS(x)
#endif // defined(__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
#endif // defined(__clang__) || defined(__GNUC__)
//
// GSL_ASSUME(cond)
@@ -88,18 +86,14 @@
namespace gsl
{
struct fail_fast : public std::logic_error
{
explicit fail_fast(char const* const message) : std::logic_error(message) {}
};
namespace details
{
#if defined(GSL_MSVC_USE_STL_NOEXCEPTION_WORKAROUND)
typedef void (__cdecl *terminate_handler)();
GSL_SUPPRESS(f.6) // NO-FORMAT: attribute
typedef void(__cdecl* terminate_handler)();
GSL_SUPPRESS(f.6)
[[noreturn]] inline void __cdecl default_terminate_handler()
{
__fastfail(RANGE_CHECKS_FAILURE);
@@ -111,7 +105,7 @@ namespace details
return handler;
}
#endif
#endif // defined(GSL_MSVC_USE_STL_NOEXCEPTION_WORKAROUND)
[[noreturn]] inline void terminate() noexcept
{
@@ -119,49 +113,20 @@ namespace details
(*gsl::details::get_terminate_handler())();
#else
std::terminate();
#endif
#endif // defined(GSL_MSVC_USE_STL_NOEXCEPTION_WORKAROUND)
}
#if defined(GSL_TERMINATE_ON_CONTRACT_VIOLATION)
template <typename Exception>
[[noreturn]] void throw_exception(Exception&&) noexcept
{
gsl::details::terminate();
}
#else
template <typename Exception>
[[noreturn]] void throw_exception(Exception&& exception)
{
throw std::forward<Exception>(exception);
}
#endif
} // namespace details
} // namespace gsl
#if defined(GSL_THROW_ON_CONTRACT_VIOLATION)
#define GSL_CONTRACT_CHECK(type, cond) \
(GSL_LIKELY(cond) ? static_cast<void>(0) \
: gsl::details::throw_exception(gsl::fail_fast( \
"GSL: " type " failure at " __FILE__ ": " GSL_STRINGIFY(__LINE__))))
#elif defined(GSL_TERMINATE_ON_CONTRACT_VIOLATION)
#define GSL_CONTRACT_CHECK(type, cond) \
(GSL_LIKELY(cond) ? static_cast<void>(0) : gsl::details::terminate())
#elif defined(GSL_UNENFORCED_ON_CONTRACT_VIOLATION)
#define GSL_CONTRACT_CHECK(type, cond) GSL_ASSUME(cond)
#endif
#define Expects(cond) GSL_CONTRACT_CHECK("Precondition", cond)
#define Ensures(cond) GSL_CONTRACT_CHECK("Postcondition", cond)
#endif // GSL_CONTRACTS_H
#if defined(GSL_MSVC_USE_STL_NOEXCEPTION_WORKAROUND) && defined(__clang__)
#pragma clang diagnostic pop
#endif
#endif // GSL_ASSERT_H
+49 -51
View File
@@ -17,19 +17,7 @@
#ifndef GSL_BYTE_H
#define GSL_BYTE_H
//
// make suppress attributes work for some compilers
// Hopefully temporary until suppresion standardization occurs
//
#if defined(_MSC_VER)
#define GSL_SUPPRESS(x) [[gsl::suppress(x)]]
#else
#if defined(__clang__)
#define GSL_SUPPRESS(x) [[gsl::suppress("x")]]
#else
#define GSL_SUPPRESS(x)
#endif // __clang__
#endif // _MSC_VER
#include "./util" // for GSL_DEPRECATED
#include <type_traits>
@@ -38,32 +26,33 @@
#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
#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(_HAS_STD_BYTE) && _HAS_STD_BYTE
#if defined(__cpp_lib_byte) && __cpp_lib_byte >= 201603
#define GSL_USE_STD_BYTE 1
#else // defined(_HAS_STD_BYTE) && _HAS_STD_BYTE
#else // defined(__cpp_lib_byte) && __cpp_lib_byte >= 201603
#define GSL_USE_STD_BYTE 0
#endif // defined(_HAS_STD_BYTE) && _HAS_STD_BYTE
#endif // defined(__cpp_lib_byte) && __cpp_lib_byte >= 201603
#endif // GSL_USE_STD_BYTE
#else // _MSC_VER
#ifndef GSL_USE_STD_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 libstc++ actually contains std::byte
#if defined(__cplusplus) && (__cplusplus >= 201703L) && \
(defined(__cpp_lib_byte) && (__cpp_lib_byte >= 201603) || \
defined(_LIBCPP_VERSION) && (_LIBCPP_VERSION >= 5000))
#include <cstddef> /* __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
#include <cstddef>
#else // defined(__cplusplus) && (__cplusplus >= 201703L) &&
// (defined(__cpp_lib_byte) && (__cpp_lib_byte >= 201603) ||
@@ -71,7 +60,7 @@
#define GSL_USE_STD_BYTE 0
#endif //defined(__cplusplus) && (__cplusplus >= 201703L) &&
#endif // defined(__cplusplus) && (__cplusplus >= 201703L) &&
// (defined(__cpp_lib_byte) && (__cpp_lib_byte >= 201603) ||
// defined(_LIBCPP_VERSION) && (_LIBCPP_VERSION >= 5000))
#endif // GSL_USE_STD_BYTE
@@ -79,17 +68,30 @@
#endif // _MSC_VER
// Use __may_alias__ attribute on gcc and clang
#if defined __clang__ || (__GNUC__ > 5)
#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 <cstddef>
#endif
namespace gsl
{
#if GSL_USE_STD_BYTE
using 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;
} // namespace impl
using byte GSL_DEPRECATED("Use std::byte instead.") = std::byte;
using std::to_integer;
#else // GSL_USE_STD_BYTE
@@ -100,25 +102,33 @@ enum class byte_may_alias byte : unsigned char
{
};
template <class IntegerType, class = std::enable_if_t<std::is_integral<IntegerType>::value>>
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;
} // namespace impl
template <class IntegerType, std::enable_if_t<std::is_integral<IntegerType>::value, bool> = true>
constexpr byte& operator<<=(byte& b, IntegerType shift) noexcept
{
return b = byte(static_cast<unsigned char>(b) << shift);
}
template <class IntegerType, class = std::enable_if_t<std::is_integral<IntegerType>::value>>
template <class IntegerType, std::enable_if_t<std::is_integral<IntegerType>::value, bool> = true>
constexpr byte operator<<(byte b, IntegerType shift) noexcept
{
return byte(static_cast<unsigned char>(b) << shift);
}
template <class IntegerType, class = std::enable_if_t<std::is_integral<IntegerType>::value>>
template <class IntegerType, std::enable_if_t<std::is_integral<IntegerType>::value, bool> = true>
constexpr byte& operator>>=(byte& b, IntegerType shift) noexcept
{
return b = byte(static_cast<unsigned char>(b) >> shift);
}
template <class IntegerType, class = std::enable_if_t<std::is_integral<IntegerType>::value>>
template <class IntegerType, std::enable_if_t<std::is_integral<IntegerType>::value, bool> = true>
constexpr byte operator>>(byte b, IntegerType shift) noexcept
{
return byte(static_cast<unsigned char>(b) >> shift);
@@ -156,7 +166,7 @@ constexpr byte operator^(byte l, byte r) noexcept
constexpr byte operator~(byte b) noexcept { return byte(~static_cast<unsigned char>(b)); }
template <class IntegerType, class = std::enable_if_t<std::is_integral<IntegerType>::value>>
template <class IntegerType, std::enable_if_t<std::is_integral<IntegerType>::value, bool> = true>
constexpr IntegerType to_integer(byte b) noexcept
{
return static_cast<IntegerType>(b);
@@ -164,34 +174,22 @@ constexpr IntegerType to_integer(byte b) noexcept
#endif // GSL_USE_STD_BYTE
template <bool E, typename T>
constexpr byte to_byte_impl(T t) noexcept
template <typename T>
constexpr gsl::impl::byte to_byte(T t) noexcept
{
static_assert(
E, "gsl::to_byte(t) must be provided an unsigned char, otherwise data loss may occur. "
"If you are calling to_byte with an integer contant use: gsl::to_byte<t>() version.");
return static_cast<byte>(t);
}
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 byte to_byte_impl<true, unsigned char>(unsigned char t) noexcept
{
return byte(t);
}
template <typename T>
constexpr byte to_byte(T t) noexcept
{
return to_byte_impl<std::is_same<T, unsigned char>::value, T>(t);
std::is_same<T, unsigned char>::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<t>() version.");
return gsl::impl::byte(t);
}
template <int I>
constexpr byte to_byte() noexcept
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<byte>(I);
return static_cast<gsl::impl::byte>(I);
}
} // namespace gsl
+439
View File
@@ -0,0 +1,439 @@
// -*- C++ -*-
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2026 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_DYN_ARRAY_H
#define GSL_DYN_ARRAY_H
#include "./assert"
#include "./narrow"
#include "./util"
#include <algorithm>
#include <iterator>
#include <memory>
#include <type_traits>
#if defined(__cpp_lib_ranges) && (__cpp_lib_ranges >= 201911L)
#include <ranges>
#endif /* __cpp_lib_ranges >= 201911L */
namespace gsl
{
namespace details
{
template <typename T, typename Allocator = std::allocator<T>>
class dyn_array_base : public Allocator
{
using pointer = T*;
using size_type = std::size_t;
template <typename... Args>
GSL_CONSTEXPR_SINCE_CPP20 void construct(pointer ptr, Args&&... args)
{
std::allocator_traits<Allocator>::construct(static_cast<Allocator&>(*this), ptr,
std::forward<Args>(args)...);
}
GSL_CONSTEXPR_SINCE_CPP20 void destroy(pointer ptr)
{
std::allocator_traits<Allocator>::destroy(static_cast<Allocator&>(*this), ptr);
}
GSL_CONSTEXPR_SINCE_CPP20 void destroy_range(pointer first, pointer last)
{
for (; first != last; ++first) { destroy(first); }
}
GSL_CONSTEXPR_SINCE_CPP20 void rollback_construction(pointer first, pointer last)
{
destroy_range(first, last);
std::allocator_traits<Allocator>::deallocate(static_cast<Allocator&>(*this), _data,
_count);
_data = nullptr;
_count = 0;
}
protected:
constexpr auto data() const { return _data; }
constexpr auto count() const { return _count; }
GSL_CONSTEXPR_SINCE_CPP20 void resize(size_type count)
{
// This should only be called when constructing a non-forward iterator.
// It neither frees nor copies `_data`.
Expects(_data == nullptr && _count == 0);
if (count != 0)
{
_data = std::allocator_traits<Allocator>::allocate(static_cast<Allocator&>(*this),
count);
_count = count;
}
}
GSL_CONSTEXPR_SINCE_CPP20 void fill(pointer first, size_type count, const T& value)
{
pointer current = first;
try
{
for (size_type i = 0; i < count; ++i, ++current) { construct(current, value); }
} catch (...)
{
rollback_construction(first, current);
throw;
}
}
template <typename InputIt>
GSL_CONSTEXPR_SINCE_CPP20 void copy(InputIt first, InputIt last, pointer output)
{
pointer current = output;
try
{
for (; first != last; ++first, ++current) { construct(current, *first); }
} catch (...)
{
rollback_construction(output, current);
throw;
}
}
GSL_CONSTEXPR_SINCE_CPP20 void default_construct(pointer first, size_type count)
{
pointer current = first;
try
{
for (size_type i = 0; i < count; ++i, ++current) { construct(current); }
} catch (...)
{
rollback_construction(first, current);
throw;
}
}
private:
pointer _data;
size_type _count;
public:
constexpr dyn_array_base(const Allocator& alloc)
: Allocator{alloc}, _data{nullptr}, _count{0}
{
Ensures((_count == 0 && _data == nullptr) || (_count > 0 && _data != nullptr));
}
constexpr dyn_array_base(size_type count, const Allocator& alloc)
: Allocator{alloc}
, _data{count == 0 ? nullptr
: std::allocator_traits<Allocator>::allocate(
static_cast<Allocator&>(*this), count)}
, _count{count}
{
Ensures((_count == 0 && _data == nullptr) || (_count > 0 && _data != nullptr));
}
GSL_CONSTEXPR_SINCE_CPP20 ~dyn_array_base()
{
if (_data)
{
if (!std::is_trivially_destructible<T>::value)
{
destroy_range(_data, _data + _count);
}
std::allocator_traits<Allocator>::deallocate(static_cast<Allocator&>(*this), _data,
_count);
}
}
};
template <typename T>
class dyn_array_iterator
{
using size_type = std::size_t;
public:
using difference_type = std::ptrdiff_t;
using value_type = T;
using pointer = T*;
using reference = T&;
using const_reference = const T&;
using iterator_category = std::random_access_iterator_tag;
#if defined(__cpp_lib_ranges) && (__cpp_lib_ranges >= 201911L)
constexpr dyn_array_iterator() = default;
#endif /* __cpp_lib_ranges >= 201911L */
constexpr dyn_array_iterator(pointer ptr, size_type pos, size_type end_pos)
: _ptr{ptr}, _pos{pos}, _end_pos{end_pos}
{
Ensures((_ptr != nullptr && _end_pos > 0) || (_ptr == nullptr && _end_pos == 0));
Ensures(_pos <= _end_pos);
}
#if defined(_MSC_VER) && defined(__cpp_lib_ranges) && (__cpp_lib_ranges >= 201911L)
constexpr operator pointer() const { return _ptr + gsl::narrow<size_type>(_pos); }
#endif /* defined(_MSC_VER) && __cpp_lib_ranges >= 201911L */
constexpr auto operator==(const dyn_array_iterator& other) const
{
Expects(_ptr == other._ptr);
Expects(_end_pos == other._end_pos);
return _pos == other._pos;
}
constexpr auto operator!=(const dyn_array_iterator& other) const
{
return !(*this == other);
}
constexpr auto operator*() const -> reference
{
Expects(_ptr != nullptr);
Expects(_pos < _end_pos);
return _ptr[_pos];
}
constexpr auto operator++() -> dyn_array_iterator&
{
Expects(_pos < _end_pos);
++_pos;
return *this;
}
constexpr auto operator++(int)
{
auto rv = *this;
++(*this);
return rv;
}
constexpr auto operator--() -> dyn_array_iterator&
{
Expects(_pos > 0);
--_pos;
return *this;
}
constexpr auto operator--(int)
{
auto rv = *this;
--(*this);
return rv;
}
constexpr auto operator+=(difference_type diff) -> dyn_array_iterator&
{
auto new_pos = gsl::narrow<difference_type>(_pos) + diff;
Expects(new_pos >= 0);
Expects(new_pos <= gsl::narrow<difference_type>(_end_pos));
_pos = gsl::narrow<size_type>(new_pos);
return *this;
}
constexpr auto operator-=(difference_type diff) -> dyn_array_iterator&
{
auto new_pos = gsl::narrow<difference_type>(_pos) - diff;
Expects(new_pos >= 0);
Expects(new_pos <= gsl::narrow<difference_type>(_end_pos));
_pos = gsl::narrow<size_type>(new_pos);
return *this;
}
constexpr auto operator+(difference_type diff) const
{
auto new_pos = gsl::narrow<difference_type>(_pos) + diff;
return dyn_array_iterator{_ptr, gsl::narrow<size_type>(new_pos), _end_pos};
}
constexpr auto operator-(difference_type diff) const { return *this + (-diff); }
constexpr auto operator-(const dyn_array_iterator& other) const
{
Expects(_ptr == other._ptr);
Expects(_end_pos == other._end_pos);
return gsl::narrow<difference_type>(_pos) - gsl::narrow<difference_type>(other._pos);
}
constexpr auto operator[](size_type pos) -> reference
{
Expects(_pos + pos < _end_pos);
return _ptr[_pos + pos];
}
constexpr auto operator[](size_type pos) const -> const_reference
{
return const_cast<dyn_array_iterator&>(*this).operator[](pos);
}
private:
pointer _ptr{};
size_type _pos{};
size_type _end_pos{};
};
} // namespace details
template <typename T, typename Allocator = std::allocator<T>>
class dyn_array : private details::dyn_array_base<T, Allocator>
{
using base = details::dyn_array_base<T, Allocator>;
using pointer = T*;
public:
using value_type = T;
using reference = T&;
using const_reference = const T&;
using iterator = details::dyn_array_iterator<T>;
using const_iterator = details::dyn_array_iterator<const T>;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
using difference_type = std::ptrdiff_t;
using size_type = std::size_t;
using allocator_type = Allocator;
explicit constexpr dyn_array(const Allocator& alloc = {}) : base{alloc} {}
constexpr dyn_array(size_type count, const T& value, const Allocator& alloc = {})
: base{count, alloc}
{
base::fill(data(), size(), value);
}
template <typename InputIt,
std::enable_if_t<details::is_fwd_iterator<InputIt>::value, bool> = true>
constexpr dyn_array(InputIt first, InputIt last, const Allocator& alloc = {})
: base{gsl::narrow<size_type>(std::distance(first, last)), alloc}
{
base::copy(first, last, data());
}
template <typename InputIt, std::enable_if_t<!details::is_fwd_iterator<InputIt>::value &&
details::is_iterator<InputIt>::value,
bool> = true>
constexpr dyn_array(InputIt first, InputIt last, const Allocator& alloc = {}) : dyn_array{alloc}
{
std::vector<T> tmp(first, last);
base::resize(tmp.size());
base::copy(std::begin(tmp), std::end(tmp), data());
}
#if defined(__cpp_lib_containers_ranges) && (__cpp_lib_containers_ranges >= 202202L)
template <typename InputRg>
requires(std::ranges::input_range<InputRg>)
constexpr dyn_array(std::from_range_t, InputRg&& rg, const Allocator& alloc = {})
: base{gsl::narrow<size_type>(std::size(rg)), alloc}
{
base::copy(std::ranges::begin(rg), std::ranges::end(rg), data());
}
#endif /* __cpp_lib_containers_ranges >= 202202L */
constexpr explicit dyn_array(size_type count, const Allocator& alloc = {}) : base{count, alloc}
{
base::default_construct(data(), size());
}
constexpr dyn_array(const dyn_array& other, const Allocator& alloc = {})
: dyn_array(other.begin(), other.end(), alloc)
{}
constexpr dyn_array(std::initializer_list<T> init, const Allocator& alloc = {})
: dyn_array(init.begin(), init.end(), alloc)
{}
constexpr dyn_array(dyn_array&&) = delete;
dyn_array& operator=(dyn_array&&) = delete;
constexpr auto operator==(const dyn_array& other) const
{
return size() == other.size() && std::equal(begin(), end(), other.begin(), other.end());
}
constexpr auto operator!=(const dyn_array& other) const { return !(*this == other); }
constexpr auto size() const { return base::count(); }
constexpr auto empty() const { return size() == 0; }
constexpr auto max_size() const { return static_cast<size_type>(-1); }
constexpr auto get_allocator() -> Allocator& { return *this; }
constexpr auto operator[](size_type pos) -> reference
{
Expects(pos < size());
return data()[pos];
}
constexpr auto operator[](size_type pos) const -> const_reference
{
return const_cast<dyn_array&>(*this)[pos];
}
constexpr auto data() { return base::data(); }
constexpr auto data() const -> const T* { return const_cast<dyn_array&>(*this).data(); }
constexpr auto begin() { return iterator{data(), 0, size()}; }
constexpr auto begin() const { return const_iterator{data(), 0, size()}; }
constexpr auto cbegin() const { return begin(); }
constexpr auto rbegin() { return reverse_iterator{end()}; }
constexpr auto rbegin() const { return const_reverse_iterator{end()}; }
constexpr auto crbegin() const { return rbegin(); }
#ifdef _MSC_VER
constexpr auto _Unchecked_begin() { return data(); }
constexpr auto _Unchecked_begin() const -> const T*
{
return const_cast<dyn_array&>(*this)._Unchecked_begin();
}
#endif /* _MSC_VER */
constexpr auto end() { return iterator{data(), size(), size()}; }
constexpr auto end() const { return const_iterator{data(), size(), size()}; }
constexpr auto cend() const { return end(); }
constexpr auto rend() { return reverse_iterator{begin()}; }
constexpr auto rend() const { return const_reverse_iterator{begin()}; }
constexpr auto crend() const { return rend(); }
#ifdef _MSC_VER
constexpr auto _Unchecked_end() { return data() + size(); }
constexpr auto _Unchecked_end() const -> const T*
{
return const_cast<dyn_array&>(*this)._Unchecked_end();
}
#endif /* _MSC_VER */
};
#if defined(__cpp_deduction_guides) && (__cpp_deduction_guides >= 201703L)
template <class InputIt,
class Alloc = std::allocator<typename std::iterator_traits<InputIt>::value_type>>
dyn_array(InputIt, InputIt, Alloc = {})
-> dyn_array<typename std::iterator_traits<InputIt>::value_type, Alloc>;
#if defined(__cpp_lib_containers_ranges) && (__cpp_lib_containers_ranges >= 202202L)
template <std::ranges::input_range InputRg,
class Alloc = std::allocator<std::ranges::range_value_t<InputRg>>>
dyn_array(std::from_range_t, InputRg&&, Alloc = {})
-> dyn_array<std::ranges::range_value_t<InputRg>, Alloc>;
#endif /* __cpp_lib_containers_ranges >= 202202L */
#endif /* __cpp_deduction_guides >= 201703L */
} // namespace gsl
#endif /* defined(GSL_DYN_ARRAY_H) */
+13 -8
View File
@@ -17,13 +17,18 @@
#ifndef GSL_GSL_H
#define GSL_GSL_H
#include <gsl/gsl_algorithm> // copy
#include <gsl/gsl_assert> // Ensures/Expects
#include <gsl/gsl_byte> // byte
#include <gsl/gsl_util> // finally()/narrow()/narrow_cast()...
#include <gsl/multi_span> // multi_span, strided_span...
#include <gsl/pointers> // owner, not_null
#include <gsl/span> // span
#include <gsl/string_span> // zstring, string_span, zstring_builder...
// IWYU pragma: begin_exports
#include "./algorithm" // copy
#include "./assert" // Ensures/Expects
#include "./byte" // byte
#include "./pointers" // owner, not_null
#include "./span" // span
#include "./util" // finally()/narrow_cast()...
#include "./zstring" // zstring
#ifdef __cpp_exceptions
#include "./narrow" // narrow()
#endif
// IWYU pragma: end_exports
#endif // GSL_GSL_H
-166
View File
@@ -1,166 +0,0 @@
///////////////////////////////////////////////////////////////////////////////
//
// 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 <gsl/gsl_assert> // for Expects
#include <array>
#include <cstddef> // for ptrdiff_t, size_t
#include <exception> // for exception
#include <initializer_list> // for initializer_list
#include <type_traits> // for is_signed, integral_constant
#include <utility> // for forward
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable : 4127) // conditional expression is constant
#if _MSC_VER < 1910
#pragma push_macro("constexpr")
#define constexpr /*constexpr*/
#endif // _MSC_VER < 1910
#endif // _MSC_VER
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 F>
class final_action
{
public:
explicit final_action(F f) noexcept : f_(std::move(f)) {}
final_action(final_action&& other) noexcept : f_(std::move(other.f_)), invoke_(other.invoke_)
{
other.invoke_ = false;
}
final_action(const final_action&) = delete;
final_action& operator=(const final_action&) = delete;
final_action& operator=(final_action&&) = delete;
GSL_SUPPRESS(f.6) // NO-FORMAT: attribute // terminate if throws
~final_action() noexcept
{
if (invoke_) f_();
}
private:
F f_;
bool invoke_{true};
};
// finally() - convenience function to generate a final_action
template <class F>
final_action<F> finally(const F& f) noexcept
{
return final_action<F>(f);
}
template <class F>
final_action<F> finally(F&& f) noexcept
{
return final_action<F>(std::forward<F>(f));
}
// narrow_cast(): a searchable way to do narrowing casts of values
template <class T, class U>
GSL_SUPPRESS(type.1) // NO-FORMAT: attribute
constexpr T narrow_cast(U&& u) noexcept
{
return static_cast<T>(std::forward<U>(u));
}
struct narrowing_error : public std::exception
{
};
namespace details
{
template <class T, class U>
struct is_same_signedness
: public std::integral_constant<bool, std::is_signed<T>::value == std::is_signed<U>::value>
{
};
} // namespace details
// narrow() : a checked version of narrow_cast() that throws if the cast changed the value
template <class T, class U>
GSL_SUPPRESS(type.1) // NO-FORMAT: attribute
GSL_SUPPRESS(f.6) // NO-FORMAT: attribute // TODO: MSVC /analyze does not recognise noexcept(false)
T narrow(U u) noexcept(false)
{
T t = narrow_cast<T>(u);
if (static_cast<U>(t) != u) gsl::details::throw_exception(narrowing_error());
if (!details::is_same_signedness<T, U>::value && ((t < T{}) != (u < U{})))
gsl::details::throw_exception(narrowing_error());
return t;
}
//
// at() - Bounds-checked way of accessing builtin arrays, std::array, std::vector
//
template <class T, std::size_t N>
GSL_SUPPRESS(bounds.4) // NO-FORMAT: attribute
GSL_SUPPRESS(bounds.2) // NO-FORMAT: attribute
constexpr T& at(T (&arr)[N], const index i)
{
Expects(i >= 0 && i < narrow_cast<index>(N));
return arr[narrow_cast<std::size_t>(i)];
}
template <class Cont>
GSL_SUPPRESS(bounds.4) // NO-FORMAT: attribute
GSL_SUPPRESS(bounds.2) // NO-FORMAT: attribute
constexpr auto at(Cont& cont, const index i) -> decltype(cont[cont.size()])
{
Expects(i >= 0 && i < narrow_cast<index>(cont.size()));
using size_type = decltype(cont.size());
return cont[narrow_cast<size_type>(i)];
}
template <class T>
GSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute
constexpr T at(const std::initializer_list<T> cont, const index i)
{
Expects(i >= 0 && i < narrow_cast<index>(cont.size()));
return *(cont.begin() + i);
}
} // namespace gsl
#if defined(_MSC_VER)
#if _MSC_VER < 1910
#undef constexpr
#pragma pop_macro("constexpr")
#endif // _MSC_VER < 1910
#pragma warning(pop)
#endif // _MSC_VER
#endif // GSL_UTIL_H
File diff suppressed because it is too large Load Diff
+76
View File
@@ -0,0 +1,76 @@
///////////////////////////////////////////////////////////////////////////////
//
// 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 <exception> // 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 <class T, class U, typename std::enable_if<std::is_arithmetic<T>::value>::type* = nullptr>
GSL_SUPPRESS(type.1)
GSL_SUPPRESS(es.46) // 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
constexpr T narrow(U u)
{
constexpr const bool is_different_signedness =
(std::is_signed<T>::value != std::is_signed<U>::value);
GSL_SUPPRESS(es.103) // don't overflow
GSL_SUPPRESS(es.104) // don't underflow
GSL_SUPPRESS(p.2) // don't rely on undefined behavior
const T t = narrow_cast<T>(
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<U>(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 <class T, class U, typename std::enable_if<!std::is_arithmetic<T>::value>::type* = nullptr>
GSL_SUPPRESS(type.1) constexpr T narrow(U u)
{
const T t = narrow_cast<T>(u);
if (static_cast<U>(t) != u) { throw narrowing_error{}; }
return t;
}
} // namespace gsl
#endif // GSL_NARROW_H
+230 -46
View File
@@ -1,3 +1,4 @@
// -*- C++ -*-
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
@@ -17,38 +18,71 @@
#ifndef GSL_POINTERS_H
#define GSL_POINTERS_H
#include <gsl/gsl_assert> // for Ensures, Expects
#include "./assert" // for Ensures, Expects
#include "./util" // for GSL_DEPRECATED
#include <algorithm> // for forward
#include <iosfwd> // for ptrdiff_t, nullptr_t, ostream, size_t
#include <memory> // for shared_ptr, unique_ptr
#include <system_error> // for hash
#include <type_traits> // for enable_if_t, is_convertible, is_assignable
#include <cstddef> // for ptrdiff_t, nullptr_t, size_t
#include <functional> // for less, greater
#include <memory> // for shared_ptr, unique_ptr, hash
#include <type_traits> // for enable_if_t, is_convertible, is_assignable
#include <utility> // for declval, forward
#if defined(_MSC_VER) && _MSC_VER < 1910
#pragma push_macro("constexpr")
#define constexpr /*constexpr*/
#endif // defined(_MSC_VER) && _MSC_VER < 1910
#if !defined(GSL_NO_IOSTREAMS)
#include <iosfwd> // for ostream
#endif // !defined(GSL_NO_IOSTREAMS)
namespace gsl
{
namespace details
{
template <typename T, typename = void>
struct is_comparable_to_nullptr : std::false_type
{
};
template <typename T>
struct is_comparable_to_nullptr<
T,
std::enable_if_t<std::is_convertible<decltype(std::declval<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 <typename T>
using value_or_reference_return_t =
std::conditional_t<sizeof(T) <= 2 * sizeof(void*) &&
std::is_trivially_copy_constructible<T>::value,
const T, const T&>;
} // namespace details
//
// GSL.owner: ownership pointers
//
using std::unique_ptr;
using std::shared_ptr;
template <typename... Ts>
using shared_ptr GSL_DEPRECATED("Use std::shared_ptr instead") = std::shared_ptr<Ts...>;
template <typename... Ts>
using unique_ptr GSL_DEPRECATED("Use std::unique_ptr instead") = std::unique_ptr<Ts...>;
//
// owner
//
// owner<T> is designed as a bridge for code that must deal directly with owning pointers for some reason
// `gsl::owner<T>` 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 <class T, class = std::enable_if_t<std::is_pointer<T>::value>>
template <class T, std::enable_if_t<std::is_pointer<T>::value, bool> = true>
using owner = T;
//
@@ -69,38 +103,41 @@ template <class T>
class not_null
{
public:
static_assert(std::is_assignable<T&, std::nullptr_t>::value, "T cannot be assigned nullptr.");
static_assert(details::is_comparable_to_nullptr<T>::value, "T cannot be compared to nullptr.");
using element_type = T;
template <typename U, typename = std::enable_if_t<std::is_convertible<U, T>::value>>
constexpr explicit not_null(U&& u) : ptr_(std::forward<U>(u))
constexpr not_null(U&& u) noexcept(std::is_nothrow_move_constructible<T>::value)
: ptr_(std::forward<U>(u))
{
Expects(ptr_ != nullptr);
}
template <typename = std::enable_if_t<!std::is_same<std::nullptr_t, T>::value>>
constexpr explicit not_null(T u) : ptr_(u)
constexpr not_null(T u) noexcept(std::is_nothrow_move_constructible<T>::value)
: ptr_(std::move(u))
{
Expects(ptr_ != nullptr);
}
template <typename U, typename = std::enable_if_t<std::is_convertible<U, T>::value>>
constexpr not_null(const not_null<U>& other) : not_null(other.get())
{
}
constexpr not_null(const not_null<U>& other) noexcept(
std::is_nothrow_move_constructible<T>::value)
: not_null(other.get())
{}
not_null(not_null&& other) = default;
not_null(const not_null& other) = default;
not_null& operator=(const not_null& other) = default;
constexpr T get() const
constexpr details::value_or_reference_return_t<T> get() const
noexcept(noexcept(details::value_or_reference_return_t<T>(std::declval<T&>())))
{
Ensures(ptr_ != nullptr);
return ptr_;
}
constexpr operator T() const { return get(); }
constexpr T operator->() const { return get(); }
constexpr decltype(auto) operator*() 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;
@@ -115,56 +152,83 @@ public:
not_null& operator-=(std::ptrdiff_t) = delete;
void operator[](std::ptrdiff_t) const = delete;
void swap(not_null<T>& other) noexcept { std::swap(ptr_, other.ptr_); }
private:
T ptr_;
};
template <class T>
auto make_not_null(T&& t) {
return gsl::not_null<std::remove_cv_t<std::remove_reference_t<T>>>{std::forward<T>(t)};
template <typename T, std::enable_if_t<std::is_move_assignable<T>::value &&
std::is_move_constructible<T>::value,
bool> = true>
void swap(not_null<T>& a, not_null<T>& b) noexcept
{
a.swap(b);
}
template <class T>
auto make_not_null(T&& t) noexcept
{
return not_null<std::remove_cv_t<std::remove_reference_t<T>>>{std::forward<T>(t)};
}
#if !defined(GSL_NO_IOSTREAMS)
template <class T>
std::ostream& operator<<(std::ostream& os, const not_null<T>& val)
{
os << val.get();
return os;
}
#endif // !defined(GSL_NO_IOSTREAMS)
template <class T, class U>
auto operator==(const not_null<T>& lhs, const not_null<U>& rhs) -> decltype(lhs.get() == rhs.get())
constexpr auto operator==(const not_null<T>& lhs,
const not_null<U>& rhs) noexcept(noexcept(lhs.get() == rhs.get()))
-> decltype(lhs.get() == rhs.get())
{
return lhs.get() == rhs.get();
}
template <class T, class U>
auto operator!=(const not_null<T>& lhs, const not_null<U>& rhs) -> decltype(lhs.get() != rhs.get())
constexpr auto operator!=(const not_null<T>& lhs,
const not_null<U>& rhs) noexcept(noexcept(lhs.get() != rhs.get()))
-> decltype(lhs.get() != rhs.get())
{
return lhs.get() != rhs.get();
}
template <class T, class U>
auto operator<(const not_null<T>& lhs, const not_null<U>& rhs) -> decltype(lhs.get() < rhs.get())
constexpr auto operator<(const not_null<T>& lhs, const not_null<U>& rhs) noexcept(
noexcept(std::less<>{}(lhs.get(), rhs.get()))) -> decltype(std::less<>{}(lhs.get(), rhs.get()))
{
return lhs.get() < rhs.get();
return std::less<>{}(lhs.get(), rhs.get());
}
template <class T, class U>
auto operator<=(const not_null<T>& lhs, const not_null<U>& rhs) -> decltype(lhs.get() <= rhs.get())
constexpr auto
operator<=(const not_null<T>& lhs,
const not_null<U>& rhs) noexcept(noexcept(std::less_equal<>{}(lhs.get(), rhs.get())))
-> decltype(std::less_equal<>{}(lhs.get(), rhs.get()))
{
return lhs.get() <= rhs.get();
return std::less_equal<>{}(lhs.get(), rhs.get());
}
template <class T, class U>
auto operator>(const not_null<T>& lhs, const not_null<U>& rhs) -> decltype(lhs.get() > rhs.get())
constexpr auto
operator>(const not_null<T>& lhs,
const not_null<U>& rhs) noexcept(noexcept(std::greater<>{}(lhs.get(), rhs.get())))
-> decltype(std::greater<>{}(lhs.get(), rhs.get()))
{
return lhs.get() > rhs.get();
return std::greater<>{}(lhs.get(), rhs.get());
}
template <class T, class U>
auto operator>=(const not_null<T>& lhs, const not_null<U>& rhs) -> decltype(lhs.get() >= rhs.get())
constexpr auto
operator>=(const not_null<T>& lhs,
const not_null<U>& rhs) noexcept(noexcept(std::greater_equal<>{}(lhs.get(), rhs.get())))
-> decltype(std::greater_equal<>{}(lhs.get(), rhs.get()))
{
return lhs.get() >= rhs.get();
return std::greater_equal<>{}(lhs.get(), rhs.get());
}
// more unwanted operators
@@ -177,22 +241,142 @@ not_null<T> operator+(const not_null<T>&, std::ptrdiff_t) = delete;
template <class T>
not_null<T> operator+(std::ptrdiff_t, const not_null<T>&) = delete;
// T is conceptually a pointer so we don't have to worry about it being a reference and violating
// std::hash requirements
template <class T, class U = typename T::element_type,
bool = std::is_default_constructible<std::hash<U>>::value>
struct not_null_hash
{
std::size_t operator()(const T& value) const noexcept { return std::hash<U>{}(value.get()); }
};
template <class T, class U>
struct not_null_hash<T, U, false>
{
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 <class T>
struct hash<gsl::not_null<T>>
struct hash<gsl::not_null<T>> : gsl::not_null_hash<gsl::not_null<T>>
{
std::size_t operator()(const gsl::not_null<T>& value) const { return hash<T>{}(value); }
};
} // namespace std
#if defined(_MSC_VER) && _MSC_VER < 1910
#undef constexpr
#pragma pop_macro("constexpr")
namespace gsl
{
#endif // defined(_MSC_VER) && _MSC_VER < 1910
//
// 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 T>
class strict_not_null : public not_null<T>
{
public:
template <typename U, typename = std::enable_if_t<std::is_convertible<U, T>::value>>
constexpr explicit strict_not_null(U&& u) noexcept(std::is_nothrow_move_constructible<T>::value)
: not_null<T>(std::forward<U>(u))
{}
template <typename = std::enable_if_t<!std::is_same<std::nullptr_t, T>::value>>
constexpr explicit strict_not_null(T u) noexcept(std::is_nothrow_move_constructible<T>::value)
: not_null<T>(std::move(u))
{}
template <typename U, typename = std::enable_if_t<std::is_convertible<U, T>::value>>
constexpr strict_not_null(const not_null<U>& other) noexcept(
std::is_nothrow_move_constructible<T>::value)
: not_null<T>(other)
{}
template <typename U, typename = std::enable_if_t<std::is_convertible<U, T>::value>>
constexpr strict_not_null(const strict_not_null<U>& other) noexcept(
std::is_nothrow_move_constructible<T>::value)
: not_null<T>(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<T>::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<T>& other)
{
not_null<T>::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 <class T, class U>
std::ptrdiff_t operator-(const strict_not_null<T>&, const strict_not_null<U>&) = delete;
template <class T>
strict_not_null<T> operator-(const strict_not_null<T>&, std::ptrdiff_t) = delete;
template <class T>
strict_not_null<T> operator+(const strict_not_null<T>&, std::ptrdiff_t) = delete;
template <class T>
strict_not_null<T> operator+(std::ptrdiff_t, const strict_not_null<T>&) = delete;
template <class T>
auto make_strict_not_null(T&& t) noexcept
{
return strict_not_null<std::remove_cv_t<std::remove_reference_t<T>>>{std::forward<T>(t)};
}
#if defined(__cpp_deduction_guides) && (__cpp_deduction_guides >= 201703L)
// deduction guides to prevent the ctad-maybe-unsupported warning
template <class T>
not_null(T) -> not_null<T>;
template <class T>
strict_not_null(T) -> strict_not_null<T>;
#endif // defined(__cpp_deduction_guides) && (__cpp_deduction_guides >= 201703L)
} // namespace gsl
namespace std
{
template <class T>
struct hash<gsl::strict_not_null<T>> : gsl::not_null_hash<gsl::strict_not_null<T>>
{
};
} // namespace std
#endif // GSL_POINTERS_H
+451 -382
View File
File diff suppressed because it is too large Load Diff
+214
View File
@@ -0,0 +1,214 @@
///////////////////////////////////////////////////////////////////////////////
//
// 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 <cstddef> // for ptrdiff_t, size_t
#include <utility>
#ifndef GSL_KERNEL_MODE
#include <algorithm> // for lexicographical_compare
#endif // GSL_KERNEL_MODE
namespace gsl
{
// [span.views.constants], constants
GSL_INLINE constexpr const std::size_t dynamic_extent = narrow_cast<std::size_t>(-1);
template <class ElementType, std::size_t Extent = dynamic_extent>
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 <class ElementType, std::size_t FirstExtent, std::size_t SecondExtent>
constexpr bool operator==(span<ElementType, FirstExtent> l, span<ElementType, SecondExtent> r)
{
return std::equal(l.begin(), l.end(), r.begin(), r.end());
}
template <class ElementType, std::size_t Extent>
constexpr bool operator!=(span<ElementType, Extent> l, span<ElementType, Extent> r)
{
return !(l == r);
}
template <class ElementType, std::size_t Extent>
constexpr bool operator<(span<ElementType, Extent> l, span<ElementType, Extent> r)
{
return std::lexicographical_compare(l.begin(), l.end(), r.begin(), r.end());
}
template <class ElementType, std::size_t Extent>
constexpr bool operator<=(span<ElementType, Extent> l, span<ElementType, Extent> r)
{
return !(l > r);
}
template <class ElementType, std::size_t Extent>
constexpr bool operator>(span<ElementType, Extent> l, span<ElementType, Extent> r)
{
return r < l;
}
template <class ElementType, std::size_t Extent>
constexpr bool operator>=(span<ElementType, Extent> l, span<ElementType, Extent> r)
{
return !(l < r);
}
#endif // GSL_KERNEL_MODE
//
// make_span() - Utility functions for creating spans
//
template <class ElementType>
constexpr span<ElementType> make_span(ElementType* ptr, typename span<ElementType>::size_type count)
{
return span<ElementType>(ptr, count);
}
template <class ElementType>
constexpr span<ElementType> make_span(ElementType* firstElem, ElementType* lastElem)
{
return span<ElementType>(firstElem, lastElem);
}
template <class ElementType, std::size_t N>
constexpr span<ElementType, N> make_span(ElementType (&arr)[N]) noexcept
{
return span<ElementType, N>(arr);
}
template <class Container>
constexpr span<typename Container::value_type> make_span(Container& cont)
{
return span<typename Container::value_type>(cont);
}
template <class Container>
constexpr span<const typename Container::value_type> make_span(const Container& cont)
{
return span<const typename Container::value_type>(cont);
}
template <class Ptr>
GSL_DEPRECATED("This function is deprecated. See GSL issue #1092.")
constexpr span<typename Ptr::element_type> make_span(Ptr& cont, std::size_t count)
{
return span<typename Ptr::element_type>(cont, count);
}
template <class Ptr>
GSL_DEPRECATED("This function is deprecated. See GSL issue #1092.")
constexpr span<typename Ptr::element_type> make_span(Ptr& cont)
{
return span<typename Ptr::element_type>(cont);
}
// Specialization of gsl::at for span
template <class ElementType, std::size_t Extent>
constexpr ElementType& at(span<ElementType, Extent> s, index i)
{
// No bounds checking here because it is done in span::operator[] called below
Ensures(i >= 0);
return s[narrow_cast<std::size_t>(i)];
}
// [span.obs] Free observer functions
template <class ElementType, std::size_t Extent>
constexpr std::ptrdiff_t ssize(const span<ElementType, Extent>& s) noexcept
{
return gsl::narrow_cast<std::ptrdiff_t>(s.size());
}
// [span.iter] Free functions for begin/end functions
template <class ElementType, std::size_t Extent>
constexpr typename span<ElementType, Extent>::iterator
begin(const span<ElementType, Extent>& s) noexcept
{
return s.begin();
}
template <class ElementType, std::size_t Extent = dynamic_extent>
constexpr typename span<ElementType, Extent>::iterator
end(const span<ElementType, Extent>& s) noexcept
{
return s.end();
}
template <class ElementType, std::size_t Extent>
constexpr typename span<ElementType, Extent>::reverse_iterator
rbegin(const span<ElementType, Extent>& s) noexcept
{
return s.rbegin();
}
template <class ElementType, std::size_t Extent>
constexpr typename span<ElementType, Extent>::reverse_iterator
rend(const span<ElementType, Extent>& s) noexcept
{
return s.rend();
}
template <class ElementType, std::size_t Extent>
constexpr typename span<ElementType, Extent>::iterator
cbegin(const span<ElementType, Extent>& s) noexcept
{
return s.begin();
}
template <class ElementType, std::size_t Extent = dynamic_extent>
constexpr typename span<ElementType, Extent>::iterator
cend(const span<ElementType, Extent>& s) noexcept
{
return s.end();
}
template <class ElementType, std::size_t Extent>
constexpr typename span<ElementType, Extent>::reverse_iterator
crbegin(const span<ElementType, Extent>& s) noexcept
{
return s.rbegin();
}
template <class ElementType, std::size_t Extent>
constexpr typename span<ElementType, Extent>::reverse_iterator
crend(const span<ElementType, Extent>& s) noexcept
{
return s.rend();
}
} // namespace gsl
#endif // GSL_SPAN_EXT_H
-719
View File
@@ -1,719 +0,0 @@
///////////////////////////////////////////////////////////////////////////////
//
// 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_STRING_SPAN_H
#define GSL_STRING_SPAN_H
#include <gsl/gsl_assert> // for Ensures, Expects
#include <gsl/gsl_util> // for narrow_cast
#include <gsl/span> // for operator!=, operator==, dynamic_extent
#include <gsl/pointers> // for not_null
#include <algorithm> // for equal, lexicographical_compare
#include <array> // for array
#include <cstddef> // for ptrdiff_t, size_t, nullptr_t
#include <cstdint> // for PTRDIFF_MAX
#include <cstring>
#include <string> // for basic_string, allocator, char_traits
#include <type_traits> // for declval, is_convertible, enable_if_t, add_...
#ifdef _MSC_VER
#pragma warning(push)
// Turn MSVC /analyze rules that generate too much noise. TODO: fix in the tool.
#pragma warning(disable : 26446) // TODO: bug in parser - attributes and templates
#pragma warning(disable : 26481) // TODO: suppress does not work inside templates sometimes
#if _MSC_VER < 1910
#pragma push_macro("constexpr")
#define constexpr /*constexpr*/
#endif // _MSC_VER < 1910
#endif // _MSC_VER
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 <typename CharT, std::ptrdiff_t Extent = dynamic_extent>
using basic_zstring = CharT*;
template <std::ptrdiff_t Extent = dynamic_extent>
using czstring = basic_zstring<const char, Extent>;
template <std::ptrdiff_t Extent = dynamic_extent>
using cwzstring = basic_zstring<const wchar_t, Extent>;
template <std::ptrdiff_t Extent = dynamic_extent>
using cu16zstring = basic_zstring<const char16_t, Extent>;
template <std::ptrdiff_t Extent = dynamic_extent>
using cu32zstring = basic_zstring<const char32_t, Extent>;
template <std::ptrdiff_t Extent = dynamic_extent>
using zstring = basic_zstring<char, Extent>;
template <std::ptrdiff_t Extent = dynamic_extent>
using wzstring = basic_zstring<wchar_t, Extent>;
template <std::ptrdiff_t Extent = dynamic_extent>
using u16zstring = basic_zstring<char16_t, Extent>;
template <std::ptrdiff_t Extent = dynamic_extent>
using u32zstring = basic_zstring<char32_t, Extent>;
namespace details
{
template <class CharT>
std::ptrdiff_t string_length(const CharT* str, std::ptrdiff_t n)
{
if (str == nullptr || n <= 0) return 0;
const span<const CharT> str_span{str, n};
std::ptrdiff_t len = 0;
while (len < n && str_span[len]) len++;
return len;
}
} // namespace details
//
// ensure_sentinel()
//
// Provides a way to obtain an span from a contiguous sequence
// that ends with a (non-inclusive) sentinel value.
//
// Will fail-fast if sentinel cannot be found before max elements are examined.
//
template <typename T, const T Sentinel>
span<T, dynamic_extent> ensure_sentinel(T* seq, std::ptrdiff_t max = PTRDIFF_MAX)
{
Ensures(seq != nullptr);
GSL_SUPPRESS(f.23) // NO-FORMAT: attribute // TODO: false positive // TODO: suppress does not work
auto cur = seq;
Ensures(cur != nullptr); // workaround for removing the warning
GSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute // TODO: suppress does not work
while ((cur - seq) < max && *cur != Sentinel) ++cur;
Ensures(*cur == Sentinel);
return {seq, cur - seq};
}
//
// ensure_z - creates a span for a zero terminated strings.
// Will fail fast if a null-terminator cannot be found before
// the limit of size_type.
//
template <typename CharT>
span<CharT, dynamic_extent> ensure_z(CharT* const& sz, std::ptrdiff_t max = PTRDIFF_MAX)
{
return ensure_sentinel<CharT, CharT(0)>(sz, max);
}
template <typename CharT, std::size_t N>
span<CharT, dynamic_extent> ensure_z(CharT (&sz)[N])
{
return ensure_z(&sz[0], narrow_cast<std::ptrdiff_t>(N));
}
template <class Cont>
span<typename std::remove_pointer<typename Cont::pointer>::type, dynamic_extent>
ensure_z(Cont& cont)
{
return ensure_z(cont.data(), narrow_cast<std::ptrdiff_t>(cont.size()));
}
template <typename CharT, std::ptrdiff_t>
class basic_string_span;
namespace details {
template <typename T>
struct is_basic_string_span_oracle : std::false_type
{
};
template <typename CharT, std::ptrdiff_t Extent>
struct is_basic_string_span_oracle<basic_string_span<CharT, Extent>> : std::true_type
{
};
template <typename T>
struct is_basic_string_span : is_basic_string_span_oracle<std::remove_cv_t<T>>
{
};
} // namespace details
//
// string_span and relatives
//
template <typename CharT, std::ptrdiff_t Extent = dynamic_extent>
class basic_string_span
{
public:
using element_type = CharT;
using pointer = std::add_pointer_t<element_type>;
using reference = std::add_lvalue_reference_t<element_type>;
using const_reference = std::add_lvalue_reference_t<std::add_const_t<element_type>>;
using impl_type = span<element_type, Extent>;
using index_type = typename impl_type::index_type;
using iterator = typename impl_type::iterator;
using const_iterator = typename impl_type::const_iterator;
using reverse_iterator = typename impl_type::reverse_iterator;
using const_reverse_iterator = typename impl_type::const_reverse_iterator;
// default (empty)
constexpr basic_string_span() noexcept = default;
// copy
constexpr basic_string_span(const basic_string_span& other) noexcept = default;
// assign
constexpr basic_string_span& operator=(const basic_string_span& other) noexcept = default;
constexpr basic_string_span(pointer ptr, index_type length) : span_(ptr, length) {}
constexpr basic_string_span(pointer firstElem, pointer lastElem) : span_(firstElem, lastElem) {}
// From static arrays - if 0-terminated, remove 0 from the view
// All other containers allow 0s within the length, so we do not remove them
template <std::size_t N>
constexpr basic_string_span(element_type (&arr)[N]) : span_(remove_z(arr))
{}
template <std::size_t N, class ArrayElementType = std::remove_const_t<element_type>>
constexpr basic_string_span(std::array<ArrayElementType, N>& arr) noexcept : span_(arr)
{}
template <std::size_t N, class ArrayElementType = std::remove_const_t<element_type>>
constexpr basic_string_span(const std::array<ArrayElementType, N>& arr) noexcept : span_(arr)
{}
// Container signature should work for basic_string after C++17 version exists
template <class Traits, class Allocator>
// GSL_SUPPRESS(bounds.4) // NO-FORMAT: attribute // TODO: parser bug
constexpr basic_string_span(std::basic_string<element_type, Traits, Allocator>& str)
: span_(&str[0], narrow_cast<std::ptrdiff_t>(str.length()))
{}
template <class Traits, class Allocator>
constexpr basic_string_span(const std::basic_string<element_type, Traits, Allocator>& str)
: span_(&str[0], str.length())
{}
// from containers. Containers must have a pointer type and data() function signatures
template <class Container,
class = std::enable_if_t<
!details::is_basic_string_span<Container>::value &&
std::is_convertible<typename Container::pointer, pointer>::value &&
std::is_convertible<typename Container::pointer,
decltype(std::declval<Container>().data())>::value>>
constexpr basic_string_span(Container& cont) : span_(cont)
{}
template <class Container,
class = std::enable_if_t<
!details::is_basic_string_span<Container>::value &&
std::is_convertible<typename Container::pointer, pointer>::value &&
std::is_convertible<typename Container::pointer,
decltype(std::declval<Container>().data())>::value>>
constexpr basic_string_span(const Container& cont) : span_(cont)
{}
// from string_span
template <
class OtherValueType, std::ptrdiff_t OtherExtent,
class = std::enable_if_t<std::is_convertible<
typename basic_string_span<OtherValueType, OtherExtent>::impl_type, impl_type>::value>>
constexpr basic_string_span(basic_string_span<OtherValueType, OtherExtent> other)
: span_(other.data(), other.length())
{}
template <index_type Count>
constexpr basic_string_span<element_type, Count> first() const
{
return {span_.template first<Count>()};
}
constexpr basic_string_span<element_type, dynamic_extent> first(index_type count) const
{
return {span_.first(count)};
}
template <index_type Count>
constexpr basic_string_span<element_type, Count> last() const
{
return {span_.template last<Count>()};
}
constexpr basic_string_span<element_type, dynamic_extent> last(index_type count) const
{
return {span_.last(count)};
}
template <index_type Offset, index_type Count>
constexpr basic_string_span<element_type, Count> subspan() const
{
return {span_.template subspan<Offset, Count>()};
}
constexpr basic_string_span<element_type, dynamic_extent>
subspan(index_type offset, index_type count = dynamic_extent) const
{
return {span_.subspan(offset, count)};
}
constexpr reference operator[](index_type idx) const { return span_[idx]; }
constexpr reference operator()(index_type idx) const { return span_[idx]; }
constexpr pointer data() const { return span_.data(); }
constexpr index_type length() const noexcept { return span_.size(); }
constexpr index_type size() const noexcept { return span_.size(); }
constexpr index_type size_bytes() const noexcept { return span_.size_bytes(); }
constexpr index_type length_bytes() const noexcept { return span_.length_bytes(); }
constexpr bool empty() const noexcept { return size() == 0; }
constexpr iterator begin() const noexcept { return span_.begin(); }
constexpr iterator end() const noexcept { return span_.end(); }
constexpr const_iterator cbegin() const noexcept { return span_.cbegin(); }
constexpr const_iterator cend() const noexcept { return span_.cend(); }
constexpr reverse_iterator rbegin() const noexcept { return span_.rbegin(); }
constexpr reverse_iterator rend() const noexcept { return span_.rend(); }
constexpr const_reverse_iterator crbegin() const noexcept { return span_.crbegin(); }
constexpr const_reverse_iterator crend() const noexcept { return span_.crend(); }
private:
static impl_type remove_z(pointer const& sz, std::ptrdiff_t max)
{
return {sz, details::string_length(sz, max)};
}
template <std::size_t N>
static impl_type remove_z(element_type (&sz)[N])
{
return remove_z(&sz[0], narrow_cast<std::ptrdiff_t>(N));
}
impl_type span_;
};
template <std::ptrdiff_t Extent = dynamic_extent>
using string_span = basic_string_span<char, Extent>;
template <std::ptrdiff_t Extent = dynamic_extent>
using cstring_span = basic_string_span<const char, Extent>;
template <std::ptrdiff_t Extent = dynamic_extent>
using wstring_span = basic_string_span<wchar_t, Extent>;
template <std::ptrdiff_t Extent = dynamic_extent>
using cwstring_span = basic_string_span<const wchar_t, Extent>;
template <std::ptrdiff_t Extent = dynamic_extent>
using u16string_span = basic_string_span<char16_t, Extent>;
template <std::ptrdiff_t Extent = dynamic_extent>
using cu16string_span = basic_string_span<const char16_t, Extent>;
template <std::ptrdiff_t Extent = dynamic_extent>
using u32string_span = basic_string_span<char32_t, Extent>;
template <std::ptrdiff_t Extent = dynamic_extent>
using cu32string_span = basic_string_span<const char32_t, Extent>;
//
// to_string() allow (explicit) conversions from string_span to string
//
template <typename CharT, std::ptrdiff_t Extent>
std::basic_string<typename std::remove_const<CharT>::type>
to_string(basic_string_span<CharT, Extent> view)
{
return {view.data(), narrow_cast<std::size_t>(view.length())};
}
template <typename CharT, typename Traits = typename std::char_traits<CharT>,
typename Allocator = std::allocator<CharT>, typename gCharT, std::ptrdiff_t Extent>
std::basic_string<CharT, Traits, Allocator> to_basic_string(basic_string_span<gCharT, Extent> view)
{
return {view.data(), narrow_cast<std::size_t>(view.length())};
}
template <class ElementType, std::ptrdiff_t Extent>
basic_string_span<const byte, details::calculate_byte_size<ElementType, Extent>::value>
as_bytes(basic_string_span<ElementType, Extent> s) noexcept
{
GSL_SUPPRESS(type.1) // NO-FORMAT: attribute
return {reinterpret_cast<const byte*>(s.data()), s.size_bytes()};
}
template <class ElementType, std::ptrdiff_t Extent,
class = std::enable_if_t<!std::is_const<ElementType>::value>>
basic_string_span<byte, details::calculate_byte_size<ElementType, Extent>::value>
as_writeable_bytes(basic_string_span<ElementType, Extent> s) noexcept
{
GSL_SUPPRESS(type.1) // NO-FORMAT: attribute
return {reinterpret_cast<byte*>(s.data()), s.size_bytes()};
}
// zero-terminated string span, used to convert
// zero-terminated spans to legacy strings
template <typename CharT, std::ptrdiff_t Extent = dynamic_extent>
class basic_zstring_span {
public:
using value_type = CharT;
using const_value_type = std::add_const_t<CharT>;
using pointer = std::add_pointer_t<value_type>;
using const_pointer = std::add_pointer_t<const_value_type>;
using zstring_type = basic_zstring<value_type, Extent>;
using const_zstring_type = basic_zstring<const_value_type, Extent>;
using impl_type = span<value_type, Extent>;
using string_span_type = basic_string_span<value_type, Extent>;
constexpr basic_zstring_span(impl_type s) : span_(s)
{
// expects a zero-terminated span
Expects(s[s.size() - 1] == '\0');
}
// copy
constexpr basic_zstring_span(const basic_zstring_span& other) = default;
// move
constexpr basic_zstring_span(basic_zstring_span&& other) = default;
// assign
constexpr basic_zstring_span& operator=(const basic_zstring_span& other) = default;
// move assign
constexpr basic_zstring_span& operator=(basic_zstring_span&& other) = default;
constexpr bool empty() const noexcept { return span_.size() == 0; }
constexpr string_span_type as_string_span() const noexcept
{
const auto sz = span_.size();
return {span_.data(), sz > 1 ? sz - 1 : 0};
}
constexpr string_span_type ensure_z() const { return gsl::ensure_z(span_); }
constexpr const_zstring_type assume_z() const noexcept { return span_.data(); }
private:
impl_type span_;
};
template <std::ptrdiff_t Max = dynamic_extent>
using zstring_span = basic_zstring_span<char, Max>;
template <std::ptrdiff_t Max = dynamic_extent>
using wzstring_span = basic_zstring_span<wchar_t, Max>;
template <std::ptrdiff_t Max = dynamic_extent>
using u16zstring_span = basic_zstring_span<char16_t, Max>;
template <std::ptrdiff_t Max = dynamic_extent>
using u32zstring_span = basic_zstring_span<char32_t, Max>;
template <std::ptrdiff_t Max = dynamic_extent>
using czstring_span = basic_zstring_span<const char, Max>;
template <std::ptrdiff_t Max = dynamic_extent>
using cwzstring_span = basic_zstring_span<const wchar_t, Max>;
template <std::ptrdiff_t Max = dynamic_extent>
using cu16zstring_span = basic_zstring_span<const char16_t, Max>;
template <std::ptrdiff_t Max = dynamic_extent>
using cu32zstring_span = basic_zstring_span<const char32_t, Max>;
// operator ==
template <class CharT, std::ptrdiff_t Extent, class T,
class = std::enable_if_t<
details::is_basic_string_span<T>::value ||
std::is_convertible<T, gsl::basic_string_span<std::add_const_t<CharT>>>::value>>
bool operator==(const gsl::basic_string_span<CharT, Extent>& one, const T& other)
{
const gsl::basic_string_span<std::add_const_t<CharT>> tmp(other);
return std::equal(one.begin(), one.end(), tmp.begin(), tmp.end());
}
template <class CharT, std::ptrdiff_t Extent, class T,
class = std::enable_if_t<
!details::is_basic_string_span<T>::value &&
std::is_convertible<T, gsl::basic_string_span<std::add_const_t<CharT>>>::value>>
bool operator==(const T& one, const gsl::basic_string_span<CharT, Extent>& other)
{
const gsl::basic_string_span<std::add_const_t<CharT>> tmp(one);
return std::equal(tmp.begin(), tmp.end(), other.begin(), other.end());
}
// operator !=
template <typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename = std::enable_if_t<std::is_convertible<
T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value>>
bool operator!=(gsl::basic_string_span<CharT, Extent> one, const T& other)
{
return !(one == other);
}
template <
typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename = std::enable_if_t<
std::is_convertible<T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value &&
!gsl::details::is_basic_string_span<T>::value>>
bool operator!=(const T& one, gsl::basic_string_span<CharT, Extent> other)
{
return !(one == other);
}
// operator<
template <typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename = std::enable_if_t<std::is_convertible<
T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value>>
bool operator<(gsl::basic_string_span<CharT, Extent> one, const T& other)
{
const gsl::basic_string_span<std::add_const_t<CharT>, Extent> tmp(other);
return std::lexicographical_compare(one.begin(), one.end(), tmp.begin(), tmp.end());
}
template <
typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename = std::enable_if_t<
std::is_convertible<T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value &&
!gsl::details::is_basic_string_span<T>::value>>
bool operator<(const T& one, gsl::basic_string_span<CharT, Extent> other)
{
gsl::basic_string_span<std::add_const_t<CharT>, Extent> tmp(one);
return std::lexicographical_compare(tmp.begin(), tmp.end(), other.begin(), other.end());
}
#ifndef _MSC_VER
// VS treats temp and const containers as convertible to basic_string_span,
// so the cases below are already covered by the previous operators
template <
typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename DataType = typename T::value_type,
typename = std::enable_if_t<
!gsl::details::is_span<T>::value && !gsl::details::is_basic_string_span<T>::value &&
std::is_convertible<DataType*, CharT*>::value &&
std::is_same<std::decay_t<decltype(std::declval<T>().size(), *std::declval<T>().data())>,
DataType>::value>>
bool operator<(gsl::basic_string_span<CharT, Extent> one, const T& other)
{
gsl::basic_string_span<std::add_const_t<CharT>, Extent> tmp(other);
return std::lexicographical_compare(one.begin(), one.end(), tmp.begin(), tmp.end());
}
template <
typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename DataType = typename T::value_type,
typename = std::enable_if_t<
!gsl::details::is_span<T>::value && !gsl::details::is_basic_string_span<T>::value &&
std::is_convertible<DataType*, CharT*>::value &&
std::is_same<std::decay_t<decltype(std::declval<T>().size(), *std::declval<T>().data())>,
DataType>::value>>
bool operator<(const T& one, gsl::basic_string_span<CharT, Extent> other)
{
gsl::basic_string_span<std::add_const_t<CharT>, Extent> tmp(one);
return std::lexicographical_compare(tmp.begin(), tmp.end(), other.begin(), other.end());
}
#endif
// operator <=
template <typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename = std::enable_if_t<std::is_convertible<
T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value>>
bool operator<=(gsl::basic_string_span<CharT, Extent> one, const T& other)
{
return !(other < one);
}
template <
typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename = std::enable_if_t<
std::is_convertible<T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value &&
!gsl::details::is_basic_string_span<T>::value>>
bool operator<=(const T& one, gsl::basic_string_span<CharT, Extent> other)
{
return !(other < one);
}
#ifndef _MSC_VER
// VS treats temp and const containers as convertible to basic_string_span,
// so the cases below are already covered by the previous operators
template <
typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename DataType = typename T::value_type,
typename = std::enable_if_t<
!gsl::details::is_span<T>::value && !gsl::details::is_basic_string_span<T>::value &&
std::is_convertible<DataType*, CharT*>::value &&
std::is_same<std::decay_t<decltype(std::declval<T>().size(), *std::declval<T>().data())>,
DataType>::value>>
bool operator<=(gsl::basic_string_span<CharT, Extent> one, const T& other)
{
return !(other < one);
}
template <
typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename DataType = typename T::value_type,
typename = std::enable_if_t<
!gsl::details::is_span<T>::value && !gsl::details::is_basic_string_span<T>::value &&
std::is_convertible<DataType*, CharT*>::value &&
std::is_same<std::decay_t<decltype(std::declval<T>().size(), *std::declval<T>().data())>,
DataType>::value>>
bool operator<=(const T& one, gsl::basic_string_span<CharT, Extent> other)
{
return !(other < one);
}
#endif
// operator>
template <typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename = std::enable_if_t<std::is_convertible<
T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value>>
bool operator>(gsl::basic_string_span<CharT, Extent> one, const T& other)
{
return other < one;
}
template <
typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename = std::enable_if_t<
std::is_convertible<T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value &&
!gsl::details::is_basic_string_span<T>::value>>
bool operator>(const T& one, gsl::basic_string_span<CharT, Extent> other)
{
return other < one;
}
#ifndef _MSC_VER
// VS treats temp and const containers as convertible to basic_string_span,
// so the cases below are already covered by the previous operators
template <
typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename DataType = typename T::value_type,
typename = std::enable_if_t<
!gsl::details::is_span<T>::value && !gsl::details::is_basic_string_span<T>::value &&
std::is_convertible<DataType*, CharT*>::value &&
std::is_same<std::decay_t<decltype(std::declval<T>().size(), *std::declval<T>().data())>,
DataType>::value>>
bool operator>(gsl::basic_string_span<CharT, Extent> one, const T& other)
{
return other < one;
}
template <
typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename DataType = typename T::value_type,
typename = std::enable_if_t<
!gsl::details::is_span<T>::value && !gsl::details::is_basic_string_span<T>::value &&
std::is_convertible<DataType*, CharT*>::value &&
std::is_same<std::decay_t<decltype(std::declval<T>().size(), *std::declval<T>().data())>,
DataType>::value>>
bool operator>(const T& one, gsl::basic_string_span<CharT, Extent> other)
{
return other < one;
}
#endif
// operator >=
template <typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename = std::enable_if_t<std::is_convertible<
T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value>>
bool operator>=(gsl::basic_string_span<CharT, Extent> one, const T& other)
{
return !(one < other);
}
template <
typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename = std::enable_if_t<
std::is_convertible<T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value &&
!gsl::details::is_basic_string_span<T>::value>>
bool operator>=(const T& one, gsl::basic_string_span<CharT, Extent> other)
{
return !(one < other);
}
#ifndef _MSC_VER
// VS treats temp and const containers as convertible to basic_string_span,
// so the cases below are already covered by the previous operators
template <
typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename DataType = typename T::value_type,
typename = std::enable_if_t<
!gsl::details::is_span<T>::value && !gsl::details::is_basic_string_span<T>::value &&
std::is_convertible<DataType*, CharT*>::value &&
std::is_same<std::decay_t<decltype(std::declval<T>().size(), *std::declval<T>().data())>,
DataType>::value>>
bool operator>=(gsl::basic_string_span<CharT, Extent> one, const T& other)
{
return !(one < other);
}
template <
typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename DataType = typename T::value_type,
typename = std::enable_if_t<
!gsl::details::is_span<T>::value && !gsl::details::is_basic_string_span<T>::value &&
std::is_convertible<DataType*, CharT*>::value &&
std::is_same<std::decay_t<decltype(std::declval<T>().size(), *std::declval<T>().data())>,
DataType>::value>>
bool operator>=(const T& one, gsl::basic_string_span<CharT, Extent> other)
{
return !(one < other);
}
#endif
} // namespace gsl
#ifdef _MSC_VER
#pragma warning(pop)
#if _MSC_VER < 1910
#undef constexpr
#pragma pop_macro("constexpr")
#endif // _MSC_VER < 1910
#endif // _MSC_VER
#endif // GSL_STRING_SPAN_H
+232
View File
@@ -0,0 +1,232 @@
// -*- C++ -*-
///////////////////////////////////////////////////////////////////////////////
//
// 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 <cstddef> // for ptrdiff_t, size_t
#include <initializer_list> // for initializer_list
#include <iterator> // for iterator_traits
#include <limits> // for numeric_limits
#include <type_traits> // for is_signed, integral_constant
#include <utility> // for exchange, forward
#if defined(__has_include) && __has_include(<version>)
#include <version>
#if defined(__cpp_lib_span) && __cpp_lib_span >= 202002L
#include <span>
#endif // __cpp_lib_span >= 202002L
#endif //__has_include(<version>)
#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)
#if __cplusplus >= 202002L
#define GSL_CONSTEXPR_SINCE_CPP20 constexpr
#else // ^^^ since C++20 /// before C++20 vvv
#define GSL_BEFORE_CPP20
#define GSL_CONSTEXPR_SINCE_CPP20
#endif // __cplusplus >= 202002L
namespace gsl
{
//
// GSL.util: utilities
//
// index type for all container indexes/subscripts/sizes
using index = std::ptrdiff_t;
namespace details
{
template <typename...>
using void_t = void;
template <typename T, typename = void>
struct is_iterator : std::false_type
{
};
template <typename T>
struct is_iterator<T, void_t<typename std::iterator_traits<T>::value_type>> : std::true_type
{
};
template <typename T, typename = void>
struct is_fwd_iterator : std::false_type
{
};
template <typename T>
struct is_fwd_iterator<T, void_t<typename std::iterator_traits<T>::iterator_category>>
: std::integral_constant<
bool, std::is_base_of<std::forward_iterator_tag,
typename std::iterator_traits<T>::iterator_category>::value>
{
};
} // namespace details
// final_action allows you to ensure something gets run at the end of a scope
template <class F>
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 <class F>
GSL_NODISCARD auto finally(F&& f) noexcept
{
return final_action<std::decay_t<F>>{std::forward<F>(f)};
}
// narrow_cast(): a searchable way to do narrowing casts of values
template <class T, class U>
GSL_SUPPRESS(type.1) constexpr T narrow_cast(U&& u) noexcept
{
return static_cast<T>(std::forward<U>(u));
}
//
// at() - Bounds-checked way of accessing builtin arrays, std::array, std::vector
//
template <class T, std::size_t N>
GSL_SUPPRESS(bounds.4) GSL_SUPPRESS(bounds.2) constexpr T& at(T (&arr)[N], const index i)
{
static_assert(N <= static_cast<std::size_t>((std::numeric_limits<std::ptrdiff_t>::max)()),
"We only support arrays up to PTRDIFF_MAX bytes.");
Expects(i >= 0 && i < narrow_cast<index>(N));
return arr[narrow_cast<std::size_t>(i)];
}
template <class Cont>
GSL_SUPPRESS(bounds.4) GSL_SUPPRESS(bounds.2) constexpr auto at(Cont& cont, const index i)
-> decltype(cont[cont.size()])
{
Expects(i >= 0 && i < narrow_cast<index>(cont.size()));
using size_type = decltype(cont.size());
return cont[narrow_cast<size_type>(i)];
}
template <class T>
GSL_SUPPRESS(bounds.1) constexpr T at(const std::initializer_list<T> cont, const index i)
{
Expects(i >= 0 && i < narrow_cast<index>(cont.size()));
return *(cont.begin() + i);
}
template <class T, std::enable_if_t<std::is_move_assignable<T>::value &&
std::is_move_constructible<T>::value>>
void swap(T& a, T& b)
{
std::swap(a, b);
}
#if defined(__cpp_lib_span) && __cpp_lib_span >= 202002L
template <class T, std::size_t extent = std::dynamic_extent>
constexpr auto at(std::span<T, extent> sp, const index i) -> decltype(sp[sp.size()])
{
Expects(i >= 0 && i < narrow_cast<index>(sp.size()));
return sp[gsl::narrow_cast<std::size_t>(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
+58
View File
@@ -0,0 +1,58 @@
///////////////////////////////////////////////////////////////////////////////
//
// 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 <cstddef> // 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 <typename CharT, std::size_t Extent = dynamic_extent>
using basic_zstring = CharT*;
using czstring = basic_zstring<const char, dynamic_extent>;
using cwzstring = basic_zstring<const wchar_t, dynamic_extent>;
using cu16zstring = basic_zstring<const char16_t, dynamic_extent>;
using cu32zstring = basic_zstring<const char32_t, dynamic_extent>;
using zstring = basic_zstring<char, dynamic_extent>;
using wzstring = basic_zstring<wchar_t, dynamic_extent>;
using u16zstring = basic_zstring<char16_t, dynamic_extent>;
using u32zstring = basic_zstring<char32_t, dynamic_extent>;
} // namespace gsl
#endif // GSL_ZSTRING_H
-130
View File
@@ -1,130 +0,0 @@
///////////////////////////////////////////////////////////////////////////////
//
// 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_TRANSITION_H
#define GSL_TRANSITION_H
#include <gsl/gsl_assert> // for Ensures, Expects
#include <gsl/pointers> // for gsl::not_null
#if defined(_MSC_VER) && _MSC_VER < 1910
#pragma push_macro("constexpr")
#define constexpr /*constexpr*/
#endif // defined(_MSC_VER) && _MSC_VER < 1910
namespace gsl_helpers
{
//
// sloppy_not_null
//
// Restricts a pointer or smart pointer to only hold non-null values,
//
// - provides a sloppy (i.e. no explicit contructor from T) wrapper of gsl::not_null
// - is temporary, only to be used to incrementally transition of code
// using older version of gsl::not_null to the new one that made the constructor explicit
//
// To make the transition:
//
// - replace all occurences of gsl::not_null in your code by sloppy_not_null
// variant: rename gsl::not_null by NotNull by including the following in your code,
// foe example, in a common include file:
//
// template<typename T>
// using NotNull = gsl::not_null<T>;
//
// compile using old version of GSL
// change GSL version and replace gsl::not_null by gsl_helpers::sloppy_not_null
// in the added code lines above
//
// - compile - compilation should be successful
// - replace some sloppy_not_nulls by gsl::not_null, fix compilation erros,
// redesign as needed, compile and test
// - repeat until no sloppy_not_nulls remain
//
template <class T>
class sloppy_not_null: public gsl::not_null<T>
{
public:
template <typename U, typename = std::enable_if_t<std::is_convertible<U, T>::value>>
constexpr sloppy_not_null(U&& u) :
gsl::not_null<T>(std::forward<U>(u))
{}
template <typename = std::enable_if_t<!std::is_same<std::nullptr_t, T>::value>>
constexpr sloppy_not_null(T u) :
gsl::not_null<T>(u)
{}
template <typename U, typename = std::enable_if_t<std::is_convertible<U, T>::value>>
constexpr sloppy_not_null(const gsl::not_null<U>& other) :
gsl::not_null<T>(other)
{}
sloppy_not_null(sloppy_not_null&& other) = default;
sloppy_not_null(const sloppy_not_null& other) = default;
sloppy_not_null& operator=(const sloppy_not_null& other) = default;
sloppy_not_null& operator=(const gsl::not_null<T>& other)
{
gsl::not_null<T>::operator=(other);
return *this;
}
// prevents compilation when someone attempts to assign a null pointer constant
sloppy_not_null(std::nullptr_t) = delete;
sloppy_not_null& operator=(std::nullptr_t) = delete;
// unwanted operators...pointers only point to single objects!
sloppy_not_null& operator++() = delete;
sloppy_not_null& operator--() = delete;
sloppy_not_null operator++(int) = delete;
sloppy_not_null operator--(int) = delete;
sloppy_not_null& operator+=(std::ptrdiff_t) = delete;
sloppy_not_null& operator-=(std::ptrdiff_t) = delete;
void operator[](std::ptrdiff_t) const = delete;
};
// more unwanted operators
template <class T, class U>
std::ptrdiff_t operator-(const sloppy_not_null<T>&, const sloppy_not_null<U>&) = delete;
template <class T>
sloppy_not_null<T> operator-(const sloppy_not_null<T>&, std::ptrdiff_t) = delete;
template <class T>
sloppy_not_null<T> operator+(const sloppy_not_null<T>&, std::ptrdiff_t) = delete;
template <class T>
sloppy_not_null<T> operator+(std::ptrdiff_t, const sloppy_not_null<T>&) = delete;
} // namespace gsl
namespace std
{
template <class T>
struct hash<gsl_helpers::sloppy_not_null<T>>
{
std::size_t operator()(const gsl_helpers::sloppy_not_null<T>& value) const { return hash<T>{}(value); }
};
} // namespace std
#if defined(_MSC_VER) && _MSC_VER < 1910
#undef constexpr
#pragma pop_macro("constexpr")
#endif // defined(_MSC_VER) && _MSC_VER < 1910
#endif // GSL_TRANSITION_H
+13
View File
@@ -0,0 +1,13 @@
@echo off
setlocal enabledelayedexpansion
"%VCINSTALLDIR%Tools\Llvm\bin\clang-format" -version
if %errorlevel% neq 0 (
echo [ERROR] clang-format not found, script should be called from a visual studio developer command prompt.
exit /b %errorlevel%
)
for %%f in (include\gsl\* tests\*.h tests\*.cpp) do (
echo formatting %%f
"%VCINSTALLDIR%Tools\Llvm\bin\clang-format" -i --assume-filename x.cpp "%%f"
)
+18
View File
@@ -0,0 +1,18 @@
#!/bin/bash
set -euo pipefail
cf=clang-format-$(grep -i 'CLANG_VERSION:' .github/workflows/clang-format.yml | sed -E 's/.*"([^"]+)".*/\1/')
readonly cf
if ! "${cf}" -version; then
echo "[ERROR] clang-format not found. Please install it using: sudo apt install ${cf}"
exit 1
fi
{
find include/gsl -type f
find tests -type f \( -name '*.cpp' -o -name '*.h' \)
} | xargs "${cf}" -i --assume-filename=x.cpp --verbose
find scripts -type f -name '*.sh' -print -exec shfmt -w {} \;
+259 -117
View File
@@ -1,46 +1,131 @@
cmake_minimum_required(VERSION 2.8.7)
cmake_minimum_required(VERSION 3.14...3.16)
project(GSLTests CXX)
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)
list(APPEND CATCH_CMAKE_ARGS
"-DCMAKE_INSTALL_PREFIX=${CMAKE_BINARY_DIR}/external"
"-DNO_SELFTEST=true"
)
if(GIT_FOUND)
# add catch
ExternalProject_Add(
catch
PREFIX ${CMAKE_BINARY_DIR}/catch
GIT_REPOSITORY https://github.com/catchorg/Catch2.git
GIT_TAG v2.0.1
CMAKE_ARGS ${CATCH_CMAKE_ARGS}
LOG_DOWNLOAD 1
UPDATE_DISCONNECTED 1
)
else()
# assume catch is installed in a system directory
add_custom_target(catch)
if(CI_TESTING AND GSL_CXX_STANDARD EQUAL 20)
add_compile_definitions(FORCE_STD_SPAN_TESTS=1)
endif()
if (MSVC AND (GSL_CXX_STANDARD EQUAL 17))
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)
target_compile_options(gsl_tests_config INTERFACE
$<$<CXX_COMPILER_ID:MSVC>:
if(MSVC) # MSVC or simulating MSVC
target_compile_options(gsl_tests_config INTERFACE
${GSL_CPLUSPLUS_OPT}
/EHsc
/W4
/WX
>
${GSL_CPLUSPLUS_OPT}
$<$<NOT:$<CXX_COMPILER_ID:MSVC>>:
$<$<CXX_COMPILER_ID:MSVC>:
/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
$<$<VERSION_LESS:$<CXX_COMPILER_VERSION>,1920>: # VS2015
/wd4189 # variable is initialized but not referenced
$<$<NOT:$<CONFIG:Debug>>: # Release, RelWithDebInfo
/wd4702 # Unreachable code
>
>
>
$<$<CXX_COMPILER_ID:Clang>:
-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
$<$<EQUAL:${GSL_CXX_STANDARD},14>: # no support for [[maybe_unused]]
-Wno-unused-member-function
-Wno-unused-variable
$<$<VERSION_EQUAL:$<CXX_COMPILER_VERSION>,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
@@ -48,67 +133,89 @@ target_compile_options(gsl_tests_config INTERFACE
-Wctor-dtor-privacy
-Werror
-Wextra
-Wno-missing-braces
-Wno-unknown-attributes
-Wnon-virtual-dtor
-Wold-style-cast
-Woverloaded-virtual
-Wpedantic
-Wshadow
-Wsign-conversion
>
-Wfloat-equal
-Wno-deprecated-declarations # Allow tests for [[deprecated]] elements
$<$<OR:$<CXX_COMPILER_ID:Clang>,$<CXX_COMPILER_ID:AppleClang>>:
-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
-Wno-poison-system-directories
$<$<EQUAL:${GSL_CXX_STANDARD},14>: # no support for [[maybe_unused]]
-Wno-unused-member-function
-Wno-unused-variable
>
>
$<$<CXX_COMPILER_ID:Clang>:
$<$<AND:$<VERSION_GREATER:$<CXX_COMPILER_VERSION>,4.99>,$<VERSION_LESS:$<CXX_COMPILER_VERSION>,6>>:
$<$<EQUAL:${GSL_CXX_STANDARD},17>:-Wno-undefined-func-template>
>
$<$<AND:$<EQUAL:${GSL_CXX_STANDARD},20>,$<OR:$<CXX_COMPILER_VERSION:11.0.0>,$<CXX_COMPILER_VERSION:10.0.0>>>:
-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)
>
>
$<$<CXX_COMPILER_ID:AppleClang>:
$<$<AND:$<VERSION_GREATER:$<CXX_COMPILER_VERSION>,9.1>,$<VERSION_LESS:$<CXX_COMPILER_VERSION>,10>>:
$<$<EQUAL:${GSL_CXX_STANDARD},17>:-Wno-undefined-func-template>
>
>
$<$<CXX_COMPILER_ID:GNU>:
-Wdouble-promotion # float implicit to double
-Wlogical-op # suspicious uses of logical operators
$<$<NOT:$<VERSION_LESS:$<CXX_COMPILER_VERSION>,6>>:
-Wduplicated-cond # duplicated if-else conditions
-Wmisleading-indentation
-Wnull-dereference
$<$<EQUAL:${GSL_CXX_STANDARD},14>: # no support for [[maybe_unused]]
-Wno-unused-variable
>
>
$<$<NOT:$<VERSION_LESS:$<CXX_COMPILER_VERSION>,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
)
# for tests to find the catch header
target_include_directories(gsl_tests_config INTERFACE
${CMAKE_BINARY_DIR}/external/include
)
# Individually build and register each test source (except no_exception_ensure_tests.cpp)
# no_exception_ensure_tests.cpp is built separately with exceptions disabled
file(GLOB GSL_TEST_SOURCES CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp")
list(FILTER GSL_TEST_SOURCES EXCLUDE REGEX "no_exception_ensure_tests\\.cpp$")
# set definitions for tests
target_compile_definitions(gsl_tests_config INTERFACE
GSL_THROW_ON_CONTRACT_VIOLATION
)
# create the main executable for each test. this reduces the compile time
# of each test by pre-compiling catch.
add_library(test_catch STATIC test.cpp)
target_link_libraries(test_catch
GSL
foreach(src IN LISTS GSL_TEST_SOURCES)
get_filename_component(test_name "${src}" NAME_WE)
add_executable(${test_name} ${src})
target_link_libraries(${test_name}
Microsoft.GSL::GSL
gsl_tests_config
)
add_dependencies(test_catch catch)
set_property(TARGET test_catch PROPERTY FOLDER "GSL_tests")
function(add_gsl_test name)
add_executable(${name} ${name}.cpp)
target_link_libraries(${name}
GSL
test_catch
gsl_tests_config
)
add_dependencies(${name} catch)
add_test(
${name}
${name}
)
# group all tests under GSL_tests
set_property(TARGET ${name} PROPERTY FOLDER "GSL_tests")
endfunction()
add_gsl_test(span_tests)
add_gsl_test(multi_span_tests)
add_gsl_test(strided_span_tests)
add_gsl_test(string_span_tests)
add_gsl_test(at_tests)
add_gsl_test(bounds_tests)
add_gsl_test(notnull_tests)
add_gsl_test(assertion_tests)
add_gsl_test(utils_tests)
add_gsl_test(owner_tests)
add_gsl_test(byte_tests)
add_gsl_test(algorithm_tests)
add_gsl_test(sloppy_notnull_tests)
${GTestMain_LIBRARIES}
)
add_test(NAME ${test_name} COMMAND ${test_name})
set_target_properties(${test_name} PROPERTIES FOLDER "tests")
endforeach()
# No exception tests
@@ -121,53 +228,88 @@ 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)
target_compile_options(gsl_tests_config_noexcept INTERFACE
$<$<CXX_COMPILER_ID:MSVC>:
/D_HAS_EXCEPTIONS=0
/wd4702
/wd4577
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
>
${GSL_CPLUSPLUS_OPT}
$<$<NOT:$<CXX_COMPILER_ID:MSVC>>:
-fno-strict-aliasing
$<$<CXX_COMPILER_ID:MSVC>:
/wd4577
/wd4702
/wd26440 # CppCoreCheck - GTest
/wd26446 # CppCoreCheck - prefer gsl::at()
>
$<$<CXX_COMPILER_ID:Clang>:
-Weverything
-Wfloat-equal
-Wno-c++98-compat
-Wno-c++98-compat-pedantic
-Wno-missing-prototypes
-Wno-unknown-attributes
$<$<EQUAL:${GSL_CXX_STANDARD},14>:
$<$<VERSION_EQUAL:$<CXX_COMPILER_VERSION>,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
-Wno-missing-braces
-Wno-unknown-attributes
-Wnon-virtual-dtor
-Wold-style-cast
-Woverloaded-virtual
-Wpedantic
-Wshadow
-Wsign-conversion
>
)
# set definitions for tests
target_compile_definitions(gsl_tests_config_noexcept INTERFACE
GSL_TERMINATE_ON_CONTRACT_VIOLATION
)
function(add_gsl_test_noexcept name)
add_executable(${name} ${name}.cpp)
target_link_libraries(${name}
GSL
gsl_tests_config_noexcept
-Wfloat-equal
$<$<OR:$<CXX_COMPILER_ID:Clang>,$<CXX_COMPILER_ID:AppleClang>>:
-Weverything
-Wno-c++98-compat
-Wno-c++98-compat-pedantic
-Wno-missing-prototypes
-Wno-unknown-attributes
-Wno-weak-vtables
-Wno-poison-system-directories
>
$<$<CXX_COMPILER_ID:GNU>:
-Wdouble-promotion # float implicit to double
-Wlogical-op # suspicious uses of logical operators
-Wuseless-cast # casting to its own type
$<$<NOT:$<VERSION_LESS:$<CXX_COMPILER_VERSION>,6>>:
-Wduplicated-cond # duplicated if-else conditions
-Wmisleading-indentation
-Wnull-dereference
>
$<$<NOT:$<VERSION_LESS:$<CXX_COMPILER_VERSION>,7>>:
-Wduplicated-branches # identical if-else branches
>
$<$<NOT:$<VERSION_LESS:$<CXX_COMPILER_VERSION>,8>>:
-Wcast-align=strict # increase alignment (i.e. char* to int*)
>
>
)
add_test(
${name}
${name}
)
# group all tests under GSL_tests_noexcept
set_property(TARGET ${name} PROPERTY FOLDER "GSL_tests_noexcept")
endfunction()
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_gsl_test_noexcept(no_exception_throw_tests)
add_gsl_test_noexcept(no_exception_ensure_tests)
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)
+14
View File
@@ -0,0 +1,14 @@
cmake_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 ""
)
+57 -54
View File
@@ -14,30 +14,22 @@
//
///////////////////////////////////////////////////////////////////////////////
#ifdef _MSC_VER
// blanket turn off warnings from CppCoreCheck from catch
// so people aren't annoyed by them when running the tool.
#pragma warning(disable : 26440 26426) // from catch
#endif
#include <array> // for array
#include <cstddef> // for size_t
#include <gsl/algorithm> // for copy
#include <gsl/span> // for span
#include <gtest/gtest.h>
#include <catch/catch.hpp> // for AssertionHandler, StringRef, CHECK, CHE...
#include "deathTestCommon.h"
#include <gsl/gsl_algorithm> // for copy
#include <gsl/span> // for span
#include <array> // for array
#include <cstddef> // for size_t
namespace gsl {
namespace gsl
{
struct fail_fast;
} // namespace gsl
} // namespace gsl
using namespace std;
using namespace gsl;
GSL_SUPPRESS(bounds.4) // NO-FORMAT: attribute
GSL_SUPPRESS(bounds.2) // NO-FORMAT: attribute
TEST_CASE("same_type")
TEST(algorithm_tests, same_type)
{
// dynamic source and destination span
{
@@ -50,9 +42,10 @@ TEST_CASE("same_type")
copy(src_span, dst_span);
copy(src_span, dst_span.subspan(src_span.size()));
for (std::size_t i = 0; i < src.size(); ++i) {
CHECK(dst[i] == src[i]);
CHECK(dst[i + src.size()] == src[i]);
for (std::size_t i = 0; i < src.size(); ++i)
{
EXPECT_TRUE(dst[i] == src[i]);
EXPECT_TRUE(dst[i + src.size()] == src[i]);
}
}
@@ -67,9 +60,10 @@ TEST_CASE("same_type")
copy(src_span, dst_span);
copy(src_span, dst_span.subspan(src_span.size()));
for (std::size_t i = 0; i < src.size(); ++i) {
CHECK(dst[i] == src[i]);
CHECK(dst[i + src.size()] == src[i]);
for (std::size_t i = 0; i < src.size(); ++i)
{
EXPECT_TRUE(dst[i] == src[i]);
EXPECT_TRUE(dst[i + src.size()] == src[i]);
}
}
@@ -78,15 +72,16 @@ TEST_CASE("same_type")
std::array<int, 5> src{1, 2, 3, 4, 5};
std::array<int, 10> dst{};
const span<int> src_span(src);
const span<int, 10> dst_span(dst);
const gsl::span<int> src_span(src);
const gsl::span<int, 10> 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) {
CHECK(dst[i] == src[i]);
CHECK(dst[i + src.size()] == src[i]);
for (std::size_t i = 0; i < src.size(); ++i)
{
EXPECT_TRUE(dst[i] == src[i]);
EXPECT_TRUE(dst[i + src.size()] == src[i]);
}
}
@@ -101,17 +96,15 @@ TEST_CASE("same_type")
copy(src_span, dst_span);
copy(src_span, dst_span.subspan(src_span.size()));
for (std::size_t i = 0; i < src.size(); ++i) {
CHECK(dst[i] == src[i]);
CHECK(dst[i + src.size()] == src[i]);
for (std::size_t i = 0; i < src.size(); ++i)
{
EXPECT_TRUE(dst[i] == src[i]);
EXPECT_TRUE(dst[i + src.size()] == src[i]);
}
}
}
GSL_SUPPRESS(bounds.4) // NO-FORMAT: attribute
GSL_SUPPRESS(bounds.2) // NO-FORMAT: attribute
TEST_CASE("compatible_type")
TEST(algorithm_tests, compatible_type)
{
// dynamic source and destination span
{
@@ -124,9 +117,10 @@ TEST_CASE("compatible_type")
copy(src_span, dst_span);
copy(src_span, dst_span.subspan(src_span.size()));
for (std::size_t i = 0; i < src.size(); ++i) {
CHECK(dst[i] == src[i]);
CHECK(dst[i + src.size()] == src[i]);
for (std::size_t i = 0; i < src.size(); ++i)
{
EXPECT_TRUE(dst[i] == src[i]);
EXPECT_TRUE(dst[i + src.size()] == src[i]);
}
}
@@ -141,9 +135,10 @@ TEST_CASE("compatible_type")
copy(src_span, dst_span);
copy(src_span, dst_span.subspan(src_span.size()));
for (std::size_t i = 0; i < src.size(); ++i) {
CHECK(dst[i] == src[i]);
CHECK(dst[i + src.size()] == src[i]);
for (std::size_t i = 0; i < src.size(); ++i)
{
EXPECT_TRUE(dst[i] == src[i]);
EXPECT_TRUE(dst[i + src.size()] == src[i]);
}
}
@@ -158,9 +153,10 @@ TEST_CASE("compatible_type")
copy(src_span, dst_span);
copy(src_span, dst_span.subspan(src_span.size()));
for (std::size_t i = 0; i < src.size(); ++i) {
CHECK(dst[i] == src[i]);
CHECK(dst[i + src.size()] == src[i]);
for (std::size_t i = 0; i < src.size(); ++i)
{
EXPECT_TRUE(dst[i] == src[i]);
EXPECT_TRUE(dst[i + src.size()] == src[i]);
}
}
@@ -175,15 +171,16 @@ TEST_CASE("compatible_type")
copy(src_span, dst_span);
copy(src_span, dst_span.subspan(src_span.size()));
for (std::size_t i = 0; i < src.size(); ++i) {
CHECK(dst[i] == src[i]);
CHECK(dst[i + src.size()] == src[i]);
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_CASE("incompatible_type")
TEST(algorithm_tests, incompatible_type)
{
std::array<int, 4> src{1, 2, 3, 4};
std::array<int*, 12> dst{};
@@ -191,7 +188,7 @@ TEST_CASE("incompatible_type")
span<int> src_span_dyn(src);
span<int, 4> src_span_static(src);
span<int*> dst_span_dyn(dst);
span<int*, 4> dst_span_static(dst);
span<int*, 4> dst_span_static(gsl::make_span(dst));
// every line should produce a compilation error
copy(src_span_dyn, dst_span_dyn);
@@ -201,8 +198,14 @@ TEST_CASE("incompatible_type")
}
#endif
TEST_CASE("small_destination_span")
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<int, 12> src{1, 2, 3, 4};
std::array<int, 4> dst{};
@@ -211,9 +214,9 @@ TEST_CASE("small_destination_span")
const span<int> dst_span_dyn(dst);
const span<int, 4> dst_span_static(dst);
CHECK_THROWS_AS(copy(src_span_dyn, dst_span_dyn), fail_fast);
CHECK_THROWS_AS(copy(src_span_dyn, dst_span_static), fail_fast);
CHECK_THROWS_AS(copy(src_span_static, dst_span_dyn), fail_fast);
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);
+26 -18
View File
@@ -14,39 +14,47 @@
//
///////////////////////////////////////////////////////////////////////////////
#ifdef _MSC_VER
// blanket turn off warnings from CppCoreCheck from catch
// so people aren't annoyed by them when running the tool.
#pragma warning(disable : 26440 26426) // from catch
#endif
#include <catch/catch.hpp> // for AssertionHandler, StringRef, CHECK, CHECK...
#include <gsl/gsl_assert> // for fail_fast (ptr only), Ensures, Expects
#include "deathTestCommon.h"
#include <gsl/assert> // for Ensures, Expects
#include <gtest/gtest.h>
using namespace gsl;
namespace
{
int f(int i)
{
Expects(i > 0 && i < 10);
return i;
}
TEST_CASE("expects")
{
CHECK(f(2) == 2);
CHECK_THROWS_AS(f(10), fail_fast);
}
int g(int i)
{
i++;
Ensures(i > 0 && i < 10);
return i;
}
} // namespace
TEST_CASE("ensures")
TEST(assertion_tests, expects)
{
CHECK(g(2) == 3);
CHECK_THROWS_AS(g(9), fail_fast);
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));
}
+99 -61
View File
@@ -14,111 +14,150 @@
//
///////////////////////////////////////////////////////////////////////////////
#ifdef _MSC_VER
// blanket turn off warnings from CppCoreCheck from catch
// so people aren't annoyed by them when running the tool.
#pragma warning(disable : 26440 26426) // from catch
#endif
#include <gtest/gtest.h>
#include <catch/catch.hpp> // for AssertionHandler, StringRef, CHECK_THROW...
#include <gsl/gsl_util> // for at
#include <gsl/util> // for at
#include <array> // for array
#include <cstddef> // for size_t
#include <exception> // for terminate
#include <initializer_list> // for initializer_list
#include <vector> // for vector
#if defined(__cplusplus) && __cplusplus >= 202002L
#include <span>
#endif // __cplusplus >= 202002L
#include "deathTestCommon.h"
namespace gsl {
struct fail_fast;
} // namespace gsl
using gsl::fail_fast;
GSL_SUPPRESS(bounds.4) // NO-FORMAT: attribute
GSL_SUPPRESS(bounds.2) // NO-FORMAT: attribute
TEST_CASE("static_array")
TEST(at_tests, static_array)
{
int a[4] = {1, 2, 3, 4};
const int(&c_a)[4] = a;
const int (&c_a)[4] = a;
for (int i = 0; i < 4; ++i) {
CHECK(&gsl::at(a, i) == &a[i]);
CHECK(&gsl::at(c_a, i) == &a[i]);
for (int i = 0; i < 4; ++i)
{
EXPECT_TRUE(&gsl::at(a, i) == &a[i]);
EXPECT_TRUE(&gsl::at(c_a, i) == &a[i]);
}
CHECK_THROWS_AS(gsl::at(a, -1), fail_fast);
CHECK_THROWS_AS(gsl::at(a, 4), fail_fast);
CHECK_THROWS_AS(gsl::at(c_a, -1), fail_fast);
CHECK_THROWS_AS(gsl::at(c_a, 4), fail_fast);
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);
}
GSL_SUPPRESS(bounds.4) // NO-FORMAT: attribute
GSL_SUPPRESS(bounds.2) // NO-FORMAT: attribute
TEST_CASE("std_array")
TEST(at_tests, std_array)
{
std::array<int, 4> a = {1, 2, 3, 4};
const std::array<int, 4>& c_a = a;
for (int i = 0; i < 4; ++i) {
CHECK(&gsl::at(a, i) == &a[static_cast<std::size_t>(i)]);
CHECK(&gsl::at(c_a, i) == &a[static_cast<std::size_t>(i)]);
for (int i = 0; i < 4; ++i)
{
EXPECT_TRUE(&gsl::at(a, i) == &a[static_cast<std::size_t>(i)]);
EXPECT_TRUE(&gsl::at(c_a, i) == &a[static_cast<std::size_t>(i)]);
}
CHECK_THROWS_AS(gsl::at(a, -1), fail_fast);
CHECK_THROWS_AS(gsl::at(a, 4), fail_fast);
CHECK_THROWS_AS(gsl::at(c_a, -1), fail_fast);
CHECK_THROWS_AS(gsl::at(c_a, 4), fail_fast);
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);
}
GSL_SUPPRESS(bounds.4) // NO-FORMAT: attribute
GSL_SUPPRESS(bounds.2) // NO-FORMAT: attribute
TEST_CASE("StdVector")
TEST(at_tests, std_vector)
{
std::vector<int> a = {1, 2, 3, 4};
const std::vector<int>& c_a = a;
for (int i = 0; i < 4; ++i) {
CHECK(&gsl::at(a, i) == &a[static_cast<std::size_t>(i)]);
CHECK(&gsl::at(c_a, i) == &a[static_cast<std::size_t>(i)]);
for (int i = 0; i < 4; ++i)
{
EXPECT_TRUE(&gsl::at(a, i) == &a[static_cast<std::size_t>(i)]);
EXPECT_TRUE(&gsl::at(c_a, i) == &a[static_cast<std::size_t>(i)]);
}
CHECK_THROWS_AS(gsl::at(a, -1), fail_fast);
CHECK_THROWS_AS(gsl::at(a, 4), fail_fast);
CHECK_THROWS_AS(gsl::at(c_a, -1), fail_fast);
CHECK_THROWS_AS(gsl::at(c_a, 4), fail_fast);
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);
}
GSL_SUPPRESS(bounds.4) // NO-FORMAT: attribute
GSL_SUPPRESS(bounds.2) // NO-FORMAT: attribute
TEST_CASE("InitializerList")
TEST(at_tests, InitializerList)
{
const std::initializer_list<int> a = {1, 2, 3, 4};
for (int i = 0; i < 4; ++i) {
CHECK(gsl::at(a, i) == i + 1);
CHECK(gsl::at({1, 2, 3, 4}, i) == i + 1);
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);
}
CHECK_THROWS_AS(gsl::at(a, -1), fail_fast);
CHECK_THROWS_AS(gsl::at(a, 4), fail_fast);
CHECK_THROWS_AS(gsl::at({1, 2, 3, 4}, -1), fail_fast);
CHECK_THROWS_AS(gsl::at({1, 2, 3, 4}, 4), fail_fast);
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<int> vec{1, 2, 3, 4, 5};
std::span sp{vec};
std::vector<int> cvec{1, 2, 3, 4, 5};
std::span csp{cvec};
for (gsl::index i = 0; i < gsl::narrow_cast<gsl::index>(vec.size()); ++i)
{
EXPECT_TRUE(&gsl::at(sp, i) == &vec[gsl::narrow_cast<size_t>(i)]);
EXPECT_TRUE(&gsl::at(csp, i) == &cvec[gsl::narrow_cast<size_t>(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<gsl::index>(sp.size())), expected);
EXPECT_DEATH(gsl::at(csp, -1), expected);
EXPECT_DEATH(gsl::at(csp, gsl::narrow_cast<gsl::index>(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
GSL_SUPPRESS(bounds.4) // NO-FORMAT: attribute
GSL_SUPPRESS(bounds.2) // NO-FORMAT: attribute
GSL_SUPPRESS(con.4) // NO-FORMAT: attribute
static constexpr bool test_constexpr()
{
int a1[4] = {1, 2, 3, 4};
const int(&c_a1)[4] = a1;
const int (&c_a1)[4] = a1;
std::array<int, 4> a2 = {1, 2, 3, 4};
const std::array<int, 4>& c_a2 = a2;
for (int i = 0; i < 4; ++i) {
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:
@@ -132,4 +171,3 @@ static constexpr bool test_constexpr()
static_assert(test_constexpr(), "FAIL");
#endif
-115
View File
@@ -1,115 +0,0 @@
///////////////////////////////////////////////////////////////////////////////
//
// 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.
//
///////////////////////////////////////////////////////////////////////////////
#ifdef _MSC_VER
// blanket turn off warnings from CppCoreCheck from catch
// so people aren't annoyed by them when running the tool.
#pragma warning(disable : 26440 26426) // from catch
#endif
#include <catch/catch.hpp> // for AssertionHandler, StringRef, TEST_CASE
#include <gsl/multi_span> // for static_bounds, static_bounds_dynamic_range_t
#include <cstddef> // for ptrdiff_t, size_t
namespace gsl {
struct fail_fast;
} // namespace gsl
using namespace std;
using namespace gsl;
namespace
{
void use(std::ptrdiff_t&) {}
}
GSL_SUPPRESS(type.1) // NO-FORMAT: attribute
TEST_CASE("basic_bounds")
{
for (auto point : static_bounds<dynamic_range, 3, 4>{2}) {
for (decltype(point)::size_type j = 0;
j < static_cast<decltype(point)::size_type>(decltype(point)::rank); j++)
{
use(j);
use(point[static_cast<std::size_t>(j)]);
}
}
}
GSL_SUPPRESS(f.4) // NO-FORMAT: attribute
GSL_SUPPRESS(con.4) // NO-FORMAT: attribute
TEST_CASE("bounds_basic")
{
static_bounds<3, 4, 5> b;
const auto a = b.slice();
(void) a;
static_bounds<4, dynamic_range, 2> x{4};
x.slice().slice();
}
GSL_SUPPRESS(f.4) // NO-FORMAT: attribute
GSL_SUPPRESS(con.4) // NO-FORMAT: attribute
TEST_CASE("arrayview_iterator")
{
static_bounds<4, dynamic_range, 2> bounds{3};
const auto itr = bounds.begin();
(void) itr;
#ifdef CONFIRM_COMPILATION_ERRORS
multi_span<int, 4, dynamic_range, 2> av(nullptr, bounds);
auto itr2 = av.cbegin();
for (auto& v : av) {
v = 4;
}
fill(av.begin(), av.end(), 0);
#endif
}
GSL_SUPPRESS(con.4) // NO-FORMAT: attribute
TEST_CASE("bounds_convertible")
{
static_bounds<7, 4, 2> b1;
static_bounds<7, dynamic_range, 2> b2 = b1;
(void) b2;
#ifdef CONFIRM_COMPILATION_ERRORS
static_bounds<7, dynamic_range, 1> b4 = b2;
#endif
static_bounds<dynamic_range, dynamic_range, dynamic_range> b3 = b1;
static_bounds<7, 4, 2> b4 = b3;
(void) b4;
static_bounds<dynamic_range> b11;
static_bounds<dynamic_range> b5;
static_bounds<34> b6;
b5 = static_bounds<20>();
CHECK_THROWS_AS(b6 = b5, fail_fast);
b5 = static_bounds<34>();
b6 = b5;
CHECK(b5 == b6);
CHECK(b5.size() == b6.size());
}
#ifdef CONFIRM_COMPILATION_ERRORS
copy(src_span_static, dst_span_static);
#endif
+143 -101
View File
@@ -14,123 +14,165 @@
//
///////////////////////////////////////////////////////////////////////////////
#ifdef _MSC_VER
// blanket turn off warnings from CppCoreCheck from catch
// so people aren't annoyed by them when running the tool.
#pragma warning(disable : 26440 26426) // from catch
#endif
#include <gtest/gtest.h>
#include <catch/catch.hpp> // for AssertionHandler, StringRef, CHECK, TEST_...
#define GSL_USE_STD_BYTE 0
#include <gsl/byte> // for to_byte, to_integer, byte, operator&, ope...
#include <gsl/gsl_byte> // for to_byte, to_integer, byte, operator&, ope...
#include <type_traits>
#include <utility>
using namespace std;
using namespace gsl;
namespace
{
TEST_CASE("construction")
{
{
const byte b = static_cast<byte>(4);
CHECK(static_cast<unsigned char>(b) == 4);
}
GSL_SUPPRESS(es.49)
{
const byte b = byte(12);
CHECK(static_cast<unsigned char>(b) == 12);
}
{
const byte b = to_byte<12>();
CHECK(static_cast<unsigned char>(b) == 12);
}
{
const unsigned char uc = 12;
const byte b = to_byte(uc);
CHECK(static_cast<unsigned char>(b) == 12);
}
#if defined(__cplusplus) && (__cplusplus >= 201703L)
{
const byte b { 14 };
CHECK(static_cast<unsigned char>(b) == 14);
}
#endif
}
TEST_CASE("bitwise_operations")
{
const byte b = to_byte<0xFF>();
byte a = to_byte<0x00>();
CHECK((b | a) == to_byte<0xFF>());
CHECK(a == to_byte<0x00>());
a |= b;
CHECK(a == to_byte<0xFF>());
a = to_byte<0x01>();
CHECK((b & a) == to_byte<0x01>());
a &= b;
CHECK(a == to_byte<0x01>());
CHECK((b ^ a) == to_byte<0xFE>());
CHECK(a == to_byte<0x01>());
a ^= b;
CHECK(a == to_byte<0xFE>());
a = to_byte<0x01>();
CHECK(~a == to_byte<0xFE>());
a = to_byte<0xFF>();
CHECK((a << 4) == to_byte<0xF0>());
CHECK((a >> 4) == to_byte<0x0F>());
a <<= 4;
CHECK(a == to_byte<0xF0>());
a >>= 4;
CHECK(a == to_byte<0x0F>());
}
TEST_CASE("to_integer")
{
const byte b = to_byte<0x12>();
CHECK(0x12 == gsl::to_integer<char>(b));
CHECK(0x12 == gsl::to_integer<short>(b));
CHECK(0x12 == gsl::to_integer<long>(b));
CHECK(0x12 == gsl::to_integer<long long>(b));
CHECK(0x12 == gsl::to_integer<unsigned char>(b));
CHECK(0x12 == gsl::to_integer<unsigned short>(b));
CHECK(0x12 == gsl::to_integer<unsigned long>(b));
CHECK(0x12 == gsl::to_integer<unsigned long long>(b));
// CHECK(0x12 == gsl::to_integer<float>(b)); // expect compile-time error
// CHECK(0x12 == gsl::to_integer<double>(b)); // expect compile-time error
}
int modify_both(gsl::byte & b, int& i)
int modify_both(gsl::byte& b, int& i)
{
i = 10;
b = to_byte<5>();
return i;
}
GSL_SUPPRESS(type.1)
TEST_CASE("aliasing")
TEST(byte_tests, construction)
{
int i{0};
const int res = modify_both(reinterpret_cast<byte&>(i), i);
CHECK(res == i);
}
{
const gsl::byte b = static_cast<gsl::byte>(4);
EXPECT_TRUE(static_cast<unsigned char>(b) == 4);
}
}
{
const gsl::byte b = gsl::byte(12);
EXPECT_TRUE(static_cast<unsigned char>(b) == 12);
}
{
const gsl::byte b = to_byte<12>();
EXPECT_TRUE(static_cast<unsigned char>(b) == 12);
}
{
const unsigned char uc = 12;
const gsl::byte b = to_byte(uc);
EXPECT_TRUE(static_cast<unsigned char>(b) == 12);
}
#if defined(__cplusplus) && (__cplusplus >= 201703L)
{
const gsl::byte b{14};
EXPECT_TRUE(static_cast<unsigned char>(b) == 14);
}
#endif
#ifdef CONFIRM_COMPILATION_ERRORS
copy(src_span_static, dst_span_static);
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<char>(b));
EXPECT_TRUE(0x12 == gsl::to_integer<short>(b));
EXPECT_TRUE(0x12 == gsl::to_integer<long>(b));
EXPECT_TRUE(0x12 == gsl::to_integer<long long>(b));
EXPECT_TRUE(0x12 == gsl::to_integer<unsigned char>(b));
EXPECT_TRUE(0x12 == gsl::to_integer<unsigned short>(b));
EXPECT_TRUE(0x12 == gsl::to_integer<unsigned long>(b));
EXPECT_TRUE(0x12 == gsl::to_integer<unsigned long long>(b));
// EXPECT_TRUE(0x12 == gsl::to_integer<float>(b)); // expect compile-time error
// EXPECT_TRUE(0x12 == gsl::to_integer<double>(b)); // expect compile-time error
}
TEST(byte_tests, aliasing)
{
int i{0};
const int res = modify_both(reinterpret_cast<gsl::byte&>(i), i);
EXPECT_TRUE(res == i);
}
#if __cplusplus >= 201703l
using std::void_t;
#else // __cplusplus >= 201703l
template <class...>
using void_t = void;
#endif // __cplusplus < 201703l
template <typename U, typename = void>
static constexpr bool LShiftCompilesFor = false;
template <typename U>
static constexpr bool LShiftCompilesFor<
U, void_t<decltype(gsl::operator<< <float>(declval<gsl::byte>(), declval<U>()))>> = true;
static_assert(!LShiftCompilesFor<float>, "!LShiftCompilesFor<float>");
template <typename U, typename = void>
static constexpr bool RShiftCompilesFor = false;
template <typename U>
static constexpr bool RShiftCompilesFor<
U, void_t<decltype(gsl::operator>> <U>(declval<gsl::byte>(), declval<U>()))>> = true;
static_assert(!RShiftCompilesFor<float>, "!RShiftCompilesFor<float>");
template <typename U, typename = void>
static constexpr bool LShiftAssignCompilesFor = false;
template <typename U>
static constexpr bool LShiftAssignCompilesFor<
U, void_t<decltype(gsl::operator<<= <U>(declval<gsl::byte&>(), declval<U>()))>> = true;
static_assert(!LShiftAssignCompilesFor<float>, "!LShiftAssignCompilesFor<float>");
template <typename U, typename = void>
static constexpr bool RShiftAssignCompilesFor = false;
template <typename U>
static constexpr bool RShiftAssignCompilesFor<
U, void_t<decltype(gsl::operator>>= <U>(declval<gsl::byte&>(), declval<U>()))>> = true;
static_assert(!RShiftAssignCompilesFor<float>, "!RShiftAssignCompilesFor<float>");
template <typename U, typename = void>
static constexpr bool ToIntegerCompilesFor = false;
template <typename U>
static constexpr bool ToIntegerCompilesFor<U, void_t<decltype(gsl::to_integer<U>(gsl::byte{}))>> =
true;
static_assert(!ToIntegerCompilesFor<float>, "!ToIntegerCompilesFor<float>");
} // namespace
+75
View File
@@ -0,0 +1,75 @@
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2025 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 <gsl/pointers> // for not_null
#include <gtest/gtest.h>
#include <type_traits> // for declval
using namespace gsl;
namespace
{
constexpr bool comparison_test(const int* ptr1, const int* ptr2)
{
const not_null<const int*> p1(ptr1);
const not_null<const int*> p1_same(ptr1);
const not_null<const int*> p2(ptr2);
// Testing operator==
const bool eq_result = (p1 == p1_same); // Should be true
const bool neq_result = (p1 != p2); // Should be true
// Testing operator<= and operator>=
const bool le_result = (p1 <= p1_same); // Should be true
const bool ge_result = (p1 >= p1_same); // Should be true
// The exact comparison results will depend on pointer ordering,
// but we can verify that the basic equality checks work as expected
return eq_result && neq_result && le_result && ge_result;
}
constexpr bool workaround_test(const int* ptr1, const int* ptr2)
{
const not_null<const int*> p1(ptr1);
const not_null<const int*> p1_same(ptr1);
const not_null<const int*> p2(ptr2);
// Using .get() to compare
const bool eq_result = (p1.get() == p1_same.get()); // Should be true
const bool neq_result = (p1.get() != p2.get()); // Should be true
return eq_result && neq_result;
}
} // namespace
constexpr int test_value1 = 1;
constexpr int test_value2 = 2;
static_assert(comparison_test(&test_value1, &test_value2),
"not_null comparison operators should be constexpr");
static_assert(workaround_test(&test_value1, &test_value2),
"not_null .get() comparison workaround should work");
TEST(notnull_constexpr_tests, TestNotNullConstexprComparison)
{
// This test simply verifies that the constexpr functions compile and run
// If we got here, it means the constexpr comparison operators are working
static const int value1 = 1;
static const int value2 = 2;
EXPECT_TRUE(comparison_test(&value1, &value2));
EXPECT_TRUE(workaround_test(&value1, &value2));
}
+11
View File
@@ -0,0 +1,11 @@
#pragma once
#include <gsl/assert>
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;
}
+684
View File
@@ -0,0 +1,684 @@
#include <gtest/gtest.h>
#include "deathTestCommon.h"
#include "gsl/dyn_array"
#include <cstdlib>
#include <exception>
#include <gsl/dyn_array>
#include <gsl/util>
#include <iostream>
#include <sstream>
#include <type_traits>
// Despite using <algorithm> and <ranges> utilities in this test, they
// are not being included directly by this file as a test to ensure
// transitive inclusion via <gsl/dyn_array>.
static_assert(sizeof(gsl::dyn_array<int>) == 2 * sizeof(void*),
"gsl::dyn_array (with the default allocator) should be 16 bytes");
#if defined(__cpp_lib_concepts) && (__cpp_lib_concepts >= 202002L)
static_assert(std::input_iterator<gsl::dyn_array<int>::iterator>,
"gsl::dyn_array should expose a valid input_iterator");
#endif /* __cpp_lib_concepts >= 202002L */
#if defined(__cpp_lib_ranges) && (__cpp_lib_ranges >= 201911L)
static_assert(std::ranges::input_range<gsl::dyn_array<int>>,
"gsl::dyn_array should be a valid input range");
#endif /* __cpp_lib_ranges >= 201911L */
TEST(dyn_array_tests, default_ctor)
{
gsl::dyn_array<char> diamondbacks;
EXPECT_TRUE(diamondbacks.empty());
EXPECT_EQ(diamondbacks.size(), 0);
EXPECT_EQ(diamondbacks.data(), nullptr);
}
TEST(dyn_array_tests, count_ctor)
{
gsl::dyn_array<char> athletics(10);
EXPECT_FALSE(athletics.empty());
EXPECT_EQ(athletics.size(), 10);
EXPECT_NE(athletics.data(), nullptr);
gsl::dyn_array<char> braves(0);
EXPECT_TRUE(braves.empty());
EXPECT_EQ(braves.size(), 0);
EXPECT_EQ(braves.data(), nullptr);
EXPECT_TRUE(std::all_of(braves.begin(), braves.end(), [](char c) { return c == char{}; }));
}
TEST(dyn_array_tests, count_value_ctor)
{
gsl::dyn_array<char> orioles(10, 'c');
EXPECT_FALSE(orioles.empty());
EXPECT_EQ(orioles.size(), 10);
EXPECT_NE(orioles.data(), nullptr);
EXPECT_TRUE(std::all_of(orioles.begin(), orioles.end(), [](char c) { return c == 'c'; }));
gsl::dyn_array<int> redsox(10, 42);
EXPECT_FALSE(redsox.empty());
EXPECT_EQ(redsox.size(), 10);
EXPECT_NE(redsox.data(), nullptr);
EXPECT_TRUE(std::all_of(redsox.begin(), redsox.end(), [](int i) { return i == 42; }));
}
TEST(dyn_array_tests, inputit_ctor)
{
std::vector<char> cubs(10, 'c');
gsl::dyn_array<char> whitesox(cubs.begin(), cubs.end());
EXPECT_FALSE(whitesox.empty());
EXPECT_EQ(whitesox.size(), cubs.size());
EXPECT_NE(whitesox.data(), nullptr);
EXPECT_TRUE(std::all_of(whitesox.begin(), whitesox.end(), [](char c) { return c == 'c'; }));
}
TEST(dyn_array_tests, copy_ctor)
{
gsl::dyn_array<char> reds(10, 'c');
gsl::dyn_array<char> guardians(reds);
EXPECT_FALSE(guardians.empty());
EXPECT_EQ(guardians.size(), reds.size());
EXPECT_NE(guardians.data(), nullptr);
EXPECT_TRUE(std::all_of(guardians.begin(), guardians.end(), [](char c) { return c == 'c'; }));
}
TEST(dyn_array_tests, access_operator)
{
gsl::dyn_array<char> rockies(10, 'c');
using ST = typename decltype(rockies)::size_type;
for (int i = 0; i < gsl::narrow<int>(rockies.size()); i++)
EXPECT_EQ(rockies[gsl::narrow<ST>(i)], 'c');
for (int i = 0; i < gsl::narrow<int>(rockies.size()); i++) rockies[gsl::narrow<ST>(i)] = 'r';
for (int i = 0; i < gsl::narrow<int>(rockies.size()); i++)
EXPECT_EQ(rockies[gsl::narrow<ST>(i)], 'r');
gsl::dyn_array<int> tigers(10);
for (int i = 0; i < gsl::narrow<int>(tigers.size()); i++) tigers[gsl::narrow<ST>(i)] = i;
for (int i = 0; i < gsl::narrow<int>(tigers.size()); i++)
EXPECT_EQ(tigers[gsl::narrow<ST>(i)], i);
}
TEST(dyn_array_tests, iterators)
{
gsl::dyn_array<char> astros(10, 'c');
for (auto it = astros.begin(); it != astros.end(); it++) EXPECT_EQ(*it, 'c');
for (auto it = astros.begin(); it != astros.end(); it++) *it = 'r';
for (auto it = astros.begin(); it != astros.end(); it++) EXPECT_EQ(*it, 'r');
EXPECT_TRUE(std::all_of(astros.begin(), astros.end(), [](char c) { return c == 'r'; }));
gsl::dyn_array<char> royals(10, 'c');
for (auto it = royals.begin(); it != royals.end(); ++it) EXPECT_EQ(*it, 'c');
for (auto it = royals.begin(); it != royals.end(); ++it) *it = 'r';
for (auto it = royals.begin(); it != royals.end(); ++it) EXPECT_EQ(*it, 'r');
EXPECT_TRUE(std::all_of(royals.begin(), royals.end(), [](char c) { return c == 'r'; }));
}
TEST(dyn_array_tests, range_for)
{
gsl::dyn_array<char> angels(10, 'c');
for (auto x : angels) EXPECT_EQ(x, 'c');
for (auto& x : angels) x = 'r';
for (auto x : angels) EXPECT_EQ(x, 'r');
EXPECT_TRUE(std::all_of(angels.begin(), angels.end(), [](char c) { return c == 'r'; }));
}
TEST(dyn_array_tests, use_std_algorithms)
{
gsl::dyn_array<char> dodgers(26);
std::generate(dodgers.begin(), dodgers.end(), [i = 0]() mutable { return 'a' + i++; });
char ch = 'a';
for (auto x : dodgers) EXPECT_EQ(x, ch++);
EXPECT_EQ(std::find(dodgers.begin(), dodgers.end(), 'a'), dodgers.begin());
{
auto it = std::find(dodgers.begin(), dodgers.end(), 'c');
EXPECT_EQ(std::distance(dodgers.begin(), it), 'c' - 'a');
EXPECT_EQ(std::distance(it, dodgers.begin()), 'a' - 'c');
}
{
auto it = std::lower_bound(dodgers.begin(), dodgers.end(), 'j');
EXPECT_EQ(*it, 'j');
EXPECT_EQ(std::distance(dodgers.begin(), it), 'j' - 'a');
EXPECT_EQ(std::distance(it, dodgers.begin()), 'a' - 'j');
}
EXPECT_EQ(dodgers.begin(), std::begin(dodgers));
EXPECT_EQ(dodgers.end(), std::end(dodgers));
}
#if defined(__cpp_lib_constexpr_dynamic_alloc) && (__cpp_lib_constexpr_dynamic_alloc >= 201907L)
constexpr auto default_constructed_count_dyn_array_is_constexpr()
{
gsl::dyn_array<int> values(3);
return values.size() == 3 && values[0] == 0 && values[1] == 0 && values[2] == 0;
}
TEST(dyn_array_tests, constexprness)
{
constexpr gsl::dyn_array<char> marlins;
static_assert(marlins == marlins);
static_assert(marlins.empty());
static_assert(marlins.size() == 0);
static_assert(marlins.data() == nullptr);
static_assert(marlins.begin() == marlins.end());
static_assert(std::distance(marlins.begin(), marlins.end()) == 0);
static_assert(default_constructed_count_dyn_array_is_constexpr());
}
#endif /* __cpp_lib_constexpr_dynamic_alloc >= 201907L */
#if defined(__cpp_lib_ranges) && (__cpp_lib_ranges >= 201911L)
TEST(dyn_array_tests, ranges)
{
gsl::dyn_array<char> brewers(26);
std::ranges::generate(brewers, [c = 'a']() mutable { return c++; });
char ch = 'a';
for (auto x : brewers) EXPECT_EQ(x, ch++);
EXPECT_EQ(std::ranges::find(brewers, 'a'), std::ranges::begin(brewers));
{
auto it = std::ranges::find(brewers, 'c');
EXPECT_EQ(std::ranges::distance(std::ranges::begin(brewers), it), 'c' - 'a');
EXPECT_EQ(std::ranges::distance(it, std::ranges::begin(brewers)), 'a' - 'c');
}
#if defined(__cpp_lib_containers_ranges) && (__cpp_lib_containers_ranges >= 202202L)
std::vector<char> twins(10, 'c');
gsl::dyn_array<char> mets(std::from_range, twins);
EXPECT_EQ(twins.size(), mets.size());
EXPECT_TRUE(std::ranges::all_of(mets, [](char c) { return c == 'c'; }));
#endif /* __cpp_lib_containers_ranges >= 202202L */
}
#endif /* __cpp_lib_ranges >= 201911L */
#if defined(__cpp_lib_constexpr_dynamic_alloc) && (__cpp_lib_constexpr_dynamic_alloc >= 201907L)
template <typename T, unsigned N>
struct ConstexprAllocator
{
using value_type = T;
T buf[N]{};
std::size_t sz{};
constexpr ConstexprAllocator() = default;
template <typename U>
constexpr ConstexprAllocator(const ConstexprAllocator<U, N>&) noexcept : buf{}, sz{}
{}
template <typename U>
struct rebind
{
using other = ConstexprAllocator<U, N>;
};
constexpr auto allocate(std::size_t n) -> value_type*
{
auto addr = &buf[sz];
sz += n;
return addr;
}
constexpr void deallocate(value_type*, std::size_t) noexcept {}
};
template <typename T1, unsigned N1, typename T2, unsigned N2>
constexpr auto operator==(const ConstexprAllocator<T1, N1>& lhs,
const ConstexprAllocator<T2, N2>& rhs) noexcept
{
return std::addressof(lhs) == std::addressof(rhs);
}
template <typename T1, unsigned N1, typename T2, unsigned N2>
constexpr auto operator!=(const ConstexprAllocator<T1, N1>& lhs,
const ConstexprAllocator<T2, N2>& rhs) noexcept
{
return !(lhs == rhs);
}
#endif /* __cpp_lib_constexpr_dynamic_alloc >= 201907L */
template <typename T>
static int AllocCounter = 0;
template <typename T>
static int DeallocCounter = 0;
struct LifetimeCounter
{
static int alive_count;
int value{};
explicit LifetimeCounter(int v = 0) : value(v) { ++alive_count; }
LifetimeCounter(const LifetimeCounter& other) : value(other.value) { ++alive_count; }
~LifetimeCounter() { --alive_count; }
};
int LifetimeCounter::alive_count = 0;
struct DefaultConstructionCounter
{
static int default_constructor_count;
static int copy_constructor_count;
int value{};
DefaultConstructionCounter() { ++default_constructor_count; }
DefaultConstructionCounter(const DefaultConstructionCounter& other) : value(other.value)
{
++copy_constructor_count;
}
static void reset()
{
default_constructor_count = 0;
copy_constructor_count = 0;
}
};
int DefaultConstructionCounter::default_constructor_count = 0;
int DefaultConstructionCounter::copy_constructor_count = 0;
struct DefaultOnlyElement
{
DefaultOnlyElement() = default;
DefaultOnlyElement(const DefaultOnlyElement&) = delete;
DefaultOnlyElement& operator=(const DefaultOnlyElement&) = delete;
DefaultOnlyElement(DefaultOnlyElement&&) = delete;
DefaultOnlyElement& operator=(DefaultOnlyElement&&) = delete;
};
struct ThrowOnCopy
{
static int alive_count;
static int copy_count;
static int throw_on_copy_index;
int value{};
explicit ThrowOnCopy(int v = 0) : value(v) { ++alive_count; }
ThrowOnCopy(const ThrowOnCopy& other) : value(other.value)
{
if (copy_count == throw_on_copy_index)
{
++copy_count;
throw 42;
}
++copy_count;
++alive_count;
}
~ThrowOnCopy() { --alive_count; }
};
int ThrowOnCopy::alive_count = 0;
int ThrowOnCopy::copy_count = 0;
int ThrowOnCopy::throw_on_copy_index = -1;
template <typename T>
class Newocator
{
public:
using value_type = T;
Newocator() = default;
template <typename U>
Newocator(const Newocator<U>&) noexcept
{}
static void init()
{
AllocCounter<Newocator<T>> = 0;
DeallocCounter<Newocator<T>> = 0;
}
static void check() { EXPECT_EQ(AllocCounter<Newocator<T>>, DeallocCounter<Newocator<T>>); }
auto allocate(std::size_t n) -> value_type*
{
AllocCounter<Newocator<T>> ++;
return static_cast<value_type*>(::operator new(n * sizeof(value_type)));
}
void deallocate(value_type* p, std::size_t) noexcept
{
DeallocCounter<Newocator<T>> ++;
::operator delete(p);
}
template <typename U>
struct rebind
{
using other = Newocator<U>;
};
};
template <typename T, typename U>
constexpr auto operator==(const Newocator<T>&, const Newocator<U>&) noexcept
{
return true;
}
template <typename T, typename U>
constexpr auto operator!=(const Newocator<T>& lhs, const Newocator<U>& rhs) noexcept
{
return !(lhs == rhs);
}
template <typename T>
class OwnershipTrackingAllocator
{
public:
using value_type = T;
OwnershipTrackingAllocator() noexcept : owner_id(next_owner_id()) { ++next_owner_id(); }
explicit OwnershipTrackingAllocator(int owner) noexcept : owner_id(owner) {}
template <typename U>
OwnershipTrackingAllocator(const OwnershipTrackingAllocator<U>& other) noexcept
: owner_id(other.owner())
{}
auto allocate(std::size_t count) -> value_type*
{
static_assert(alignof(value_type) <= alignof(int),
"test allocator only supports types with int-or-smaller alignment");
auto raw =
static_cast<unsigned char*>(::operator new(sizeof(int) + count * sizeof(value_type)));
*reinterpret_cast<int*>(raw) = owner_id;
++allocation_count();
return reinterpret_cast<value_type*>(raw + sizeof(int));
}
void deallocate(value_type* pointer, std::size_t) noexcept
{
auto raw = reinterpret_cast<unsigned char*>(pointer) - sizeof(int);
if (*reinterpret_cast<int*>(raw) != owner_id) { ++mismatched_deallocation_count(); }
++deallocation_count();
::operator delete(raw);
}
auto owner() const noexcept { return owner_id; }
static void reset()
{
next_owner_id() = 1;
allocation_count() = 0;
deallocation_count() = 0;
mismatched_deallocation_count() = 0;
}
static auto mismatched_deallocations() { return mismatched_deallocation_count(); }
private:
int owner_id;
static auto next_owner_id() -> int&
{
static int value = 1;
return value;
}
static auto allocation_count() -> int&
{
static int value = 0;
return value;
}
static auto deallocation_count() -> int&
{
static int value = 0;
return value;
}
static auto mismatched_deallocation_count() -> int&
{
static int value = 0;
return value;
}
};
template <typename T, typename U>
constexpr auto operator==(const OwnershipTrackingAllocator<T>& lhs,
const OwnershipTrackingAllocator<U>& rhs) noexcept
{
return lhs.owner() == rhs.owner();
}
template <typename T, typename U>
constexpr auto operator!=(const OwnershipTrackingAllocator<T>& lhs,
const OwnershipTrackingAllocator<U>& rhs) noexcept
{
return !(lhs == rhs);
}
TEST(dyn_array_tests, custom_allocator_models_allocator)
{
using traits = std::allocator_traits<Newocator<char>>;
using ptr = traits::pointer;
static_assert(std::is_same<traits::value_type, char>::value, "allocator trait type mismatch");
static_assert(std::is_same<ptr, char*>::value, "allocator trait type mismatch");
Newocator<char> alloc;
auto p = traits::allocate(alloc, 1);
traits::deallocate(alloc, p, 1);
#if defined(__cpp_lib_constexpr_dynamic_alloc) && (__cpp_lib_constexpr_dynamic_alloc >= 201907L)
using constexpr_traits = std::allocator_traits<ConstexprAllocator<char, 10>>;
static_assert(std::is_same<constexpr_traits::value_type, char>::value,
"allocator trait type mismatch");
#endif /* __cpp_lib_constexpr_dynamic_alloc >= 201907L */
}
TEST(dyn_array_tests, custom_allocator)
{
#if defined(__cpp_lib_constexpr_dynamic_alloc) && (__cpp_lib_constexpr_dynamic_alloc >= 201907L)
static constexpr gsl::dyn_array<char, ConstexprAllocator<char, 10>> mets(10, 'c');
static_assert(mets.size() == 10);
static_assert(mets[0] == 'c');
static_assert(std::all_of(std::begin(mets), std::end(mets), [](char c) { return c == 'c'; }));
#endif /* __cpp_lib_constexpr_dynamic_alloc >= 201907L */
Newocator<char>::init();
{
gsl::dyn_array<char, Newocator<char>> yankees(10, 'c');
EXPECT_EQ(yankees.size(), 10);
EXPECT_TRUE(
std::all_of(std::begin(yankees), std::end(yankees), [](char c) { return c == 'c'; }));
yankees[0] = 'a';
yankees[1] = 'b';
EXPECT_EQ(yankees[0], 'a');
EXPECT_EQ(yankees[1], 'b');
EXPECT_EQ(yankees[2], 'c');
yankees.get_allocator().deallocate(yankees.get_allocator().allocate(1), 1);
}
Newocator<char>::check();
}
TEST(dyn_array_tests, non_trivial_elements_are_destroyed)
{
LifetimeCounter::alive_count = 0;
{
gsl::dyn_array<LifetimeCounter> values(5, LifetimeCounter{7});
EXPECT_EQ(values.size(), 5);
EXPECT_EQ(LifetimeCounter::alive_count, 5);
}
EXPECT_EQ(LifetimeCounter::alive_count, 0);
}
TEST(dyn_array_tests, count_constructor_default_constructs_each_element)
{
DefaultConstructionCounter::reset();
{
gsl::dyn_array<DefaultConstructionCounter> values(4);
EXPECT_EQ(values.size(), 4);
}
EXPECT_EQ(DefaultConstructionCounter::default_constructor_count, 4);
EXPECT_EQ(DefaultConstructionCounter::copy_constructor_count, 0);
}
#ifdef GSL_DYN_ARRAY_COMPILE_FAILURE_TESTS
TEST(dyn_array_compile_failure_tests, count_constructor_accepts_default_constructible_only_elements)
{
gsl::dyn_array<DefaultOnlyElement> values(4);
EXPECT_EQ(values.size(), 4);
}
#endif /* GSL_DYN_ARRAY_COMPILE_FAILURE_TESTS */
TEST(dyn_array_tests, failed_element_construction_rolls_back)
{
ThrowOnCopy::alive_count = 0;
ThrowOnCopy::copy_count = 0;
ThrowOnCopy::throw_on_copy_index = 2;
EXPECT_THROW((gsl::dyn_array<ThrowOnCopy>(5, ThrowOnCopy{1})), int);
EXPECT_EQ(ThrowOnCopy::alive_count, 0);
ThrowOnCopy::throw_on_copy_index = -1;
}
TEST(dyn_array_tests, init_list)
{
gsl::dyn_array<char> phillies = {'a', 'b', 'c'};
EXPECT_EQ(phillies.size(), 3);
EXPECT_EQ(phillies[0], 'a');
EXPECT_EQ(phillies[1], 'b');
EXPECT_EQ(phillies[2], 'c');
}
TEST(dyn_array_tests, const_operations)
{
const gsl::dyn_array<char> pirates{'a', 'b', 'c', 'd'};
EXPECT_EQ(pirates.size(), 4);
EXPECT_EQ(pirates[0], 'a');
}
TEST(dyn_array_tests, reverse_iterator)
{
const gsl::dyn_array<char> padres{'a', 'b', 'c'};
auto it = std::rbegin(padres);
EXPECT_EQ(*it++, 'c');
EXPECT_EQ(*it++, 'b');
EXPECT_EQ(*it++, 'a');
}
TEST(dyn_array_tests, random_access_iterator_arithmetic)
{
gsl::dyn_array<char> bluejays{'a', 'b', 'c', 'd'};
auto first = bluejays.begin();
auto third = first + 2;
EXPECT_EQ(*third, 'c');
EXPECT_EQ(third - first, 2);
EXPECT_EQ(*(third - 1), 'b');
EXPECT_EQ(*std::prev(third), 'b');
}
TEST(dyn_array_tests, random_access_iterator_arithmetic_accepts_negative_offsets)
{
gsl::dyn_array<char> bluejays{'a', 'b', 'c', 'd'};
auto third = bluejays.begin() + 2;
char previous{};
char next{};
EXPECT_NO_THROW(previous = *(third + -1));
EXPECT_EQ(previous, 'b');
EXPECT_NO_THROW(next = *(third - -1));
EXPECT_EQ(next, 'd');
}
TEST(dyn_array_tests, input_iterator_constructor)
{
std::istringstream stream{"n a t s"};
std::istream_iterator<char> first{stream};
const std::istream_iterator<char> last{};
gsl::dyn_array<char> nationals(first, last);
ASSERT_EQ(nationals.size(), 4);
EXPECT_EQ(nationals[0], 'n');
EXPECT_EQ(nationals[1], 'a');
EXPECT_EQ(nationals[2], 't');
EXPECT_EQ(nationals[3], 's');
}
TEST(dyn_array_tests, contract_violations)
{
const auto terminateHandler = std::set_terminate([] {
std::cerr << "Expected Death. dyn_array_contract_violations";
std::abort();
});
const auto expected = GetExpectedDeathString(terminateHandler);
gsl::dyn_array<char> values(3, 'v');
gsl::dyn_array<char> other(3, 'o');
EXPECT_DEATH(values[values.size()], expected);
EXPECT_DEATH((void) *values.end(), expected);
EXPECT_DEATH(++values.end(), expected);
EXPECT_DEATH(--values.begin(), expected);
EXPECT_DEATH((void) (values.begin() == other.begin()), expected);
}
#ifdef _MSC_VER
TEST(dyn_array_tests, unchecked_iterators)
{
gsl::dyn_array<char> values;
const gsl::dyn_array<char> const_values(3, 'v');
EXPECT_TRUE((std::is_same<decltype(const_values._Unchecked_begin()), const char*>::value));
EXPECT_TRUE((std::is_same<decltype(const_values._Unchecked_end()), const char*>::value));
std::size_t count = 0;
for (const auto value : const_values)
{
EXPECT_EQ(value, 'v');
++count;
}
EXPECT_EQ(count, const_values.size());
EXPECT_EQ(values._Unchecked_begin(), nullptr);
EXPECT_EQ(values._Unchecked_end(), nullptr);
}
#endif /* _MSC_VER */
TEST(DynArrayTests, TypeConsistency)
{
static_assert(std::is_same<gsl::dyn_array<int>::value_type, int>::value, "Value type mismatch");
static_assert(std::is_same<gsl::dyn_array<int>::reference, int&>::value,
"Reference type mismatch");
static_assert(std::is_same<gsl::dyn_array<int>::const_reference, const int&>::value,
"Const reference type mismatch");
static_assert(std::is_same<gsl::dyn_array<int>::iterator::value_type, int>::value,
"Iterator value type mismatch");
static_assert(std::is_same<gsl::dyn_array<int>::iterator::reference, int&>::value,
"Iterator reference type mismatch");
static_assert(std::is_same<gsl::dyn_array<int>::iterator::const_reference, const int&>::value,
"Iterator const reference type mismatch");
static_assert(std::is_same<gsl::dyn_array<int>::size_type, std::size_t>::value,
"Size type mismatch");
static_assert(std::is_same<gsl::dyn_array<int>::difference_type, std::ptrdiff_t>::value,
"Difference type mismatch");
}
#if defined(__cpp_deduction_guides) && (__cpp_deduction_guides >= 201703L)
TEST(dyn_array_tests, deduction_guides)
{
std::vector<char> giants{10};
#if defined(__cpp_lib_containers_ranges) && (__cpp_lib_containers_ranges >= 202202L)
gsl::dyn_array mariners(std::from_range, giants);
#endif /* __cpp_lib_containers_ranges >= 202202L */
gsl::dyn_array cardinals(std::begin(giants), std::end(giants));
}
#endif /* __cpp_deduction_guides >= 201703L */
File diff suppressed because it is too large Load Diff
+13 -11
View File
@@ -14,25 +14,24 @@
//
///////////////////////////////////////////////////////////////////////////////
#include <cstdlib> // for std::exit
#include <gsl/span> // for span
#include <chrono>
#include <cstdlib> // for std::exit
#include <gsl/span> // for span
#include <iostream>
#include <thread>
int operator_subscript_no_throw() noexcept
{
int arr[10];
const gsl::span<int> sp { arr };
int arr[10];
const gsl::span<int> sp{arr};
return sp[11];
}
void test_terminate()
{
std::exit(0);
}
[[noreturn]] void test_terminate() { std::exit(0); }
void setup_termination_handler() noexcept
{
#if defined(_MSC_VER)
#if defined(GSL_MSVC_USE_STL_NOEXCEPTION_WORKAROUND)
auto& handler = gsl::details::get_terminate_handler();
handler = &test_terminate;
@@ -44,9 +43,12 @@ void setup_termination_handler() noexcept
#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;
-52
View File
@@ -1,52 +0,0 @@
///////////////////////////////////////////////////////////////////////////////
//
// 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 <cstdlib> // for std::exit
#include <gsl/gsl_util> // for narrow
#include <gsl/gsl_assert> // for get_terminate
int narrow_no_throw()
{
const long long bigNumber = 0x0fffffffffffffff;
return gsl::narrow<int>(bigNumber);
}
void test_terminate()
{
std::exit(0);
}
void setup_termination_handler() noexcept
{
#if defined(_MSC_VER)
auto& handler = gsl::details::get_terminate_handler();
handler = &test_terminate;
#else
std::set_terminate(test_terminate);
#endif
}
int main()
{
setup_termination_handler();
narrow_no_throw();
return -1;
}
+425 -167
View File
@@ -14,33 +14,29 @@
//
///////////////////////////////////////////////////////////////////////////////
#ifdef _MSC_VER
// blanket turn off warnings from CppCoreCheck from catch
// so people aren't annoyed by them when running the tool.
#pragma warning(disable : 26440 26426) // from catch
#include <gtest/gtest.h>
// Fix VS2015 build breaks in Release
#pragma warning(disable : 4702) // unreachable code
#endif
#include <gsl/pointers> // for not_null, operator<, operator<=, operator>
#include <catch/catch.hpp> // for AssertionHandler, StringRef, CHECK, TEST_...
#include <gsl/pointers> // for not_null, operator<, operator<=, operator>
#include <algorithm> // for addressof
#include <memory> // for shared_ptr, make_shared, operator<, opera...
#include <sstream> // for operator<<, ostringstream, basic_ostream:...
#include <stdint.h> // for uint16_t
#include <string> // for basic_string, operator==, string, operator<<
#include <typeinfo> // for type_info
namespace gsl
{
struct fail_fast;
} // namespace gsl
#include <algorithm> // for addressof
#include <cstdint> // for uint16_t
#include <memory> // for shared_ptr, make_shared, operator<, opera...
#include <sstream> // for operator<<, ostringstream, basic_ostream:...
#include <string> // for basic_string, operator==, string, operator<<
#include <type_traits> // for declval
#include <typeinfo> // for type_info
#include <variant> // for variant, monostate, get
#include "deathTestCommon.h"
using namespace gsl;
#if __cplusplus >= 201703l
using std::void_t;
#else // __cplusplus >= 201703l
template <class...>
using void_t = void;
#endif // __cplusplus < 201703l
struct MyBase
{
};
@@ -65,7 +61,7 @@ template <typename T>
struct CustomPtr
{
CustomPtr(T* p) : p_(p) {}
operator T*() { return p_; }
operator T*() const { return p_; }
bool operator!=(std::nullptr_t) const { return p_ != nullptr; }
T* p_ = nullptr;
};
@@ -73,7 +69,7 @@ struct CustomPtr
template <typename T, typename U>
std::string operator==(CustomPtr<T> const& lhs, CustomPtr<U> const& rhs)
{
GSL_SUPPRESS(type.1) // NO-FORMAT: attribute
GSL_SUPPRESS(type.1)
return reinterpret_cast<const void*>(lhs.p_) == reinterpret_cast<const void*>(rhs.p_) ? "true"
: "false";
}
@@ -81,7 +77,7 @@ std::string operator==(CustomPtr<T> const& lhs, CustomPtr<U> const& rhs)
template <typename T, typename U>
std::string operator!=(CustomPtr<T> const& lhs, CustomPtr<U> const& rhs)
{
GSL_SUPPRESS(type.1) // NO-FORMAT: attribute
GSL_SUPPRESS(type.1)
return reinterpret_cast<const void*>(lhs.p_) != reinterpret_cast<const void*>(rhs.p_) ? "true"
: "false";
}
@@ -89,7 +85,7 @@ std::string operator!=(CustomPtr<T> const& lhs, CustomPtr<U> const& rhs)
template <typename T, typename U>
std::string operator<(CustomPtr<T> const& lhs, CustomPtr<U> const& rhs)
{
GSL_SUPPRESS(type.1) // NO-FORMAT: attribute
GSL_SUPPRESS(type.1)
return reinterpret_cast<const void*>(lhs.p_) < reinterpret_cast<const void*>(rhs.p_) ? "true"
: "false";
}
@@ -97,7 +93,7 @@ std::string operator<(CustomPtr<T> const& lhs, CustomPtr<U> const& rhs)
template <typename T, typename U>
std::string operator>(CustomPtr<T> const& lhs, CustomPtr<U> const& rhs)
{
GSL_SUPPRESS(type.1) // NO-FORMAT: attribute
GSL_SUPPRESS(type.1)
return reinterpret_cast<const void*>(lhs.p_) > reinterpret_cast<const void*>(rhs.p_) ? "true"
: "false";
}
@@ -105,7 +101,7 @@ std::string operator>(CustomPtr<T> const& lhs, CustomPtr<U> const& rhs)
template <typename T, typename U>
std::string operator<=(CustomPtr<T> const& lhs, CustomPtr<U> const& rhs)
{
GSL_SUPPRESS(type.1) // NO-FORMAT: attribute
GSL_SUPPRESS(type.1)
return reinterpret_cast<const void*>(lhs.p_) <= reinterpret_cast<const void*>(rhs.p_) ? "true"
: "false";
}
@@ -113,7 +109,7 @@ std::string operator<=(CustomPtr<T> const& lhs, CustomPtr<U> const& rhs)
template <typename T, typename U>
std::string operator>=(CustomPtr<T> const& lhs, CustomPtr<U> const& rhs)
{
GSL_SUPPRESS(type.1) // NO-FORMAT: attribute
GSL_SUPPRESS(type.1)
return reinterpret_cast<const void*>(lhs.p_) >= reinterpret_cast<const void*>(rhs.p_) ? "true"
: "false";
}
@@ -127,82 +123,196 @@ struct NonCopyableNonMovable
NonCopyableNonMovable& operator=(NonCopyableNonMovable&&) = delete;
};
GSL_SUPPRESS(f.4) // NO-FORMAT: attribute
bool helper(not_null<int*> p)
namespace
{
return *p == 12;
}
GSL_SUPPRESS(f.4)
bool helper(not_null<int*> p) { return *p == 12; }
GSL_SUPPRESS(f.4)
bool helper_const(not_null<const int*> p) { return *p == 12; }
GSL_SUPPRESS(f.4) // NO-FORMAT: attribute
bool helper_const(not_null<const int*> p)
{
return *p == 12;
}
int* return_pointer() { return nullptr; }
} // namespace
GSL_SUPPRESS(con.4) // NO-FORMAT: attribute
TEST_CASE("TestNotNullConstructors")
template <typename U, typename = void>
static constexpr bool CtorCompilesFor_A = false;
template <typename U>
static constexpr bool
CtorCompilesFor_A<U, void_t<decltype(gsl::not_null<void*>{std::declval<U>()})>> = true;
template <typename U, int N, typename = void>
static constexpr bool CtorCompilesFor_B = false;
template <typename U, int N>
static constexpr bool CtorCompilesFor_B<U, N, void_t<decltype(gsl::not_null<U>{N})>> = true;
template <typename U, typename = void>
static constexpr bool DefaultCtorCompilesFor = false;
template <typename U>
static constexpr bool DefaultCtorCompilesFor<U, void_t<decltype(gsl::not_null<U>{})>> = true;
template <typename U, typename = void>
static constexpr bool CtorCompilesFor_C = false;
template <typename U>
static constexpr bool
CtorCompilesFor_C<U, void_t<decltype(gsl::not_null<U*>{std::declval<std::unique_ptr<U>>()})>> =
true;
TEST(notnull_tests, TestNotNullConstructors)
{
{
static_assert(CtorCompilesFor_A<void*>, "CtorCompilesFor_A<void*>");
static_assert(!CtorCompilesFor_A<std::nullptr_t>, "!CtorCompilesFor_A<std::nullptr_t>");
static_assert(!CtorCompilesFor_B<void*, 0>, "!CtorCompilesFor_B<void*, 0>");
static_assert(!DefaultCtorCompilesFor<void*>, "!DefaultCtorCompilesFor<void*>");
static_assert(!CtorCompilesFor_C<int>, "CtorCompilesFor_C<int>");
#ifdef CONFIRM_COMPILATION_ERRORS
not_null<int*> p = nullptr; // yay...does not compile!
not_null<std::vector<char>*> p = 0; // yay...does not compile!
not_null<int*> p; // yay...does not compile!
std::unique_ptr<int> up = std::make_unique<int>(120);
not_null<int*> p = up;
// Forbid non-nullptr assignable types
not_null<std::vector<int>> f(std::vector<int>{1});
not_null<int> z(10);
not_null<std::vector<int>> y({1, 2});
// Forbid non-nullptr assignable types
not_null<std::vector<int>> f(std::vector<int>{1});
not_null<int> z(10);
not_null<std::vector<int>> y({1, 2});
#endif
int i = 12;
auto rp = RefCounted<int>(&i);
not_null<int*> p(rp);
CHECK(p.get() == &i);
}
not_null<std::shared_ptr<int>> x(
std::make_shared<int>(10)); // shared_ptr<int> is nullptr assignable
const auto terminateHandler = std::set_terminate([] {
std::cerr << "Expected Death. TestNotNullConstructors";
std::abort();
});
const auto expected = GetExpectedDeathString(terminateHandler);
#ifdef GSL_THROW_ON_CONTRACT_VIOLATION
int* pi = nullptr;
CHECK_THROWS_AS(not_null<decltype(pi)>(pi), fail_fast);
#endif
{
// from shared pointer
int i = 12;
auto rp = RefCounted<int>(&i);
not_null<int*> p(rp);
EXPECT_TRUE(p.get() == &i);
not_null<std::shared_ptr<int>> x(
std::make_shared<int>(10)); // shared_ptr<int> is nullptr assignable
int* pi = nullptr;
EXPECT_DEATH((not_null<decltype(pi)>(pi)), expected);
}
{
// from unique pointer
not_null<std::unique_ptr<int>> x(
std::make_unique<int>(10)); // unique_ptr<int> is nullptr assignable
EXPECT_DEATH((not_null<std::unique_ptr<int>>(std::unique_ptr<int>{})), expected);
}
{
// from pointer to local
int t = 42;
not_null<int*> 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<int*> 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<const int*> 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<const int*>{cp};
EXPECT_TRUE(*x == 42);
}
{
// from returned pointer
EXPECT_DEATH(helper(return_pointer()), expected);
EXPECT_DEATH(helper_const(return_pointer()), expected);
}
}
template<typename T>
GSL_SUPPRESS(con.4) // NO-FORMAT: attribute
template <typename T>
void ostream_helper(T v)
{
not_null<T*> p(&v);
{
std::ostringstream os;
std::ostringstream ref;
os << p;
ref << &v;
CHECK(os.str() == ref.str());
os << static_cast<void*>(p);
ref << static_cast<void*>(&v);
EXPECT_TRUE(os.str() == ref.str());
}
{
std::ostringstream os;
std::ostringstream ref;
os << *p;
ref << v;
CHECK(os.str() == ref.str());
EXPECT_TRUE(os.str() == ref.str());
}
}
TEST_CASE("TestNotNullostream")
TEST(notnull_tests, TestNotNullostream)
{
ostream_helper<int>(17);
ostream_helper<float>(21.5f);
ostream_helper<double>(3.4566e-7f);
ostream_helper<double>(3.4566e-7);
ostream_helper<char>('c');
ostream_helper<uint16_t>(0x0123u);
ostream_helper<const char*>("cstring");
ostream_helper<std::string>("string");
}
GSL_SUPPRESS(type.1) // NO-FORMAT: attribute
GSL_SUPPRESS(con.4) // NO-FORMAT: attribute
TEST_CASE("TestNotNullCasting")
template <typename U, typename V, typename = void>
static constexpr bool AssignmentCompilesFor = false;
template <typename U, typename V>
static constexpr bool
AssignmentCompilesFor<U, V,
void_t<decltype(std::declval<gsl::not_null<U*>&>().operator=(
std::declval<gsl::not_null<V*>&>()))>> = true;
template <typename U, typename V, typename = void>
static constexpr bool SCastCompilesFor = false;
template <typename U, typename V>
static constexpr bool
SCastCompilesFor<U, V, void_t<decltype(static_cast<U*>(std::declval<gsl::not_null<V*>&>()))>> =
true;
template <typename U, typename V, typename = void>
static constexpr bool RCastCompilesFor = false;
template <typename U, typename V>
static constexpr bool RCastCompilesFor<
U, V, void_t<decltype(reinterpret_cast<U*>(std::declval<gsl::not_null<V*>&>()))>> = true;
TEST(notnull_tests, TestNotNullCasting)
{
MyBase base;
MyDerived derived;
@@ -212,30 +322,51 @@ TEST_CASE("TestNotNullCasting")
not_null<MyDerived*> p{&derived};
not_null<MyBase*> q(&base);
q = p; // allowed with heterogeneous copy ctor
CHECK(q == p);
EXPECT_TRUE(q == p);
#ifdef CONFIRM_COMPILATION_ERRORS
q = u; // no viable conversion possible between MyBase* and Unrelated*
p = q; // not possible to implicitly convert MyBase* to MyDerived*
static_assert(AssignmentCompilesFor<MyBase, MyDerived>,
"AssignmentCompilesFor<MyBase, MyDerived>");
static_assert(!AssignmentCompilesFor<MyBase, Unrelated>,
"!AssignmentCompilesFor<MyBase, Unrelated>");
static_assert(!AssignmentCompilesFor<Unrelated, MyDerived>,
"!AssignmentCompilesFor<Unrelated, MyDerived>");
static_assert(!AssignmentCompilesFor<MyDerived, MyBase>,
"!AssignmentCompilesFor<MyDerived, MyBase>");
static_assert(SCastCompilesFor<MyDerived, MyDerived>, "SCastCompilesFor<MyDerived, MyDerived>");
static_assert(SCastCompilesFor<MyBase, MyDerived>, "SCastCompilesFor<MyBase, MyDerived>");
static_assert(!SCastCompilesFor<MyDerived, MyBase>, "!SCastCompilesFor<MyDerived, MyBase>");
static_assert(!SCastCompilesFor<Unrelated, MyDerived>,
"!SCastCompilesFor<Unrelated, MyDerived>");
static_assert(!RCastCompilesFor<MyDerived, MyDerived>,
"!SCastCompilesFor<MyDerived, MyDerived>");
static_assert(!RCastCompilesFor<Unrelated, MyDerived>,
"!SCastCompilesFor<Unrelated, MyDerived>");
not_null<Unrelated*> r = p;
not_null<Unrelated*> s = reinterpret_cast<Unrelated*>(p);
#endif
not_null<Unrelated*> t(reinterpret_cast<Unrelated*>(p.get()));
CHECK(reinterpret_cast<void*>(p.get()) == reinterpret_cast<void*>(t.get()));
EXPECT_TRUE(reinterpret_cast<void*>(p.get()) == reinterpret_cast<void*>(t.get()));
(void) static_cast<MyDerived*>(p);
(void) static_cast<MyBase*>(p);
}
TEST_CASE("TestNotNullAssignment")
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<int*> p(&i);
CHECK(helper(p));
EXPECT_TRUE(helper(p));
int* q = nullptr;
CHECK_THROWS_AS(p = not_null<int*>(q), fail_fast);
EXPECT_DEATH(p = not_null<int*>(q), expected);
}
TEST_CASE("TestNotNullRawPointerComparison")
TEST(notnull_tests, TestNotNullRawPointerComparison)
{
int ints[2] = {42, 43};
int* p1 = &ints[0];
@@ -244,34 +375,33 @@ TEST_CASE("TestNotNullRawPointerComparison")
using NotNull1 = not_null<decltype(p1)>;
using NotNull2 = not_null<decltype(p2)>;
CHECK((NotNull1(p1) == NotNull1(p1)) == true);
CHECK((NotNull1(p1) == NotNull2(p2)) == false);
EXPECT_TRUE((NotNull1(p1) == NotNull1(p1)) == true);
EXPECT_TRUE((NotNull1(p1) == NotNull2(p2)) == false);
CHECK((NotNull1(p1) != NotNull1(p1)) == false);
CHECK((NotNull1(p1) != NotNull2(p2)) == true);
EXPECT_TRUE((NotNull1(p1) != NotNull1(p1)) == false);
EXPECT_TRUE((NotNull1(p1) != NotNull2(p2)) == true);
CHECK((NotNull1(p1) < NotNull1(p1)) == false);
CHECK((NotNull1(p1) < NotNull2(p2)) == (p1 < p2));
CHECK((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));
CHECK((NotNull1(p1) > NotNull1(p1)) == false);
CHECK((NotNull1(p1) > NotNull2(p2)) == (p1 > p2));
CHECK((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));
CHECK((NotNull1(p1) <= NotNull1(p1)) == true);
CHECK((NotNull1(p1) <= NotNull2(p2)) == (p1 <= p2));
CHECK((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));
}
GSL_SUPPRESS(con.4) // NO-FORMAT: attribute
TEST_CASE("TestNotNullDereferenceOperator")
TEST(notnull_tests, TestNotNullDereferenceOperator)
{
{
auto sp1 = std::make_shared<NonCopyableNonMovable>();
using NotNullSp1 = not_null<decltype(sp1)>;
CHECK(typeid(*sp1) == typeid(*NotNullSp1(sp1)));
CHECK(std::addressof(*NotNullSp1(sp1)) == std::addressof(*sp1));
EXPECT_TRUE(typeid(*sp1) == typeid(*NotNullSp1(sp1)));
EXPECT_TRUE(std::addressof(*NotNullSp1(sp1)) == std::addressof(*sp1));
}
{
@@ -279,22 +409,22 @@ TEST_CASE("TestNotNullDereferenceOperator")
CustomPtr<int> p1(&ints[0]);
using NotNull1 = not_null<decltype(p1)>;
CHECK(typeid(*NotNull1(p1)) == typeid(*p1));
CHECK(*NotNull1(p1) == 42);
EXPECT_TRUE(typeid(*NotNull1(p1)) == typeid(*p1));
EXPECT_TRUE(*NotNull1(p1) == 42);
*NotNull1(p1) = 43;
CHECK(ints[0] == 43);
EXPECT_TRUE(ints[0] == 43);
}
{
int v = 42;
gsl::not_null<int*> p(&v);
CHECK(typeid(*p) == typeid(*(&v)));
EXPECT_TRUE(typeid(*p) == typeid(*(&v)));
*p = 43;
CHECK(v == 43);
EXPECT_TRUE(v == 43);
}
}
TEST_CASE("TestNotNullSharedPtrComparison")
TEST(notnull_tests, TestNotNullSharedPtrComparison)
{
auto sp1 = std::make_shared<int>(42);
auto sp2 = std::make_shared<const int>(43);
@@ -302,31 +432,30 @@ TEST_CASE("TestNotNullSharedPtrComparison")
using NotNullSp1 = not_null<decltype(sp1)>;
using NotNullSp2 = not_null<decltype(sp2)>;
CHECK((NotNullSp1(sp1) == NotNullSp1(sp1)) == true);
CHECK((NotNullSp1(sp1) == NotNullSp2(sp2)) == false);
EXPECT_TRUE((NotNullSp1(sp1) == NotNullSp1(sp1)) == true);
EXPECT_TRUE((NotNullSp1(sp1) == NotNullSp2(sp2)) == false);
CHECK((NotNullSp1(sp1) != NotNullSp1(sp1)) == false);
CHECK((NotNullSp1(sp1) != NotNullSp2(sp2)) == true);
EXPECT_TRUE((NotNullSp1(sp1) != NotNullSp1(sp1)) == false);
EXPECT_TRUE((NotNullSp1(sp1) != NotNullSp2(sp2)) == true);
CHECK((NotNullSp1(sp1) < NotNullSp1(sp1)) == false);
CHECK((NotNullSp1(sp1) < NotNullSp2(sp2)) == (sp1 < sp2));
CHECK((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));
CHECK((NotNullSp1(sp1) > NotNullSp1(sp1)) == false);
CHECK((NotNullSp1(sp1) > NotNullSp2(sp2)) == (sp1 > sp2));
CHECK((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));
CHECK((NotNullSp1(sp1) <= NotNullSp1(sp1)) == true);
CHECK((NotNullSp1(sp1) <= NotNullSp2(sp2)) == (sp1 <= sp2));
CHECK((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));
CHECK((NotNullSp1(sp1) >= NotNullSp1(sp1)) == true);
CHECK((NotNullSp1(sp1) >= NotNullSp2(sp2)) == (sp1 >= sp2));
CHECK((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));
}
GSL_SUPPRESS(con.4) // NO-FORMAT: attribute
TEST_CASE("TestNotNullCustomPtrComparison")
TEST(notnull_tests, TestNotNullCustomPtrComparison)
{
int ints[2] = {42, 43};
CustomPtr<int> p1(&ints[0]);
@@ -335,33 +464,44 @@ TEST_CASE("TestNotNullCustomPtrComparison")
using NotNull1 = not_null<decltype(p1)>;
using NotNull2 = not_null<decltype(p2)>;
CHECK((NotNull1(p1) == NotNull1(p1)) == "true");
CHECK((NotNull1(p1) == NotNull2(p2)) == "false");
EXPECT_TRUE((NotNull1(p1) == NotNull1(p1)) == "true");
EXPECT_TRUE((NotNull1(p1) == NotNull2(p2)) == "false");
CHECK((NotNull1(p1) != NotNull1(p1)) == "false");
CHECK((NotNull1(p1) != NotNull2(p2)) == "true");
EXPECT_TRUE((NotNull1(p1) != NotNull1(p1)) == "false");
EXPECT_TRUE((NotNull1(p1) != NotNull2(p2)) == "true");
CHECK((NotNull1(p1) < NotNull1(p1)) == "false");
CHECK((NotNull1(p1) < NotNull2(p2)) == (p1 < p2));
CHECK((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));
CHECK((NotNull1(p1) > NotNull1(p1)) == "false");
CHECK((NotNull1(p1) > NotNull2(p2)) == (p1 > p2));
CHECK((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));
CHECK((NotNull1(p1) <= NotNull1(p1)) == "true");
CHECK((NotNull1(p1) <= NotNull2(p2)) == (p1 <= p2));
CHECK((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));
CHECK((NotNull1(p1) >= NotNull1(p1)) == "true");
CHECK((NotNull1(p1) >= NotNull2(p2)) == (p1 >= p2));
CHECK((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)
GSL_SUPPRESS(con.4) // NO-FORMAT: attribute
TEST_CASE("TestNotNullConstructorTypeDeduction")
template <typename U, typename = void>
static constexpr bool TypeDeductionCtorCompilesFor = false;
template <typename U>
static constexpr bool
TypeDeductionCtorCompilesFor<U, void_t<decltype(not_null{std::declval<U>()})>> = true;
template <typename U, typename = void>
static constexpr bool TypeDeductionHelperCompilesFor = false;
template <typename U>
static constexpr bool
TypeDeductionHelperCompilesFor<U, void_t<decltype(helper(not_null{std::declval<U>()}))>> = true;
TEST(notnull_tests, TestNotNullConstructorTypeDeduction)
{
{
int i = 42;
@@ -370,7 +510,19 @@ TEST_CASE("TestNotNullConstructorTypeDeduction")
helper(not_null{&i});
helper_const(not_null{&i});
CHECK(*x == 42);
EXPECT_TRUE(*x == 42);
}
{
const int i = 42;
not_null x{&i};
static_assert(TypeDeductionHelperCompilesFor<int*>, "TypeDeductionHelperCompilesFor<int*>");
static_assert(!TypeDeductionHelperCompilesFor<const int*>,
"!TypeDeductionHelperCompilesFor<const int*>");
helper_const(not_null{&i});
EXPECT_TRUE(*x == 42);
}
{
@@ -381,15 +533,31 @@ TEST_CASE("TestNotNullConstructorTypeDeduction")
helper(not_null{p});
helper_const(not_null{p});
CHECK(*x == 42);
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};
};
CHECK_THROWS_AS(workaround_macro(), fail_fast);
EXPECT_DEATH(workaround_macro(), expected);
}
{
@@ -397,27 +565,46 @@ TEST_CASE("TestNotNullConstructorTypeDeduction")
const int* p1 = nullptr;
const not_null x{p1};
};
CHECK_THROWS_AS(workaround_macro(), fail_fast);
EXPECT_DEATH(workaround_macro(), expected);
}
{
int* p = nullptr;
CHECK_THROWS_AS(helper(not_null{p}), fail_fast);
CHECK_THROWS_AS(helper_const(not_null{p}), fail_fast);
EXPECT_DEATH(helper(not_null{p}), expected);
EXPECT_DEATH(helper_const(not_null{p}), expected);
}
#ifdef CONFIRM_COMPILATION_ERRORS
{
not_null x{nullptr};
helper(not_null{nullptr});
helper_const(not_null{nullptr});
}
static_assert(TypeDeductionCtorCompilesFor<void*>, "TypeDeductionCtorCompilesFor<void*>");
#if defined(_MSC_VER) && !defined(__clang__)
// Fails on gcc, clang, xcode, VS clang with
// "error : no type named 'type' in 'std::enable_if<false>'; 'enable_if' cannot be used to
// disable this declaration"
static_assert(!TypeDeductionCtorCompilesFor<std::nullptr_t>,
"!TypeDeductionCtorCompilesFor<std::nullptr_t>");
static_assert(!TypeDeductionHelperCompilesFor<std::nullptr_t>,
"!TypeDeductionHelperCompilesFor<std::nullptr_t>");
#endif
}
TEST(notnull_tests, TestVariantEmplace)
{
int i = 0;
std::variant<std::monostate, not_null<int*>> v;
v.emplace<not_null<int*>>(&i);
EXPECT_FALSE(v.valueless_by_exception());
EXPECT_TRUE(v.index() == 1);
EXPECT_TRUE(std::get<not_null<int*>>(v) == &i);
}
#endif // #if defined(__cplusplus) && (__cplusplus >= 201703L)
TEST_CASE("TestMakeNotNull")
template <typename U, typename = void>
static constexpr bool HelperCompilesFor = false;
template <typename U>
static constexpr bool HelperCompilesFor<U, void_t<decltype(helper(std::declval<U>()))>> = true;
TEST(notnull_tests, TestMakeNotNull)
{
{
int i = 42;
@@ -426,7 +613,18 @@ TEST_CASE("TestMakeNotNull")
helper(make_not_null(&i));
helper_const(make_not_null(&i));
CHECK(*x == 42);
EXPECT_TRUE(*x == 42);
}
{
const int i = 42;
const auto x = make_not_null(&i);
static_assert(HelperCompilesFor<gsl::not_null<int*>>,
"HelperCompilesFor<gsl::not_null<int*>>");
helper_const(make_not_null(&i));
EXPECT_TRUE(*x == 42);
}
{
@@ -437,42 +635,102 @@ TEST_CASE("TestMakeNotNull")
helper(make_not_null(p));
helper_const(make_not_null(p));
CHECK(*x == 42);
EXPECT_TRUE(*x == 42);
}
{
const int i = 42;
const int* p = &i;
const auto x = make_not_null(p);
static_assert(!HelperCompilesFor<gsl::not_null<const int*>>,
"!HelperCompilesFor<gsl::not_null<const int*>>");
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);
CHECK(*x == 42);
EXPECT_TRUE(*x == 42);
};
CHECK_THROWS_AS(workaround_macro(), fail_fast);
EXPECT_DEATH(workaround_macro(), expected);
}
{
const auto workaround_macro = []() {
const int* p1 = nullptr;
const auto x = make_not_null(p1);
CHECK(*x == 42);
EXPECT_TRUE(*x == 42);
};
CHECK_THROWS_AS(workaround_macro(), fail_fast);
EXPECT_DEATH(workaround_macro(), expected);
}
{
int* p = nullptr;
CHECK_THROWS_AS(helper(make_not_null(p)), fail_fast);
CHECK_THROWS_AS(helper_const(make_not_null(p)), fail_fast);
EXPECT_DEATH(helper(make_not_null(p)), expected);
EXPECT_DEATH(helper_const(make_not_null(p)), expected);
}
#ifdef CONFIRM_COMPILATION_ERRORS
{
CHECK_THROWS_AS(make_not_null(nullptr), fail_fast);
CHECK_THROWS_AS(helper(make_not_null(nullptr)), fail_fast);
CHECK_THROWS_AS(helper_const(make_not_null(nullptr)), fail_fast);
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
}
static_assert(std::is_nothrow_move_constructible<not_null<void *>>::value, "not_null must be no-throw move constructible");
TEST(notnull_tests, TestStdHash)
{
{
int x = 42;
int y = 99;
not_null<int*> nn{&x};
const not_null<int*> cnn{&x};
std::hash<not_null<int*>> hash_nn;
std::hash<int*> 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<const int*> nn{&x};
const not_null<const int*> cnn{&x};
std::hash<not_null<const int*>> hash_nn;
std::hash<const int*> 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));
}
{
auto x = std::make_shared<int>(42);
auto y = std::make_shared<int>(99);
not_null<std::shared_ptr<int>> nn{x};
const not_null<std::shared_ptr<int>> cnn{x};
std::hash<not_null<std::shared_ptr<int>>> hash_nn;
std::hash<std::shared_ptr<int>> hash_sharedptr;
EXPECT_TRUE(hash_nn(nn) == hash_sharedptr(x));
EXPECT_FALSE(hash_nn(nn) == hash_sharedptr(y));
EXPECT_TRUE(hash_nn(cnn) == hash_sharedptr(x));
}
}
+20 -24
View File
@@ -14,40 +14,36 @@
//
///////////////////////////////////////////////////////////////////////////////
#ifdef _MSC_VER
// blanket turn off warnings from CppCoreCheck from catch
// so people aren't annoyed by them when running the tool.
#pragma warning(disable : 26440 26426) // from catch
#endif
#include <catch/catch.hpp> // for AssertionHandler, StringRef, CHECK, TEST_...
#include <gtest/gtest.h>
#include <gsl/pointers> // for owner
#include <type_traits> // for declval
using namespace gsl;
GSL_SUPPRESS(f.23) // NO-FORMAT: attribute
GSL_SUPPRESS(f.23)
void f(int* i) { *i += 1; }
GSL_SUPPRESS(r.11) // NO-FORMAT: attribute
GSL_SUPPRESS(r.3) // NO-FORMAT: attribute // TODO: false positive
GSL_SUPPRESS(r.5) // NO-FORMAT: attribute
TEST_CASE("basic_test")
TEST(owner_tests, basic_test)
{
owner<int*> p = new int(120);
CHECK(*p == 120);
EXPECT_TRUE(*p == 120);
f(p);
CHECK(*p == 121);
EXPECT_TRUE(*p == 121);
delete p;
}
TEST_CASE("check_pointer_constraint")
{
#ifdef CONFIRM_COMPILATION_ERRORS
{
owner<int> integerTest = 10;
owner<std::shared_ptr<int>> sharedPtrTest(new int(10));
}
#endif
}
#if __cplusplus >= 201703l
using std::void_t;
#else // __cplusplus >= 201703l
template <class...>
using void_t = void;
#endif // __cplusplus < 201703l
template <typename U, typename = void>
static constexpr bool OwnerCompilesFor = false;
template <typename U>
static constexpr bool OwnerCompilesFor<U, void_t<decltype(gsl::owner<U>{})>> = true;
static_assert(OwnerCompilesFor<int*>, "OwnerCompilesFor<int*>");
static_assert(!OwnerCompilesFor<int>, "!OwnerCompilesFor<int>");
static_assert(!OwnerCompilesFor<std::shared_ptr<int>>, "!OwnerCompilesFor<std::shared_ptr<int>>");
+119
View File
@@ -0,0 +1,119 @@
#include <gtest/gtest.h>
#include <gsl/pointers>
#include <functional>
#include <memory>
#include <type_traits>
#include <utility>
#if __cplusplus >= 201703l
using std::void_t;
#else // __cplusplus >= 201703l
template <class...>
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 <typename U, typename = void>
static constexpr bool SwapCompilesFor = false;
template <typename U>
static constexpr bool
SwapCompilesFor<U, void_t<decltype(gsl::swap<U>(std::declval<gsl::not_null<U>&>(),
std::declval<gsl::not_null<U>&>()))>> = true;
TEST(pointers_test, swap)
{
// taken from gh-1129:
{
gsl::not_null<std::unique_ptr<int>> a(std::make_unique<int>(0));
gsl::not_null<std::unique_ptr<int>> b(std::make_unique<int>(1));
static_assert(noexcept(gsl::swap(a, b)),
"not null unique_ptr should be noexcept-swappable");
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<NotMoveAssignableCustomPtr>()};
gsl::not_null<NotMoveAssignableCustomPtr> c{*shared_custom_ptr};
EXPECT_TRUE(c.get() != nullptr);
}
{
gsl::strict_not_null<std::unique_ptr<int>> a{std::make_unique<int>(0)};
gsl::strict_not_null<std::unique_ptr<int>> b{std::make_unique<int>(1)};
static_assert(noexcept(gsl::swap(a, b)),
"strict not null unique_ptr should be noexcept-swappable");
EXPECT_TRUE(*a == 0);
EXPECT_TRUE(*b == 1);
gsl::swap(a, b);
EXPECT_TRUE(*a == 1);
EXPECT_TRUE(*b == 0);
}
{
gsl::not_null<std::unique_ptr<int>> a{std::make_unique<int>(0)};
gsl::strict_not_null<std::unique_ptr<int>> b{std::make_unique<int>(1)};
EXPECT_TRUE(*a == 0);
EXPECT_TRUE(*b == 1);
gsl::swap(a, b);
EXPECT_TRUE(*a == 1);
EXPECT_TRUE(*b == 0);
}
static_assert(!SwapCompilesFor<NotMoveAssignableCustomPtr>,
"!SwapCompilesFor<NotMoveAssignableCustomPtr>");
}
TEST(pointers_test, member_types)
{
static_assert(std::is_same<gsl::not_null<int*>::element_type, int*>::value,
"check member type: element_type");
}
TEST(pointers_test, hash_noexcept_compiles)
{
{
using Key = gsl::not_null<std::shared_ptr<int>>;
static_assert(noexcept(std::hash<Key>{}(std::declval<Key>())),
"gsl::not_null hash operator must be noexcept");
}
{
using Key = gsl::strict_not_null<std::shared_ptr<int>>;
static_assert(noexcept(std::hash<Key>{}(std::declval<Key>())),
"gsl::strict_not_null hash operator must be noexcept");
}
}
} // namespace
-124
View File
@@ -1,124 +0,0 @@
///////////////////////////////////////////////////////////////////////////////
//
// 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.
//
///////////////////////////////////////////////////////////////////////////////
#ifdef _MSC_VER
// blanket turn off warnings from CppCoreCheck from catch
// so people aren't annoyed by them when running the tool.
#pragma warning(disable : 26440 26426) // from catch
// Fix VS2015 build breaks in Release
#pragma warning(disable : 4702) // unreachable code
#endif
#include <catch/catch.hpp> // for AssertionHandler, StringRef, CHECK, TEST_...
#include <gsl/pointers> // for not_null, operator<, operator<=, operator>
#include <samples/gsl_transition> // for sloppy_not_null
namespace gsl
{
struct fail_fast;
} // namespace gsl
using namespace gsl;
using namespace gsl_helpers;
GSL_SUPPRESS(f.4) // NO-FORMAT: attribute
bool helper(not_null<int*> p) { return *p == 12; }
GSL_SUPPRESS(f.4) // NO-FORMAT: attribute
bool helper_const(not_null<const int*> p) { return *p == 12; }
GSL_SUPPRESS(f.4) // NO-FORMAT: attribute
bool sloppy_helper(sloppy_not_null<int*> p) { return *p == 12; }
GSL_SUPPRESS(f.4) // NO-FORMAT: attribute
bool sloppy_helper_const(sloppy_not_null<const int*> p) { return *p == 12; }
TEST_CASE("TestSloppyNotNull")
{
{
// raw ptr <-> sloppy_not_null
int x = 42;
const sloppy_not_null<int*> snn = &x;
sloppy_helper(&x);
sloppy_helper_const(&x);
CHECK(*snn == 42);
}
{
// sloppy_not_null -> sloppy_not_null
int x = 42;
sloppy_not_null<int*> snn1{&x};
const sloppy_not_null<int*> snn2{&x};
sloppy_helper(snn1);
sloppy_helper_const(snn1);
CHECK(snn1 == snn2);
}
{
// sloppy_not_null -> not_null
int x = 42;
sloppy_not_null<int*> snn{&x};
const not_null<int*> nn1 = snn;
const not_null<int*> nn2{snn};
helper(snn);
helper_const(snn);
CHECK(snn == nn1);
CHECK(snn == nn2);
}
{
// not_null -> sloppy_not_null
int x = 42;
not_null<int*> nn{&x};
const sloppy_not_null<int*> snn1{nn};
const sloppy_not_null<int*> snn2 = nn;
sloppy_helper(nn);
sloppy_helper_const(nn);
CHECK(snn1 == nn);
CHECK(snn2 == nn);
std::hash<sloppy_not_null<int*>> hash_snn;
std::hash<not_null<int*>> hash_nn;
CHECK(hash_nn(snn1) == hash_nn(nn));
CHECK(hash_snn(snn1) == hash_nn(nn));
CHECK(hash_nn(snn1) == hash_nn(snn2));
CHECK(hash_snn(snn1) == hash_snn(nn));
}
#ifdef CONFIRM_COMPILATION_ERRORS
{
sloppy_not_null<int*> p{nullptr};
}
#endif
}
static_assert(std::is_nothrow_move_constructible<sloppy_not_null<void*>>::value,
"sloppy_not_null must be no-throw move constructible");
File diff suppressed because it is too large Load Diff
+380
View File
@@ -0,0 +1,380 @@
///////////////////////////////////////////////////////////////////////////////
//
// 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 <gtest/gtest.h>
#include <gsl/span> // for span and span_ext
#include <gsl/util> // for narrow_cast, at
#include <array> // for array
#include <exception> // for terminate
#include <iostream> // for cerr
#include <vector> // 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<gsl::span<int>::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<int, 4> 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<int> s1 = make_span(arr);
static gsl::span<int> 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<int, 4> 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<const int, 4> 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<int> v = {1, 2, 3};
const std::vector<int> 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<int> vec{1, 2, 3, 4, 5};
gsl::span<int> sp{vec};
std::vector<int> cvec{1, 2, 3, 4, 5};
gsl::span<int> csp{cvec};
for (gsl::index i = 0; i < gsl::narrow_cast<gsl::index>(vec.size()); ++i)
{
EXPECT_TRUE(&gsl::at(sp, i) == &vec[gsl::narrow_cast<size_t>(i)]);
EXPECT_TRUE(&gsl::at(csp, i) == &cvec[gsl::narrow_cast<size_t>(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<gsl::index>(sp.size())), expected);
EXPECT_DEATH(gsl::at(csp, -1), expected);
EXPECT_DEATH(gsl::at(csp, gsl::narrow_cast<gsl::index>(sp.size())), expected);
}
TEST(span_ext_test, iterator_free_functions)
{
int a[] = {1, 2, 3, 4};
gsl::span<int> s{a};
EXPECT_TRUE((std::is_same<decltype(s.begin()), decltype(begin(s))>::value));
EXPECT_TRUE((std::is_same<decltype(s.end()), decltype(end(s))>::value));
EXPECT_TRUE((std::is_same<decltype(std::cbegin(s)), decltype(cbegin(s))>::value));
EXPECT_TRUE((std::is_same<decltype(std::cend(s)), decltype(cend(s))>::value));
EXPECT_TRUE((std::is_same<decltype(s.rbegin()), decltype(rbegin(s))>::value));
EXPECT_TRUE((std::is_same<decltype(s.rend()), decltype(rend(s))>::value));
EXPECT_TRUE((std::is_same<decltype(std::crbegin(s)), decltype(crbegin(s))>::value));
EXPECT_TRUE((std::is_same<decltype(std::crend(s)), decltype(crend(s))>::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<int> s{a};
EXPECT_FALSE((std::is_same<decltype(s.size()), decltype(ssize(s))>::value));
EXPECT_TRUE(s.size() == static_cast<std::size_t>(ssize(s)));
}
#ifndef GSL_KERNEL_MODE
TEST(span_ext_test, comparison_operators)
{
{
gsl::span<int> s1;
gsl::span<int> 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<int> s1 = arr;
gsl::span<int> 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<int> s1;
gsl::span<int> 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<int> s1 = arr1;
gsl::span<int> 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<int> s1 = {&arr[0], 2}; // shorter
gsl::span<int> 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<int> s1 = arr1;
gsl::span<int> 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
+847 -972
View File
File diff suppressed because it is too large Load Diff
+450
View File
@@ -0,0 +1,450 @@
///////////////////////////////////////////////////////////////////////////////
//
// 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 <gsl/pointers> // for not_null, operator<, operator<=, operator>
#include <gtest/gtest.h>
#include <type_traits> // for declval
#include "deathTestCommon.h"
using namespace gsl;
#if __cplusplus >= 201703l
using std::void_t;
#else // __cplusplus >= 201703l
template <class...>
using void_t = void;
#endif // __cplusplus < 201703l
// stand-in for a user-defined ref-counted class
template <typename T>
struct RefCounted
{
RefCounted(T* p) : p_(p) {}
operator T*() { return p_; }
T* p_;
};
namespace
{
GSL_SUPPRESS(f.4)
bool helper(not_null<int*> p) { return *p == 12; }
GSL_SUPPRESS(f.4)
bool helper_const(not_null<const int*> p) { return *p == 12; }
GSL_SUPPRESS(f.4)
bool strict_helper(strict_not_null<int*> p) { return *p == 12; }
GSL_SUPPRESS(f.4)
bool strict_helper_const(strict_not_null<const int*> p) { return *p == 12; }
int* return_pointer() { return nullptr; }
} // namespace
template <typename U, typename = void>
static constexpr bool CtorCompilesFor_A = false;
template <typename U>
static constexpr bool
CtorCompilesFor_A<U, void_t<decltype(gsl::strict_not_null<void*>{std::declval<U>()})>> = true;
template <typename U, int N, typename = void>
static constexpr bool CtorCompilesFor_B = false;
template <typename U, int N>
static constexpr bool CtorCompilesFor_B<U, N, void_t<decltype(gsl::strict_not_null<U>{N})>> = true;
template <typename U, typename = void>
static constexpr bool DefaultCtorCompilesFor = false;
template <typename U>
static constexpr bool DefaultCtorCompilesFor<U, void_t<decltype(gsl::strict_not_null<U>{})>> = true;
template <typename U, typename = void>
static constexpr bool CtorCompilesFor_C = false;
template <typename U>
static constexpr bool CtorCompilesFor_C<
U, void_t<decltype(gsl::strict_not_null<U*>{std::declval<std::unique_ptr<U>>()})>> = true;
TEST(strict_notnull_tests, TestStrictNotNullConstructors)
{
{
static_assert(CtorCompilesFor_A<void*>, "CtorCompilesFor_A<void*>");
static_assert(!CtorCompilesFor_A<std::nullptr_t>, "!CtorCompilesFor_A<std::nullptr_t>");
static_assert(!CtorCompilesFor_B<void*, 0>, "!CtorCompilesFor_B<void*, 0>");
static_assert(!DefaultCtorCompilesFor<void*>, "!DefaultCtorCompilesFor<void*>");
static_assert(!CtorCompilesFor_C<int>, "CtorCompilesFor_C<int>");
#ifdef CONFIRM_COMPILATION_ERRORS
// Forbid non-nullptr assignable types
strict_not_null<std::vector<int>> f(std::vector<int>{1});
strict_not_null<int> z(10);
strict_not_null<std::vector<int>> 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<int>(&i);
strict_not_null<int*> p(rp);
EXPECT_TRUE(p.get() == &i);
strict_not_null<std::shared_ptr<int>> x(
std::make_shared<int>(10)); // shared_ptr<int> is nullptr assignable
int* pi = nullptr;
EXPECT_DEATH((strict_not_null<decltype(pi)>(pi)), expected);
}
{
// from unique pointer
strict_not_null<std::unique_ptr<int>> x(
std::make_unique<int>(10)); // unique_ptr<int> is nullptr assignable
EXPECT_DEATH((strict_not_null<std::unique_ptr<int>>(std::unique_ptr<int>{})), expected);
}
{
// from pointer to local
int t = 42;
strict_not_null<int*> 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<int*> 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<const int*> 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<const int*>{cp};
EXPECT_TRUE(*x == 42);
}
{
// from returned pointer
EXPECT_DEATH(helper(return_pointer()), expected);
EXPECT_DEATH(helper_const(return_pointer()), expected);
}
}
template <typename U, typename = void>
static constexpr bool StrictHelperCompilesFor = false;
template <typename U>
static constexpr bool
StrictHelperCompilesFor<U, void_t<decltype(strict_helper(std::declval<U>()))>> = true;
template <typename U, typename = void>
static constexpr bool StrictHelperConstCompilesFor = false;
template <typename U>
static constexpr bool
StrictHelperConstCompilesFor<U, void_t<decltype(strict_helper_const(std::declval<U>()))>> =
true;
template <typename U, typename = void>
static constexpr bool HelperCompilesFor = false;
template <typename U>
static constexpr bool HelperCompilesFor<U, void_t<decltype(helper(std::declval<U>()))>> = true;
TEST(strict_notnull_tests, TestStrictNotNull)
{
{
// raw ptr <-> strict_not_null
int x = 42;
#ifdef CONFIRM_COMPILATION_ERRORS
strict_not_null<int*> snn = &x;
#endif
static_assert(!StrictHelperCompilesFor<int*>, "!StrictHelperCompilesFor<int*>");
static_assert(!StrictHelperConstCompilesFor<int*>, "!StrictHelperCompilesFor<int*>");
const strict_not_null<int*> snn1{&x};
static_assert(StrictHelperCompilesFor<const strict_not_null<int*>>,
"StrictHelperCompilesFor<const strict_not_null<int*>>");
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<int*> snn = &x;
#endif
static_assert(!StrictHelperCompilesFor<const int*>, "!StrictHelperFor<const int*>");
static_assert(!StrictHelperConstCompilesFor<const int*>,
"!StrictHelperCompilesFor<const int*>");
const strict_not_null<const int*> snn1{&x};
static_assert(!HelperCompilesFor<const strict_not_null<const int*>>,
"!HelperCompilesFor<const strict_not_null<const int*>>");
static_assert(StrictHelperConstCompilesFor<const strict_not_null<const int*>>,
"StrictHelperCompilesFor<const strict_not_null<const int*>>");
helper_const(snn1);
EXPECT_TRUE(*snn1 == 42);
}
{
// strict_not_null -> strict_not_null
int x = 42;
strict_not_null<int*> snn1{&x};
const strict_not_null<int*> 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<const int*> snn1{&x};
const strict_not_null<const int*> snn2{&x};
static_assert(!StrictHelperCompilesFor<strict_not_null<const int*>>,
"!StrictHelperCompilesFor<strict_not_null<const int*>>");
strict_helper_const(snn1);
strict_helper_const(snn2);
EXPECT_TRUE(snn1 == snn2);
}
{
// strict_not_null -> not_null
int x = 42;
strict_not_null<int*> snn{&x};
const not_null<int*> nn1 = snn;
const not_null<int*> 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<const int*> snn{&x};
const not_null<const int*> nn1 = snn;
const not_null<const int*> nn2{snn};
static_assert(!HelperCompilesFor<strict_not_null<const int*>>,
"!HelperCompilesFor<strict_not_null<const int*>>");
helper_const(snn);
EXPECT_TRUE(snn == nn1);
EXPECT_TRUE(snn == nn2);
}
{
// not_null -> strict_not_null
int x = 42;
not_null<int*> nn{&x};
const strict_not_null<int*> snn1{nn};
const strict_not_null<int*> snn2{nn};
strict_helper(nn);
strict_helper_const(nn);
EXPECT_TRUE(snn1 == nn);
EXPECT_TRUE(snn2 == nn);
std::hash<strict_not_null<int*>> hash_snn;
std::hash<not_null<int*>> 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<const int*> nn{&x};
const strict_not_null<const int*> snn1{nn};
const strict_not_null<const int*> snn2{nn};
static_assert(!StrictHelperCompilesFor<not_null<const int*>>,
"!StrictHelperCompilesFor<not_null<const int*>>");
strict_helper_const(nn);
EXPECT_TRUE(snn1 == nn);
EXPECT_TRUE(snn2 == nn);
std::hash<strict_not_null<const int*>> hash_snn;
std::hash<not_null<const int*>> 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<gsl::strict_not_null<int*>::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<strict_not_null<const int*>>,
"!HelperCompilesFor<strict_not_null<const int*>>");
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<strict_not_null<const int*>>,
"!HelperCompilesFor<strict_not_null<const int*>>");
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)
-796
View File
@@ -1,796 +0,0 @@
///////////////////////////////////////////////////////////////////////////////
//
// 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.
//
///////////////////////////////////////////////////////////////////////////////
#ifdef _MSC_VER
// blanket turn off warnings from CppCoreCheck from catch
// so people aren't annoyed by them when running the tool.
#pragma warning(disable : 26440 26426) // from catch
#endif
#include <catch/catch.hpp> // for AssertionHandler, StringRef, CHECK, CHECK...
#include <gsl/gsl_byte> // for byte
#include <gsl/gsl_util> // for narrow_cast
#include <gsl/multi_span> // for strided_span, index, multi_span, strided_...
#include <iostream> // for size_t
#include <iterator> // for begin, end
#include <numeric> // for iota
#include <type_traits> // for integral_constant<>::value, is_convertible
#include <vector> // for vector
namespace gsl {
struct fail_fast;
} // namespace gsl
using namespace std;
using namespace gsl;
namespace
{
struct BaseClass
{
};
struct DerivedClass : BaseClass
{
};
}
TEST_CASE("span_section_test")
{
int a[30][4][5];
const auto av = as_multi_span(a);
const auto sub = av.section({15, 0, 0}, gsl::multi_span_index<3>{2, 2, 2});
const auto subsub = sub.section({1, 0, 0}, gsl::multi_span_index<3>{1, 1, 1});
(void) subsub;
}
TEST_CASE("span_section")
{
std::vector<int> data(5 * 10);
std::iota(begin(data), end(data), 0);
const multi_span<int, 5, 10> av = as_multi_span(multi_span<int>{data}, dim<5>(), dim<10>());
const strided_span<int, 2> av_section_1 = av.section({1, 2}, {3, 4});
CHECK(!av_section_1.empty());
CHECK((av_section_1[{0, 0}] == 12));
CHECK((av_section_1[{0, 1}] == 13));
CHECK((av_section_1[{1, 0}] == 22));
CHECK((av_section_1[{2, 3}] == 35));
const strided_span<int, 2> av_section_2 = av_section_1.section({1, 2}, {2, 2});
CHECK(!av_section_2.empty());
CHECK((av_section_2[{0, 0}] == 24));
CHECK((av_section_2[{0, 1}] == 25));
CHECK((av_section_2[{1, 0}] == 34));
}
GSL_SUPPRESS(con.4) // NO-FORMAT: attribute
TEST_CASE("strided_span_constructors")
{
// Check stride constructor
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
const int carr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
strided_span<int, 1> sav1{arr, {{9}, {1}}}; // T -> T
CHECK(sav1.bounds().index_bounds() == multi_span_index<1>{9});
CHECK(sav1.bounds().stride() == 1);
CHECK((sav1[0] == 1 && sav1[8] == 9));
strided_span<const int, 1> sav2{carr, {{4}, {2}}}; // const T -> const T
CHECK(sav2.bounds().index_bounds() == multi_span_index<1>{4});
CHECK(sav2.bounds().strides() == multi_span_index<1>{2});
CHECK((sav2[0] == 1 && sav2[3] == 7));
strided_span<int, 2> sav3{arr, {{2, 2}, {6, 2}}}; // T -> const T
CHECK((sav3.bounds().index_bounds() == multi_span_index<2>{2, 2}));
CHECK((sav3.bounds().strides() == multi_span_index<2>{6, 2}));
CHECK((sav3[{0, 0}] == 1 && sav3[{0, 1}] == 3 && sav3[{1, 0}] == 7));
}
// Check multi_span constructor
{
int arr[] = {1, 2};
// From non-cv-qualified source
{
const multi_span<int> src = arr;
strided_span<int, 1> sav{src, {2, 1}};
CHECK(sav.bounds().index_bounds() == multi_span_index<1>{2});
CHECK(sav.bounds().strides() == multi_span_index<1>{1});
CHECK(sav[1] == 2);
#if _MSC_VER > 1800
// strided_span<const int, 1> sav_c{ {src}, {2, 1} };
strided_span<const int, 1> sav_c{multi_span<const int>{src},
strided_bounds<1>{2, 1}};
#else
strided_span<const int, 1> sav_c{multi_span<const int>{src},
strided_bounds<1>{2, 1}};
#endif
CHECK(sav_c.bounds().index_bounds() == multi_span_index<1>{2});
CHECK(sav_c.bounds().strides() == multi_span_index<1>{1});
CHECK(sav_c[1] == 2);
#if _MSC_VER > 1800
strided_span<volatile int, 1> sav_v{src, {2, 1}};
#else
strided_span<volatile int, 1> sav_v{multi_span<volatile int>{src},
strided_bounds<1>{2, 1}};
#endif
CHECK(sav_v.bounds().index_bounds() == multi_span_index<1>{2});
CHECK(sav_v.bounds().strides() == multi_span_index<1>{1});
CHECK(sav_v[1] == 2);
#if _MSC_VER > 1800
strided_span<const volatile int, 1> sav_cv{src, {2, 1}};
#else
strided_span<const volatile int, 1> sav_cv{multi_span<const volatile int>{src},
strided_bounds<1>{2, 1}};
#endif
CHECK(sav_cv.bounds().index_bounds() == multi_span_index<1>{2});
CHECK(sav_cv.bounds().strides() == multi_span_index<1>{1});
CHECK(sav_cv[1] == 2);
}
// From const-qualified source
{
const multi_span<const int> src{arr};
strided_span<const int, 1> sav_c{src, {2, 1}};
CHECK(sav_c.bounds().index_bounds() == multi_span_index<1>{2});
CHECK(sav_c.bounds().strides() == multi_span_index<1>{1});
CHECK(sav_c[1] == 2);
#if _MSC_VER > 1800
strided_span<const volatile int, 1> sav_cv{src, {2, 1}};
#else
strided_span<const volatile int, 1> sav_cv{multi_span<const volatile int>{src},
strided_bounds<1>{2, 1}};
#endif
CHECK(sav_cv.bounds().index_bounds() == multi_span_index<1>{2});
CHECK(sav_cv.bounds().strides() == multi_span_index<1>{1});
CHECK(sav_cv[1] == 2);
}
// From volatile-qualified source
{
const multi_span<volatile int> src{arr};
strided_span<volatile int, 1> sav_v{src, {2, 1}};
CHECK(sav_v.bounds().index_bounds() == multi_span_index<1>{2});
CHECK(sav_v.bounds().strides() == multi_span_index<1>{1});
CHECK(sav_v[1] == 2);
#if _MSC_VER > 1800
strided_span<const volatile int, 1> sav_cv{src, {2, 1}};
#else
strided_span<const volatile int, 1> sav_cv{multi_span<const volatile int>{src},
strided_bounds<1>{2, 1}};
#endif
CHECK(sav_cv.bounds().index_bounds() == multi_span_index<1>{2});
CHECK(sav_cv.bounds().strides() == multi_span_index<1>{1});
CHECK(sav_cv[1] == 2);
}
// From cv-qualified source
{
const multi_span<const volatile int> src{arr};
strided_span<const volatile int, 1> sav_cv{src, {2, 1}};
CHECK(sav_cv.bounds().index_bounds() == multi_span_index<1>{2});
CHECK(sav_cv.bounds().strides() == multi_span_index<1>{1});
CHECK(sav_cv[1] == 2);
}
}
// Check const-casting constructor
{
int arr[2] = {4, 5};
const multi_span<int, 2> av(arr, 2);
multi_span<const int, 2> av2{av};
CHECK(av2[1] == 5);
static_assert(
std::is_convertible<const multi_span<int, 2>, multi_span<const int, 2>>::value,
"ctor is not implicit!");
const strided_span<int, 1> src{arr, {2, 1}};
strided_span<const int, 1> sav{src};
CHECK(sav.bounds().index_bounds() == multi_span_index<1>{2});
CHECK(sav.bounds().stride() == 1);
CHECK(sav[1] == 5);
static_assert(
std::is_convertible<const strided_span<int, 1>, strided_span<const int, 1>>::value,
"ctor is not implicit!");
}
// Check copy constructor
{
int arr1[2] = {3, 4};
const strided_span<int, 1> src1{arr1, {2, 1}};
strided_span<int, 1> sav1{src1};
CHECK(sav1.bounds().index_bounds() == multi_span_index<1>{2});
CHECK(sav1.bounds().stride() == 1);
CHECK(sav1[0] == 3);
int arr2[6] = {1, 2, 3, 4, 5, 6};
const strided_span<const int, 2> src2{arr2, {{3, 2}, {2, 1}}};
strided_span<const int, 2> sav2{src2};
CHECK((sav2.bounds().index_bounds() == multi_span_index<2>{3, 2}));
CHECK((sav2.bounds().strides() == multi_span_index<2>{2, 1}));
CHECK((sav2[{0, 0}] == 1 && sav2[{2, 0}] == 5));
}
// Check const-casting assignment operator
{
int arr1[2] = {1, 2};
int arr2[6] = {3, 4, 5, 6, 7, 8};
const strided_span<int, 1> src{arr1, {{2}, {1}}};
strided_span<const int, 1> sav{arr2, {{3}, {2}}};
strided_span<const int, 1>& sav_ref = (sav = src);
CHECK(sav.bounds().index_bounds() == multi_span_index<1>{2});
CHECK(sav.bounds().strides() == multi_span_index<1>{1});
CHECK(sav[0] == 1);
CHECK(&sav_ref == &sav);
}
// Check copy assignment operator
{
int arr1[2] = {3, 4};
int arr1b[1] = {0};
const strided_span<int, 1> src1{arr1, {2, 1}};
strided_span<int, 1> sav1{arr1b, {1, 1}};
strided_span<int, 1>& sav1_ref = (sav1 = src1);
CHECK(sav1.bounds().index_bounds() == multi_span_index<1>{2});
CHECK(sav1.bounds().strides() == multi_span_index<1>{1});
CHECK(sav1[0] == 3);
CHECK(&sav1_ref == &sav1);
const int arr2[6] = {1, 2, 3, 4, 5, 6};
const int arr2b[1] = {0};
const strided_span<const int, 2> src2{arr2, {{3, 2}, {2, 1}}};
strided_span<const int, 2> sav2{arr2b, {{1, 1}, {1, 1}}};
strided_span<const int, 2>& sav2_ref = (sav2 = src2);
CHECK((sav2.bounds().index_bounds() == multi_span_index<2>{3, 2}));
CHECK((sav2.bounds().strides() == multi_span_index<2>{2, 1}));
CHECK((sav2[{0, 0}] == 1 && sav2[{2, 0}] == 5));
CHECK(&sav2_ref == &sav2);
}
}
GSL_SUPPRESS(con.4) // NO-FORMAT: attribute
TEST_CASE("strided_span_slice")
{
std::vector<int> data(5 * 10);
std::iota(begin(data), end(data), 0);
const multi_span<int, 5, 10> src =
as_multi_span(multi_span<int>{data}, dim<5>(), dim<10>());
const strided_span<int, 2> sav{src, {{5, 10}, {10, 1}}};
#ifdef CONFIRM_COMPILATION_ERRORS
const strided_span<const int, 2> csav{{src}, {{5, 10}, {10, 1}}};
#endif
const strided_span<const int, 2> csav{multi_span<const int, 5, 10>{src},
{{5, 10}, {10, 1}}};
strided_span<int, 1> sav_sl = sav[2];
CHECK(sav_sl[0] == 20);
CHECK(sav_sl[9] == 29);
strided_span<const int, 1> csav_sl = sav[3];
CHECK(csav_sl[0] == 30);
CHECK(csav_sl[9] == 39);
CHECK(sav[4][0] == 40);
CHECK(sav[4][9] == 49);
}
GSL_SUPPRESS(con.4) // NO-FORMAT: attribute
TEST_CASE("strided_span_column_major")
{
// strided_span may be used to accommodate more peculiar
// use cases, such as column-major multidimensional array
// (aka. "FORTRAN" layout).
int cm_array[3 * 5] = {1, 4, 7, 10, 13, 2, 5, 8, 11, 14, 3, 6, 9, 12, 15};
strided_span<int, 2> cm_sav{cm_array, {{5, 3}, {1, 5}}};
// Accessing elements
CHECK((cm_sav[{0, 0}] == 1));
CHECK((cm_sav[{0, 1}] == 2));
CHECK((cm_sav[{1, 0}] == 4));
CHECK((cm_sav[{4, 2}] == 15));
// Slice
strided_span<int, 1> cm_sl = cm_sav[3];
CHECK(cm_sl[0] == 10);
CHECK(cm_sl[1] == 11);
CHECK(cm_sl[2] == 12);
// Section
strided_span<int, 2> cm_sec = cm_sav.section({2, 1}, {3, 2});
CHECK((cm_sec.bounds().index_bounds() == multi_span_index<2>{3, 2}));
CHECK((cm_sec[{0, 0}] == 8));
CHECK((cm_sec[{0, 1}] == 9));
CHECK((cm_sec[{1, 0}] == 11));
CHECK((cm_sec[{2, 1}] == 15));
}
GSL_SUPPRESS(con.4) // NO-FORMAT: attribute
TEST_CASE("strided_span_bounds")
{
int arr[] = {0, 1, 2, 3};
multi_span<int> av(arr);
{
// incorrect sections
CHECK_THROWS_AS(av.section(0, 0)[0], fail_fast);
CHECK_THROWS_AS(av.section(1, 0)[0], fail_fast);
CHECK_THROWS_AS(av.section(1, 1)[1], fail_fast);
CHECK_THROWS_AS(av.section(2, 5), fail_fast);
CHECK_THROWS_AS(av.section(5, 2), fail_fast);
CHECK_THROWS_AS(av.section(5, 0), fail_fast);
CHECK_THROWS_AS(av.section(0, 5), fail_fast);
CHECK_THROWS_AS(av.section(5, 5), fail_fast);
}
{
// zero stride
strided_span<int, 1> sav{av, {{4}, {}}};
CHECK(sav[0] == 0);
CHECK(sav[3] == 0);
CHECK_THROWS_AS(sav[4], fail_fast);
}
{
// zero extent
strided_span<int, 1> sav{av, {{}, {1}}};
CHECK_THROWS_AS(sav[0], fail_fast);
}
{
// zero extent and stride
strided_span<int, 1> sav{av, {{}, {}}};
CHECK_THROWS_AS(sav[0], fail_fast);
}
{
// strided array ctor with matching strided bounds
strided_span<int, 1> sav{arr, {4, 1}};
CHECK(sav.bounds().index_bounds() == multi_span_index<1>{4});
CHECK(sav[3] == 3);
CHECK_THROWS_AS(sav[4], fail_fast);
}
{
// strided array ctor with smaller strided bounds
strided_span<int, 1> sav{arr, {2, 1}};
CHECK(sav.bounds().index_bounds() == multi_span_index<1>{2});
CHECK(sav[1] == 1);
CHECK_THROWS_AS(sav[2], fail_fast);
}
{
// strided array ctor with fitting irregular bounds
strided_span<int, 1> sav{arr, {2, 3}};
CHECK(sav.bounds().index_bounds() == multi_span_index<1>{2});
CHECK(sav[0] == 0);
CHECK(sav[1] == 3);
CHECK_THROWS_AS(sav[2], fail_fast);
}
{
// bounds cross data boundaries - from static arrays
CHECK_THROWS_AS((strided_span<int, 1>{arr, {3, 2}}), fail_fast);
CHECK_THROWS_AS((strided_span<int, 1>{arr, {3, 3}}), fail_fast);
CHECK_THROWS_AS((strided_span<int, 1>{arr, {4, 5}}), fail_fast);
CHECK_THROWS_AS((strided_span<int, 1>{arr, {5, 1}}), fail_fast);
CHECK_THROWS_AS((strided_span<int, 1>{arr, {5, 5}}), fail_fast);
}
{
// bounds cross data boundaries - from array view
CHECK_THROWS_AS((strided_span<int, 1>{av, {3, 2}}), fail_fast);
CHECK_THROWS_AS((strided_span<int, 1>{av, {3, 3}}), fail_fast);
CHECK_THROWS_AS((strided_span<int, 1>{av, {4, 5}}), fail_fast);
CHECK_THROWS_AS((strided_span<int, 1>{av, {5, 1}}), fail_fast);
CHECK_THROWS_AS((strided_span<int, 1>{av, {5, 5}}), fail_fast);
}
{
// bounds cross data boundaries - from dynamic arrays
CHECK_THROWS_AS((strided_span<int, 1>{av.data(), 4, {3, 2}}), fail_fast);
CHECK_THROWS_AS((strided_span<int, 1>{av.data(), 4, {3, 3}}), fail_fast);
CHECK_THROWS_AS((strided_span<int, 1>{av.data(), 4, {4, 5}}), fail_fast);
CHECK_THROWS_AS((strided_span<int, 1>{av.data(), 4, {5, 1}}), fail_fast);
CHECK_THROWS_AS((strided_span<int, 1>{av.data(), 4, {5, 5}}), fail_fast);
CHECK_THROWS_AS((strided_span<int, 1>{av.data(), 2, {2, 2}}), fail_fast);
}
#ifdef CONFIRM_COMPILATION_ERRORS
{
strided_span<int, 1> sav0{av.data(), {3, 2}};
strided_span<int, 1> sav1{arr, {1}};
strided_span<int, 1> sav2{arr, {1, 1, 1}};
strided_span<int, 1> sav3{av, {1}};
strided_span<int, 1> sav4{av, {1, 1, 1}};
strided_span<int, 2> sav5{av.as_multi_span(dim<2>(), dim<2>()), {1}};
strided_span<int, 2> sav6{av.as_multi_span(dim<2>(), dim<2>()), {1, 1, 1}};
strided_span<int, 2> sav7{av.as_multi_span(dim<2>(), dim<2>()),
{{1, 1}, {1, 1}, {1, 1}}};
multi_span_index<1> index{0, 1};
strided_span<int, 1> sav8{arr, {1, {1, 1}}};
strided_span<int, 1> sav9{arr, {{1, 1}, {1, 1}}};
strided_span<int, 1> sav10{av, {1, {1, 1}}};
strided_span<int, 1> sav11{av, {{1, 1}, {1, 1}}};
strided_span<int, 2> sav12{av.as_multi_span(dim<2>(), dim<2>()), {{1}, {1}}};
strided_span<int, 2> sav13{av.as_multi_span(dim<2>(), dim<2>()), {{1}, {1, 1, 1}}};
strided_span<int, 2> sav14{av.as_multi_span(dim<2>(), dim<2>()), {{1, 1, 1}, {1}}};
}
#endif
}
GSL_SUPPRESS(con.4) // NO-FORMAT: attribute
TEST_CASE("strided_span_type_conversion")
{
int arr[] = {0, 1, 2, 3};
multi_span<int> av(arr);
{
strided_span<int, 1> sav{av.data(), av.size(), {av.size() / 2, 2}};
#ifdef CONFIRM_COMPILATION_ERRORS
strided_span<long, 1> lsav1 = sav.as_strided_span<long, 1>();
#endif
}
{
strided_span<int, 1> sav{av, {av.size() / 2, 2}};
#ifdef CONFIRM_COMPILATION_ERRORS
strided_span<long, 1> lsav1 = sav.as_strided_span<long, 1>();
#endif
}
multi_span<const byte, dynamic_range> bytes = as_bytes(av);
// retype strided array with regular strides - from raw data
{
strided_bounds<2> bounds{{2, bytes.size() / 4}, {bytes.size() / 2, 1}};
strided_span<const byte, 2> sav2{bytes.data(), bytes.size(), bounds};
strided_span<const int, 2> sav3 = sav2.as_strided_span<const int>();
CHECK(sav3[0][0] == 0);
CHECK(sav3[1][0] == 2);
CHECK_THROWS_AS(sav3[1][1], fail_fast);
CHECK_THROWS_AS(sav3[0][1], fail_fast);
}
// retype strided array with regular strides - from multi_span
{
strided_bounds<2> bounds{{2, bytes.size() / 4}, {bytes.size() / 2, 1}};
multi_span<const byte, 2, dynamic_range> bytes2 =
as_multi_span(bytes, dim<2>(), dim(bytes.size() / 2));
strided_span<const byte, 2> sav2{bytes2, bounds};
strided_span<int, 2> sav3 = sav2.as_strided_span<int>();
CHECK(sav3[0][0] == 0);
CHECK(sav3[1][0] == 2);
CHECK_THROWS_AS(sav3[1][1], fail_fast);
CHECK_THROWS_AS(sav3[0][1], fail_fast);
}
// retype strided array with not enough elements - last dimension of the array is too small
{
strided_bounds<2> bounds{{4, 2}, {4, 1}};
multi_span<const byte, 2, dynamic_range> bytes2 =
as_multi_span(bytes, dim<2>(), dim(bytes.size() / 2));
strided_span<const byte, 2> sav2{bytes2, bounds};
CHECK_THROWS_AS(sav2.as_strided_span<int>(), fail_fast);
}
// retype strided array with not enough elements - strides are too small
{
strided_bounds<2> bounds{{4, 2}, {2, 1}};
multi_span<const byte, 2, dynamic_range> bytes2 =
as_multi_span(bytes, dim<2>(), dim(bytes.size() / 2));
strided_span<const byte, 2> sav2{bytes2, bounds};
CHECK_THROWS_AS(sav2.as_strided_span<int>(), fail_fast);
}
// retype strided array with not enough elements - last dimension does not divide by the new
// typesize
{
strided_bounds<2> bounds{{2, 6}, {4, 1}};
multi_span<const byte, 2, dynamic_range> bytes2 =
as_multi_span(bytes, dim<2>(), dim(bytes.size() / 2));
strided_span<const byte, 2> sav2{bytes2, bounds};
CHECK_THROWS_AS(sav2.as_strided_span<int>(), fail_fast);
}
// retype strided array with not enough elements - strides does not divide by the new
// typesize
{
strided_bounds<2> bounds{{2, 1}, {6, 1}};
multi_span<const byte, 2, dynamic_range> bytes2 =
as_multi_span(bytes, dim<2>(), dim(bytes.size() / 2));
strided_span<const byte, 2> sav2{bytes2, bounds};
CHECK_THROWS_AS(sav2.as_strided_span<int>(), fail_fast);
}
// retype strided array with irregular strides - from raw data
{
strided_bounds<1> bounds{bytes.size() / 2, 2};
strided_span<const byte, 1> sav2{bytes.data(), bytes.size(), bounds};
CHECK_THROWS_AS(sav2.as_strided_span<int>(), fail_fast);
}
// retype strided array with irregular strides - from multi_span
{
strided_bounds<1> bounds{bytes.size() / 2, 2};
strided_span<const byte, 1> sav2{bytes, bounds};
CHECK_THROWS_AS(sav2.as_strided_span<int>(), fail_fast);
}
}
GSL_SUPPRESS(con.4) // NO-FORMAT: attribute
GSL_SUPPRESS(bounds.4) // NO-FORMAT: attribute
TEST_CASE("empty_strided_spans")
{
{
multi_span<int, 0> empty_av(nullptr);
strided_span<int, 1> empty_sav{empty_av, {0, 1}};
CHECK(empty_sav.bounds().index_bounds() == multi_span_index<1>{0});
CHECK(empty_sav.empty());
CHECK_THROWS_AS(empty_sav[0], fail_fast);
CHECK_THROWS_AS(empty_sav.begin()[0], fail_fast);
CHECK_THROWS_AS(empty_sav.cbegin()[0], fail_fast);
for (const auto& v : empty_sav) {
(void) v;
CHECK(false);
}
}
{
strided_span<int, 1> empty_sav{nullptr, 0, {0, 1}};
CHECK(empty_sav.bounds().index_bounds() == multi_span_index<1>{0});
CHECK_THROWS_AS(empty_sav[0], fail_fast);
CHECK_THROWS_AS(empty_sav.begin()[0], fail_fast);
CHECK_THROWS_AS(empty_sav.cbegin()[0], fail_fast);
for (const auto& v : empty_sav) {
(void) v;
CHECK(false);
}
}
}
GSL_SUPPRESS(con.4) // NO-FORMAT: attribute
GSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute
void iterate_every_other_element(multi_span<int, dynamic_range> av)
{
// pick every other element
auto length = av.size() / 2;
#if _MSC_VER > 1800
auto bounds = strided_bounds<1>({length}, {2});
#else
auto bounds = strided_bounds<1>(multi_span_index<1>{length}, multi_span_index<1>{2});
#endif
strided_span<int, 1> strided(&av.data()[1], av.size() - 1, bounds);
CHECK(strided.size() == length);
CHECK(strided.bounds().index_bounds()[0] == length);
for (auto i = 0; i < strided.size(); ++i) {
CHECK(strided[i] == av[2 * i + 1]);
}
int idx = 0;
for (auto num : strided) {
CHECK(num == av[2 * idx + 1]);
idx++;
}
}
GSL_SUPPRESS(con.4) // NO-FORMAT: attribute
TEST_CASE("strided_span_section_iteration")
{
int arr[8] = {4, 0, 5, 1, 6, 2, 7, 3};
// static bounds
{
multi_span<int, 8> av(arr, 8);
iterate_every_other_element(av);
}
// dynamic bounds
{
multi_span<int, dynamic_range> av(arr, 8);
iterate_every_other_element(av);
}
}
GSL_SUPPRESS(con.4) // NO-FORMAT: attribute
GSL_SUPPRESS(r.11) // NO-FORMAT: attribute
GSL_SUPPRESS(r.3) // NO-FORMAT: attribute
GSL_SUPPRESS(r.5) // NO-FORMAT: attribute
GSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute
TEST_CASE("dynamic_strided_span_section_iteration")
{
auto arr = new int[8];
for (int i = 0; i < 4; ++i) {
arr[2 * i] = 4 + i;
arr[2 * i + 1] = i;
}
auto av = as_multi_span(arr, 8);
iterate_every_other_element(av);
delete[] arr;
}
GSL_SUPPRESS(con.4) // NO-FORMAT: attribute
GSL_SUPPRESS(bounds.4) // NO-FORMAT: attribute
GSL_SUPPRESS(bounds.2) // NO-FORMAT: attribute // TODO: does not work
void iterate_second_slice(multi_span<int, dynamic_range, dynamic_range, dynamic_range> av)
{
const int expected[6] = {2, 3, 10, 11, 18, 19};
auto section = av.section({0, 1, 0}, {3, 1, 2});
for (auto i = 0; i < section.extent<0>(); ++i) {
for (auto j = 0; j < section.extent<1>(); ++j)
for (auto k = 0; k < section.extent<2>(); ++k) {
auto idx = multi_span_index<3>{i, j, k}; // avoid braces in the CHECK macro
CHECK(section[idx] == expected[2 * i + 2 * j + k]);
}
}
for (auto i = 0; i < section.extent<0>(); ++i) {
for (auto j = 0; j < section.extent<1>(); ++j)
for (auto k = 0; k < section.extent<2>(); ++k)
CHECK(section[i][j][k] == expected[2 * i + 2 * j + k]);
}
int i = 0;
for (const auto num : section) {
CHECK(num == expected[i]);
i++;
}
}
GSL_SUPPRESS(con.4) // NO-FORMAT: attribute
GSL_SUPPRESS(bounds.4) // NO-FORMAT: attribute
GSL_SUPPRESS(bounds.2) // NO-FORMAT: attribute
TEST_CASE("strided_span_section_iteration_3d")
{
int arr[3][4][2]{};
for (auto i = 0; i < 3; ++i) {
for (auto j = 0; j < 4; ++j)
for (auto k = 0; k < 2; ++k) arr[i][j][k] = 8 * i + 2 * j + k;
}
{
multi_span<int, 3, 4, 2> av = arr;
iterate_second_slice(av);
}
}
GSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute
GSL_SUPPRESS(con.4) // NO-FORMAT: attribute
GSL_SUPPRESS(r.3) // NO-FORMAT: attribute
GSL_SUPPRESS(r.5) // NO-FORMAT: attribute
GSL_SUPPRESS(r.11) // NO-FORMAT: attribute
TEST_CASE("dynamic_strided_span_section_iteration_3d")
{
const auto height = 12, width = 2;
const auto size = height * width;
auto arr = new int[static_cast<std::size_t>(size)];
for (auto i = 0; i < size; ++i) {
arr[i] = i;
}
{
auto av = as_multi_span(as_multi_span(arr, 24), dim<3>(), dim<4>(), dim<2>());
iterate_second_slice(av);
}
{
auto av = as_multi_span(as_multi_span(arr, 24), dim(3), dim<4>(), dim<2>());
iterate_second_slice(av);
}
{
auto av = as_multi_span(as_multi_span(arr, 24), dim<3>(), dim(4), dim<2>());
iterate_second_slice(av);
}
{
auto av = as_multi_span(as_multi_span(arr, 24), dim<3>(), dim<4>(), dim(2));
iterate_second_slice(av);
}
delete[] arr;
}
GSL_SUPPRESS(con.4) // NO-FORMAT: attribute
GSL_SUPPRESS(bounds.4) // NO-FORMAT: attribute
GSL_SUPPRESS(bounds.2) // NO-FORMAT: attribute
TEST_CASE("strided_span_conversion")
{
// get an multi_span of 'c' values from the list of X's
struct X
{
int a;
int b;
int c;
};
X arr[4] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {9, 10, 11}};
int s = sizeof(int) / sizeof(byte);
auto d2 = 3 * s;
auto d1 = narrow_cast<int>(sizeof(int)) * 12 / d2;
// convert to 4x12 array of bytes
auto av = as_multi_span(as_bytes(as_multi_span(&arr[0], 4)), dim(d1), dim(d2));
CHECK(av.bounds().index_bounds()[0] == 4);
CHECK(av.bounds().index_bounds()[1] == 12);
// get the last 4 columns
auto section = av.section({0, 2 * s}, {4, s}); // { { arr[0].c[0], arr[0].c[1], arr[0].c[2],
// arr[0].c[3] } , { arr[1].c[0], ... } , ...
// }
// convert to array 4x1 array of integers
auto cs = section.as_strided_span<int>(); // { { arr[0].c }, {arr[1].c } , ... }
CHECK(cs.bounds().index_bounds()[0] == 4);
CHECK(cs.bounds().index_bounds()[1] == 1);
// transpose to 1x4 array
strided_bounds<2> reverse_bounds{
{cs.bounds().index_bounds()[1], cs.bounds().index_bounds()[0]},
{cs.bounds().strides()[1], cs.bounds().strides()[0]}};
strided_span<int, 2> transposed{cs.data(), cs.bounds().total_size(), reverse_bounds};
// slice to get a one-dimensional array of c's
strided_span<int, 1> result = transposed[0];
CHECK(result.bounds().index_bounds()[0] == 4);
CHECK_THROWS_AS(result.bounds().index_bounds()[1], fail_fast);
int i = 0;
for (auto& num : result) {
CHECK(num == arr[i].c);
i++;
}
}
File diff suppressed because it is too large Load Diff
-26
View File
@@ -1,26 +0,0 @@
///////////////////////////////////////////////////////////////////////////////
//
// 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.
//
///////////////////////////////////////////////////////////////////////////////
#define CATCH_CONFIG_MAIN
#ifdef _MSC_VER
// blanket turn off warnings from CppCoreCheck from catch
// so people aren't annoyed by them when running the tool.
#pragma warning(disable : 26401 26409 26415 26418 26426 26429 26432 26433 26434 26435 26436 26439 26440 26443 26444 26446 26447 26451 26460 26461 26466 26472 26481 26482 26485 26492 26493 26494 26495 26496 26497) // from catch
#endif // _MSC_VER
#include <catch/catch.hpp>
+83 -47
View File
@@ -14,116 +14,152 @@
//
///////////////////////////////////////////////////////////////////////////////
#ifdef _MSC_VER
// blanket turn off warnings from CppCoreCheck from catch
// so people aren't annoyed by them when running the tool.
#pragma warning(disable : 26440 26426) // from catch
#include <gtest/gtest.h>
#endif
#include <catch/catch.hpp> // for AssertionHandler, StringRef, CHECK, TEST_...
#include <gsl/gsl_util> // for narrow, finally, narrow_cast, narrowing_e...
#include <algorithm> // for move
#include <algorithm> // for move
#include <complex>
#include <cstddef> // for std::ptrdiff_t
#include <cstdint> // for uint32_t, int32_t
#include <functional> // for reference_wrapper, _Bind_helper<>::type
#include <gsl/narrow> // for narrow, narrowing_error
#include <gsl/util> // finally, narrow_cast
#include <limits> // for numeric_limits
#include <stdint.h> // for uint32_t, int32_t
#include <type_traits> // for is_same
using namespace gsl;
TEST_CASE("sanity check for gsl::index typedef")
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<gsl::index, std::ptrdiff_t>::value,
"gsl::index represents wrong arithmetic type");
}
void f(int& i) { i += 1; }
TEST_CASE("finally_lambda")
TEST(utils_tests, finally_lambda)
{
int i = 0;
{
auto _ = finally([&]() { f(i); });
CHECK(i == 0);
EXPECT_TRUE(i == 0);
}
CHECK(i == 1);
EXPECT_TRUE(i == 1);
}
TEST_CASE("finally_lambda_move")
TEST(utils_tests, finally_lambda_move)
{
int i = 0;
{
auto _1 = finally([&]() { f(i); });
{
auto _2 = std::move(_1);
CHECK(i == 0);
EXPECT_TRUE(i == 0);
}
CHECK(i == 1);
EXPECT_TRUE(i == 1);
{
auto _2 = std::move(_1);
CHECK(i == 1);
EXPECT_TRUE(i == 1);
}
CHECK(i == 1);
EXPECT_TRUE(i == 1);
}
CHECK(i == 1);
EXPECT_TRUE(i == 1);
}
TEST_CASE("finally_function_with_bind")
TEST(utils_tests, finally_const_lvalue_lambda)
{
int i = 0;
{
auto _ = finally(std::bind(&f, std::ref(i)));
CHECK(i == 0);
const auto const_lvalue_lambda = [&]() { f(i); };
auto _ = finally(const_lvalue_lambda);
EXPECT_TRUE(i == 0);
}
CHECK(i == 1);
EXPECT_TRUE(i == 1);
}
int j = 0;
void g() { j += 1; }
TEST_CASE("finally_function_ptr")
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);
CHECK(j == 0);
EXPECT_TRUE(j == 0);
}
CHECK(j == 1);
EXPECT_TRUE(j == 1);
}
GSL_SUPPRESS(con.4) // NO-FORMAT: attribute
TEST_CASE("narrow_cast")
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<char>(n);
CHECK(c == 120);
EXPECT_TRUE(c == 120);
n = 300;
unsigned char uc = narrow_cast<unsigned char>(n);
CHECK(uc == 44);
EXPECT_TRUE(uc == 44);
}
GSL_SUPPRESS(con.5) // NO-FORMAT: attribute
TEST_CASE("narrow")
#ifndef GSL_KERNEL_MODE
TEST(utils_tests, narrow)
{
int n = 120;
const char c = narrow<char>(n);
CHECK(c == 120);
EXPECT_TRUE(c == 120);
n = 300;
CHECK_THROWS_AS(narrow<char>(n), narrowing_error);
EXPECT_THROW(narrow<char>(n), narrowing_error);
const auto int32_max = std::numeric_limits<int32_t>::max();
const auto int32_min = std::numeric_limits<int32_t>::min();
CHECK(narrow<uint32_t>(int32_t(0)) == 0);
CHECK(narrow<uint32_t>(int32_t(1)) == 1);
CHECK(narrow<uint32_t>(int32_max) == static_cast<uint32_t>(int32_max));
EXPECT_TRUE(narrow<uint32_t>(int32_t(0)) == 0);
EXPECT_TRUE(narrow<uint32_t>(int32_t(1)) == 1);
EXPECT_TRUE(narrow<uint32_t>(int32_max) == static_cast<uint32_t>(int32_max));
CHECK_THROWS_AS(narrow<uint32_t>(int32_t(-1)), narrowing_error);
CHECK_THROWS_AS(narrow<uint32_t>(int32_min), narrowing_error);
EXPECT_THROW(narrow<uint32_t>(int32_t(-1)), narrowing_error);
EXPECT_THROW(narrow<uint32_t>(int32_min), narrowing_error);
n = -42;
CHECK_THROWS_AS(narrow<unsigned>(n), narrowing_error);
EXPECT_THROW(narrow<unsigned>(n), narrowing_error);
EXPECT_TRUE(narrow<std::complex<float>>(std::complex<double>(4, 2)) ==
std::complex<float>(4, 2));
EXPECT_THROW(narrow<std::complex<float>>(std::complex<double>(4.2)), narrowing_error);
EXPECT_TRUE(narrow<int>(float(1)) == 1);
}
#endif // GSL_KERNEL_MODE